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-template-cpp/source/extensions/omni.example.cpp.usd/python/tests/test_usd_example.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.
##
import omni.kit.test
import omni.kit.app
import omni.usd
import omni.example.cpp.usd
class TestUsdExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Cache the example usd interface.
self.example_usd_interface = omni.example.cpp.usd.get_example_usd_interface()
# Open a new USD stage.
omni.usd.get_context().new_stage()
self.usd_stage = omni.usd.get_context().get_stage()
async def tearDown(self):
# Close the USD stage.
await omni.usd.get_context().close_stage_async()
self.usd_stage = None
# Clear the example usd interface.
self.example_usd_interface = None
async def test_create_prims(self):
self.example_usd_interface.create_prims()
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_0"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_1"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_2"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_3"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_4"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_5"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_6"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_7"))
self.assertTrue(self.usd_stage.GetPrimAtPath("/World/example_prim_8"))
self.assertFalse(self.usd_stage.GetPrimAtPath("/World/a_random_prim"))
| 1,982 | Python | 43.066666 | 85 | 0.709384 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usd/python/impl/example_usd_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.
##
import omni.ext
import omni.usd
from .._example_usd_bindings import *
# Global public interface object.
_example_usd_interface = None
# Public API.
def get_example_usd_interface() -> IExampleUsdInterface:
return _example_usd_interface
# Use the extension entry points to acquire and release the interface,
# and to subscribe to usd stage events.
class ExampleUsdExtension(omni.ext.IExt):
def on_startup(self):
# Acquire the example USD interface.
global _example_usd_interface
_example_usd_interface = acquire_example_usd_interface()
# Inform the C++ plugin if a USD stage is already open.
usd_context = omni.usd.get_context()
if usd_context.get_stage_state() == omni.usd.StageState.OPENED:
_example_usd_interface.on_default_usd_stage_changed(usd_context.get_stage_id())
# Subscribe to omni.usd stage events so we can inform the C++ plugin when a new stage opens.
self._stage_event_sub = usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.example.cpp.usd"
)
# Print some info about the stage from C++.
_example_usd_interface.print_stage_info()
# Create some example prims from C++.
_example_usd_interface.create_prims()
# Print some info about the stage from C++.
_example_usd_interface.print_stage_info()
# Animate the example prims from C++.
_example_usd_interface.start_timeline_animation()
def on_shutdown(self):
global _example_usd_interface
# Stop animating the example prims from C++.
_example_usd_interface.stop_timeline_animation()
# Remove the example prims from C++.
_example_usd_interface.remove_prims()
# Unsubscribe from omni.usd stage events.
self._stage_event_sub = None
# Release the example USD interface.
release_example_usd_interface(_example_usd_interface)
_example_usd_interface = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.OPENED):
_example_usd_interface.on_default_usd_stage_changed(omni.usd.get_context().get_stage_id())
elif event.type == int(omni.usd.StageEventType.CLOSED):
_example_usd_interface.on_default_usd_stage_changed(0)
| 2,793 | Python | 37.805555 | 102 | 0.686359 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/omni/example/python/usdrt/example_python_usdrt_extension.py | ## Copyright (c) 2023, 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 math
import random
from ctypes import alignment
import omni.ext
import omni.ui as ui
import omni.usd
from usdrt import Gf, Rt, Sdf, Usd, Vt
try:
wp = None
import warp as wp
wp.init()
@wp.kernel
def deform(positions: wp.array(dtype=wp.vec3), t: float):
tid = wp.tid()
x = positions[tid]
offset = -wp.sin(x[0])
scale = wp.sin(t) * 10.0
x = x + wp.vec3(0.0, offset * scale, 0.0)
positions[tid] = x
except ImportError:
pass
def get_selected_prim_path():
"""Return the path of the first selected prim"""
context = omni.usd.get_context()
selection = context.get_selection()
paths = selection.get_selected_prim_paths()
return None if not paths else paths[0]
def get_stage_id():
"""Return the stage Id of the current stage"""
context = omni.usd.get_context()
return context.get_stage_id()
def is_vtarray(obj):
"""Check if this is a VtArray type
In Python, each data type gets its own
VtArray class i.e. Vt.Float3Array etc.
so this helper identifies any of them.
"""
return hasattr(obj, "IsFabricData")
def condensed_vtarray_str(data):
"""Return a string representing VtArray data
Include at most 6 values, and the total items
in the array
"""
size = len(data)
if size > 6:
datastr = "[{}, {}, {}, .. {}, {}, {}] (size: {})".format(
data[0], data[1], data[2], data[-3], data[-2], data[-1], size
)
else:
datastr = "["
for i in range(size - 1):
datastr += str(data[i]) + ", "
datastr += str(data[-1]) + "]"
return datastr
def get_fabric_data_for_prim(stage_id, path):
"""Get the Fabric data for a path as a string"""
if path is None:
return "Nothing selected"
stage = Usd.Stage.Attach(stage_id)
# If a prim does not already exist in Fabric,
# it will be fetched from USD by simply creating the
# Usd.Prim object. At this time, only the attributes that have
# authored opinions will be fetch into Fabric.
prim = stage.GetPrimAtPath(Sdf.Path(path))
if not prim:
return f"Prim at path {path} is not in Fabric"
# This diverges a bit from USD - only attributes
# that exist in Fabric are returned by this API
attrs = prim.GetAttributes()
result = f"Fabric data for prim at path {path}\n\n\n"
for attr in attrs:
try:
data = attr.Get()
datastr = str(data)
if data is None:
datastr = "<no value>"
elif is_vtarray(data):
datastr = condensed_vtarray_str(data)
except TypeError:
# Some data types not yet supported in Python
datastr = "<no Python conversion>"
result += "{} ({}): {}\n".format(attr.GetName(), str(attr.GetTypeName().GetAsToken()), datastr)
return result
def apply_random_rotation(stage_id, path):
"""Apply a random world space rotation to a prim in Fabric"""
if path is None:
return "Nothing selected"
stage = Usd.Stage.Attach(stage_id)
prim = stage.GetPrimAtPath(Sdf.Path(path))
if not prim:
return f"Prim at path {path} is not in Fabric"
rtxformable = Rt.Xformable(prim)
if not rtxformable.HasWorldXform():
rtxformable.SetWorldXformFromUsd()
angle = random.random() * math.pi * 2
axis = Gf.Vec3f(random.random(), random.random(), random.random()).GetNormalized()
halfangle = angle / 2.0
shalfangle = math.sin(halfangle)
rotation = Gf.Quatf(math.cos(halfangle), axis[0] * shalfangle, axis[1] * shalfangle, axis[2] * shalfangle)
rtxformable.GetWorldOrientationAttr().Set(rotation)
return f"Set new world orientation on {path} to {rotation}"
def deform_mesh_with_warp(stage_id, path, time):
"""Use Warp to deform a Mesh prim"""
if path is None:
return "Nothing selected"
stage = Usd.Stage.Attach(stage_id)
prim = stage.GetPrimAtPath(Sdf.Path(path))
if not prim:
return f"Prim at path {path} is not in Fabric"
if not prim.HasAttribute("points"):
return f"Prim at path {path} does not have points attribute"
if not wp:
return "Warp failed to initialize. Install/Load the warp extension."
# Tell OmniHydra to render points from Fabric
if not prim.HasAttribute("Deformable"):
prim.CreateAttribute("Deformable", Sdf.ValueTypeNames.PrimTypeTag, True)
points = prim.GetAttribute("points")
pointsarray = points.Get()
warparray = wp.array(pointsarray, dtype=wp.vec3, device="cuda")
wp.launch(kernel=deform, dim=len(pointsarray), inputs=[warparray, time], device="cuda")
points.Set(Vt.Vec3fArray(warparray.numpy()))
return f"Deformed points on prim {path}"
# 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 UsdrtExamplePythonExtension(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):
print("[omni.example.python.usdrt] startup")
self._window = ui.Window(
"What's in Fabric?", width=300, height=300, dockPreference=ui.DockPreference.RIGHT_BOTTOM
)
self._t = 0
with self._window.frame:
with ui.VStack():
frame = ui.ScrollingFrame()
with frame:
label = ui.Label("Select a prim and push a button", alignment=ui.Alignment.LEFT_TOP)
def get_fabric_data():
label.text = get_fabric_data_for_prim(get_stage_id(), get_selected_prim_path())
def rotate_prim():
label.text = apply_random_rotation(get_stage_id(), get_selected_prim_path())
def deform_prim():
label.text = deform_mesh_with_warp(get_stage_id(), get_selected_prim_path(), self._t)
self._t += 1
ui.Button("What's in Fabric?", clicked_fn=get_fabric_data, height=0)
ui.Button("Rotate it in Fabric!", clicked_fn=rotate_prim, height=0)
ui.Button("Deform it with Warp!", clicked_fn=deform_prim, height=0)
def on_shutdown(self):
print("[omni.example.python.usdrt] shutdown")
| 6,999 | Python | 31.71028 | 119 | 0.632519 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/omni/example/python/usdrt/__init__.py | from .example_python_usdrt_extension import *
| 46 | Python | 22.499989 | 45 | 0.804348 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.usdrt/omni/example/python/usdrt/tests/test_whats_in_fabric.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.
##
import omni.example.python.usdrt
# omni.kit.test is primarily Python's standard unittest module
# with additional wrapping to add suport for async/await tests.
# Please see: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# The Python module we are testing, imported with an absolute
# path to simulate using it from a different Python extension.
import omni.usd
import usdrt
# Any class that dervives from 'omni.kit.test.AsyncTestCase'
# declared at the root of the module will be auto-discovered,
class ExamplePythonUsdrtTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Open a new USD stage.
omni.usd.get_context().new_stage()
self.usd_stage = omni.usd.get_context().get_stage()
self.stage_id = omni.usd.get_context().get_stage_id()
# create a torus
(success, pathString) = omni.kit.commands.execute("CreateMeshPrimWithDefaultXformCommand", prim_type="Torus")
self.assertTrue(success)
self.prim_path = pathString
async def tearDown(self):
# Close the USD stage.
await omni.usd.get_context().close_stage_async()
self.usd_stage = None
async def test_get_fabric_data_for_prim(self):
result = omni.example.python.usdrt.get_fabric_data_for_prim(self.stage_id, self.prim_path)
self.assertTrue("Fabric data for prim at path %s\n\n\n" % self.prim_path in result)
for attr in ["points", "normals", "primvars:st", "extent"]:
self.assertTrue(attr in result)
# test invalid prim
result = omni.example.python.usdrt.get_fabric_data_for_prim(self.stage_id, "/invalidPrim")
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result = omni.example.python.usdrt.get_fabric_data_for_prim(self.stage_id, None)
self.assertTrue(result == "Nothing selected")
async def test_apply_random_rotation(self):
result = omni.example.python.usdrt.apply_random_rotation(self.stage_id, self.prim_path)
self.assertTrue("Set new world orientation on %s to (" % self.prim_path in result)
# test invalid prim
result = omni.example.python.usdrt.apply_random_rotation(self.stage_id, "/invalidPrim")
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result = omni.example.python.usdrt.apply_random_rotation(self.stage_id, None)
self.assertTrue(result == "Nothing selected")
async def test_deform_mesh_with_warp(self):
try:
import warp
t = 0
result = omni.example.python.usdrt.deform_mesh_with_warp(self.stage_id, self.prim_path, t)
self.assertTrue(result == f"Deformed points on prim {self.prim_path}")
# test invalid prim
result = omni.example.python.usdrt.deform_mesh_with_warp(self.stage_id, "/invalidPrim", t)
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result = omni.example.python.usdrt.deform_mesh_with_warp(self.stage_id, None, t)
self.assertTrue(result == "Nothing selected")
except ImportError:
pass
| 3,687 | Python | 41.390804 | 117 | 0.681584 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/python/tests/test_pybind_example.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.
##
import omni.kit.test
import omni.example.cpp.pybind
class TestPybindExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Cache the pybind interface.
self.bound_interface = omni.example.cpp.pybind.get_bound_interface()
# Create and register a bound object.
self.bound_object = omni.example.cpp.pybind.BoundObject("test_bound_object")
self.bound_object.property_int = 9
self.bound_object.property_bool = True
self.bound_object.property_string = "Ninety-Nine"
self.bound_interface.register_bound_object(self.bound_object)
async def tearDown(self):
# Deregister and clear the bound object.
self.bound_interface.deregister_bound_object(self.bound_object)
self.bound_object = None
# Clear the pybind interface.
self.bound_interface = None
async def test_find_bound_object(self):
found_object = self.bound_interface.find_bound_object("test_bound_object")
self.assertIsNotNone(found_object)
async def test_find_unregistered_bound_object(self):
found_object = self.bound_interface.find_bound_object("unregistered_object")
self.assertIsNone(found_object)
async def test_access_bound_object_properties(self):
self.assertEqual(self.bound_object.id, "test_bound_object")
self.assertEqual(self.bound_object.property_int, 9)
self.assertEqual(self.bound_object.property_bool, True)
self.assertEqual(self.bound_object.property_string, "Ninety-Nine")
async def test_call_bound_object_functions(self):
# Test calling a bound function that accepts an argument.
self.bound_object.multiply_int_property(9)
self.assertEqual(self.bound_object.property_int, 81)
# Test calling a bound function that returns a value.
result = self.bound_object.toggle_bool_property()
self.assertEqual(result, False)
self.assertEqual(self.bound_object.property_bool, False)
# Test calling a bound function that accepts an argument and returns a value.
result = self.bound_object.append_string_property(" Red Balloons")
self.assertEqual(result, "Ninety-Nine Red Balloons")
self.assertEqual(self.bound_object.property_string, "Ninety-Nine Red Balloons")
| 2,746 | Python | 43.306451 | 87 | 0.714494 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.pybind/python/impl/example_pybind_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.
##
import omni.ext
from .._example_pybind_bindings import *
# Global public interface object.
_bound_interface = None
# Public API.
def get_bound_interface() -> IExampleBoundInterface:
return _bound_interface
# Use the extension entry points to acquire and release the interface.
class ExamplePybindExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
global _bound_interface
_bound_interface = acquire_bound_interface()
def on_shutdown(self):
global _bound_interface
release_bound_interface(_bound_interface)
_bound_interface = None
| 1,045 | Python | 31.687499 | 77 | 0.733014 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.commands/omni/example/cpp/commands/tests/test_commands_example.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.
##
import omni.kit.test
import omni.kit.commands
import omni.kit.undo
class TestCommandsExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
omni.kit.undo.clear_stack()
async def tearDown(self):
omni.kit.undo.clear_stack()
async def test_cpp_commands(self):
# Execute
res = omni.kit.commands.execute("ExampleCpp")
self.assertEqual(res, (True, None))
# Undo
res = omni.kit.undo.undo()
self.assertTrue(res)
# Redo
res = omni.kit.undo.redo()
self.assertTrue(res)
# Repeat
res = omni.kit.undo.repeat()
self.assertTrue(res)
# Undo
res = omni.kit.undo.undo()
self.assertTrue(res)
# Undo
res = omni.kit.undo.undo()
self.assertTrue(res)
# Undo (empty command stack)
res = omni.kit.undo.undo()
self.assertFalse(res)
| 1,355 | Python | 26.119999 | 77 | 0.648708 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.ui_widget/python/tests/test_cpp_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__ = ["TestCppWidget"]
from omni.example.cpp.ui_widget import CppWidget
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.ui as ui
EXTENSION_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
GOLDEN_PATH = EXTENSION_PATH.joinpath("data/golden")
STYLE = {"CppWidget": {"color": ui.color.red}}
class TestCppWidget(OmniUiTest):
async def test_general(self):
"""Testing general look of CppWidget"""
window = await self.create_test_window()
with window.frame:
CppWidget(thickness=2, style=STYLE)
await self.finalize_test(golden_img_dir=GOLDEN_PATH, golden_img_name=f"test_general.png")
| 1,180 | Python | 34.787878 | 108 | 0.738136 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/python/tests/test_usdrt_example.py | ## Copyright (c) 2023, 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 omni.example.cpp.usdrt
import omni.kit.app
import omni.kit.test
import omni.usd
from usdrt import Sdf
class TestUsdrtExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Cache the example usdrt interface.
self.example_usdrt_interface = omni.example.cpp.usdrt.get_example_usdrt_interface()
# Open a new USD stage.
omni.usd.get_context().new_stage()
self.usd_stage = omni.usd.get_context().get_stage()
self.stage_id = omni.usd.get_context().get_stage_id()
# Create a torus
(success, pathString) = omni.kit.commands.execute("CreateMeshPrimWithDefaultXformCommand", prim_type="Torus")
self.assertTrue(success)
self.prim_path = Sdf.Path(pathString)
async def tearDown(self):
# Close the USD stage.
await omni.usd.get_context().close_stage_async()
self.usd_stage = None
# Clear the example usdrt interface.
self.example_usdrt_interface = None
async def test_get_attributes_for_prim(self):
(err, attrs) = self.example_usdrt_interface.get_attributes_for_prim(self.stage_id, self.prim_path)
self.assertTrue(err == "")
self.assertTrue(attrs)
# test invalid prim
(err, attrs) = self.example_usdrt_interface.get_attributes_for_prim(self.stage_id, Sdf.Path("/invalidPrim"))
self.assertTrue(err == "Prim at path /invalidPrim is not in Fabric")
self.assertFalse(attrs)
# test empty path
(err, attrs) = self.example_usdrt_interface.get_attributes_for_prim(self.stage_id, Sdf.Path(""))
self.assertTrue(err == "Nothing selected")
self.assertFalse(attrs)
async def test_apply_random_rotation(self):
(err, rotation) = self.example_usdrt_interface.apply_random_rotation(self.stage_id, self.prim_path)
self.assertTrue(err == "")
self.assertTrue(rotation)
# test invalid prim
(err, rotation) = self.example_usdrt_interface.apply_random_rotation(self.stage_id, Sdf.Path("/invalidPrim"))
self.assertTrue(err == "Prim at path /invalidPrim is not in Fabric")
# test empty path
(err, rotation) = self.example_usdrt_interface.apply_random_rotation(self.stage_id, Sdf.Path(""))
self.assertTrue(err == "Nothing selected")
async def test_deform_mesh(self):
t = 0
result = self.example_usdrt_interface.deform_mesh(self.stage_id, self.prim_path, t)
self.assertTrue(result == f"Deformed points on prim {self.prim_path}")
# test invalid prim
result = self.example_usdrt_interface.deform_mesh(self.stage_id, Sdf.Path("/invalidPrim"), t)
self.assertTrue(result == "Prim at path /invalidPrim is not in Fabric")
# test empty path
result =self.example_usdrt_interface.deform_mesh(self.stage_id, Sdf.Path(""), t)
self.assertTrue(result == "Nothing selected")
| 3,357 | Python | 39.951219 | 117 | 0.677391 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.usdrt/python/impl/example_usdrt_extension.py | ## Copyright (c) 2023, 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 math
import random
from ctypes import alignment
import omni.ext
import omni.ui as ui
import omni.usd
from usdrt import Gf, Rt, Sdf, Usd, Vt
from .._example_usdrt_bindings import *
# Global public interface object.
_example_usdrt_interface = None
# Public API.
def get_example_usdrt_interface() -> IExampleUsdrtInterface:
return _example_usdrt_interface
def get_selected_prim_path():
"""Return the path of the first selected prim"""
context = omni.usd.get_context()
selection = context.get_selection()
paths = selection.get_selected_prim_paths()
return None if not paths else paths[0]
def get_stage_id():
"""Return the stage Id of the current stage"""
context = omni.usd.get_context()
return context.get_stage_id()
# 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 ExampleUsdrtExtension(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):
# Acquire the example USDRT interface.
global _example_usdrt_interface
_example_usdrt_interface = acquire_example_usdrt_interface()
print("[omni.example.cpp.usdrt] startup")
self._window = ui.Window(
"What's in Fabric?", width=300, height=300, dockPreference=ui.DockPreference.RIGHT_BOTTOM
)
self._t = 0
with self._window.frame:
with ui.VStack():
frame = ui.ScrollingFrame()
with frame:
label = ui.Label("Select a prim and push a button", alignment=ui.Alignment.LEFT_TOP)
def get_fabric_data():
selected_prim_path = get_selected_prim_path()
(err, data) = _example_usdrt_interface.get_attributes_for_prim(
get_stage_id(), selected_prim_path
)
if err:
label.text = err
else:
result = f"Fabric data for prim at path {selected_prim_path}\n\n\n"
for attr in data:
try:
data = attr.Get()
datastr = str(data)
if data is None:
datastr = "<no value>"
except TypeError:
# Some data types not yet supported in Python
datastr = "<no Python conversion>"
result += "{} ({}): {}\n".format(
attr.GetName(), str(attr.GetTypeName().GetAsToken()), datastr
)
label.text = result
def rotate_prim():
selected_prim_path = get_selected_prim_path()
(err, rotation) = _example_usdrt_interface.apply_random_rotation(
get_stage_id(), selected_prim_path
)
label.text = err if err else f"Set new world orientation on {selected_prim_path} to {rotation}"
def deform_prim():
label.text = _example_usdrt_interface.deform_mesh(
get_stage_id(), get_selected_prim_path(), self._t
)
self._t += 1
ui.Button("What's in Fabric?", clicked_fn=get_fabric_data, height=0)
ui.Button("Rotate it in Fabric!", clicked_fn=rotate_prim, height=0)
ui.Button("Deform it!", clicked_fn=deform_prim, height=0)
def on_shutdown(self):
global _example_usdrt_interface
# Release the example USDRT interface.
release_example_usdrt_interface(_example_usdrt_interface)
_example_usdrt_interface = None
print("[omni.example.cpp.usdrt] shutdown")
| 4,631 | Python | 39.631579 | 119 | 0.57547 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.ui/omni/example/python/ui/example_python_ui_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.
##
import omni.ext
import omni.ui as ui
from omni.example.cpp.ui_widget import CppWidget
class ExamplePythonUIExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print(f"ExamplePythonUIExtension starting up (ext_id: {ext_id}).")
self._count = 0
self._window = ui.Window("Example Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("")
def on_click():
self._count += 1
label.text = f"count: {self._count}"
def on_reset():
self._count = 0
label.text = "empty"
on_reset()
with ui.HStack():
ui.Button("Add", clicked_fn=on_click)
ui.Button("Reset", clicked_fn=on_reset)
# Use a widget that was defined in C++
STYLE = {"CppWidget": {"color": ui.color.red}}
CppWidget(thickness=2, style=STYLE)
def on_shutdown(self):
print(f"ExamplePythonUIExtension shutting down.")
self._count = 0
| 1,579 | Python | 33.347825 | 77 | 0.592147 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.python.ui/omni/example/python/ui/tests/test_example_python_ui.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.
##
# omni.kit.test is primarily Python's standard unittest module
# with additional wrapping to add suport for async/await tests.
# Please see: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# omni.kit.ui_test is for simulating UI interactions in tests.
import omni.kit.ui_test as ui_test
# The Python module we are testing, imported with an absolute
# path to simulate using it from a different Python extension.
import omni.example.python.ui
# Any class that dervives from 'omni.kit.test.AsyncTestCase'
# declared at the root of the module will be auto-discovered,
class Test(omni.kit.test.AsyncTestCase):
# Called before running each test.
async def setUp(self):
pass
# Called after running each test.
async def tearDown(self):
pass
# Example test case that simulates UI interactions.
async def test_window_button(self):
# Find a label in the window.
label = ui_test.find("Example Window//Frame/**/Label[*]")
# Find buttons in the window.
add_button = ui_test.find("Example Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("Example Window//Frame/**/Button[*].text=='Reset'")
# Click the add button.
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
# Click the add button.
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
# Click the reset button.
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
| 2,009 | Python | 35.545454 | 87 | 0.703335 |
NVIDIA-Omniverse/kit-extension-template-cpp/source/extensions/omni.example.cpp.actions/omni/example/cpp/actions/tests/test_actions_example.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.
##
import omni.kit.test
import omni.kit.actions.core
class TestActionsExample(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.action_registry = omni.kit.actions.core.get_action_registry()
self.extension_id = "omni.example.cpp.actions"
async def tearDown(self):
self.extension_id = None
self.action_registry = None
async def test_find_and_execute_custom_action(self):
action = self.action_registry.get_action(self.extension_id, "example_custom_action_id")
self.assertIsNotNone(action)
result = action.execute()
self.assertEqual(result, 3) # 3 because this was already executed twice in the C++ tests
result = action.execute()
self.assertEqual(result, 4)
async def test_find_and_execute_lambda_action(self):
action = self.action_registry.get_action(self.extension_id, "example_lambda_action_id")
self.assertIsNotNone(action)
result = action.execute()
self.assertIsNone(result)
| 1,455 | Python | 36.333332 | 96 | 0.716151 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_manipulator.py | from omni.ui import scene as sc
from omni.ui import color as cl
import omni.ui as ui
class SliderManipulator(sc.Manipulator):
class SliderDragGesturePayload(sc.AbstractGesture.GesturePayload):
"""
Public payload. The user will access it to get the current value of
the slider.
"""
def __init__(self, base):
super().__init__(base.item_closest_point, base.ray_closest_point, base.ray_distance)
self.slider_value = 0
class SliderChangedGesture(sc.ManipulatorGesture):
"""
Public Gesture. The user will reimplement it to process the
manipulator's callbacks.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def process(self):
# Redirection to methods
if self.state == sc.GestureState.BEGAN:
self.on_began()
elif self.state == sc.GestureState.CHANGED:
self.on_changed()
elif self.state == sc.GestureState.ENDED:
self.on_ended()
# Public API:
def on_began(self):
pass
def on_changed(self):
pass
def on_ended(self):
pass
class _ArcGesturePrioritize(sc.GestureManager):
"""
Manager makes _ArcGesture the priority gesture
"""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(preventer, SliderManipulator._ArcGesture):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _ArcGesture(sc.DragGesture):
"""
Internal gesture that sets the new slider value and redirects to
public SliderChangedGesture.
"""
def __init__(self, manipulator):
super().__init__(manager=SliderManipulator._ArcGesturePrioritize())
self._manipulator = manipulator
def __repr__(self):
return f"<_ArcGesture at {hex(id(self))}>"
def process(self):
if self.state in [sc.GestureState.BEGAN, sc.GestureState.CHANGED, sc.GestureState.ENDED]:
# Form new gesture_payload object
new_gesture_payload = SliderManipulator.SliderDragGesturePayload(self.gesture_payload)
# Save the new slider position in the gesture_payload object
object_ray_point = self._manipulator.transform_space(
sc.Space.WORLD, sc.Space.OBJECT, self.gesture_payload.ray_closest_point
)
center = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("position"))
slider_value = (object_ray_point[0] - center[0]) / self._manipulator.width + 0.5
_min = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("min"))[0]
_max = self._manipulator.model.get_as_floats(self._manipulator.model.get_item("max"))[0]
new_gesture_payload.slider_value = _min + slider_value * (_max - _min)
# Call the public gesture
self._manipulator._process_gesture(
SliderManipulator.SliderChangedGesture, self.state, new_gesture_payload
)
# Base process of the gesture
super().process()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.width = 100
self.thickness = 5
self._radius = 5
self._radius_hovered = 7
def set_radius(circle, radius):
circle.radius = radius
# We don't recreate the gesture to make sure it's active when the
# underlying object is recreated
self._arc_gesture = self._ArcGesture(self)
if hasattr(sc, "HoverGesture"):
self._hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_radius(sender, self._radius_hovered),
on_ended_fn=lambda sender: set_radius(sender, self._radius),
)
else:
self._hover_gesture = None
def destroy(self):
pass
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
# Regenerate the mesh
self.invalidate()
@property
def thickness(self):
return self._thickness
@thickness.setter
def thickness(self, value):
self._thickness = value
# Regenerate the mesh
self.invalidate()
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
_min = self.model.get_as_floats(self.model.get_item("min"))[0]
_max = self.model.get_as_floats(self.model.get_item("max"))[0]
value = float(self.model.get_as_floats(self.model.get_item("value"))[0])
value_normalized = (value - _min) / (_max - _min)
value_normalized = max(min(value_normalized, 1.0), 0.0)
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Left line
line_from = -self.width * 0.5
line_to = -self.width * 0.5 + self.width * value_normalized - self._radius
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# NEW: same as left line but flipped
# Right line
line_from = -self.width * 0.5 + self.width * value_normalized + self._radius
line_to = self.width * 0.5
if line_to > line_from:
sc.Line([line_from, 0, 0], [line_to, 0, 0], color=cl.darkgray, thickness=self.thickness)
# Circle
circle_position = -self.width * 0.5 + self.width * value_normalized
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(circle_position, 0, 0)):
radius = self._radius
# NEW: Added Gesture when hovering over the circle it will increase in size
gestures = [self._arc_gesture]
if self._hover_gesture:
gestures.append(self._hover_gesture)
if self._hover_gesture.state == sc.GestureState.CHANGED:
radius = self._radius_hovered
sc.Arc(radius, axis=2, color=cl.gray, gestures=gestures)
# END NEW
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# NEW: Added more space between the slider and the label
# Move it to the top
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, self._radius_hovered, 0)):
# END NEW
with sc.Transform(scale_to=sc.Space.SCREEN):
# Move it 5 points more to the top in the screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 5, 0)):
sc.Label(f"{value:.1f}", alignment=ui.Alignment.CENTER_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate() | 7,610 | Python | 37.439394 | 108 | 0.574244 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_registry.py | from .slider_model import SliderModel
from .slider_manipulator import SliderManipulator
from typing import Any
from typing import Dict
from typing import Optional
class ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class SliderChangedGesture(SliderManipulator.SliderChangedGesture):
"""User part. Called when slider is changed."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_began(self):
# When the user drags the slider, we don't want to see the selection rect
self.__disable_selection = ViewportLegacyDisableSelection()
def on_changed(self):
"""Called when the user moved the slider"""
if not hasattr(self.gesture_payload, "slider_value"):
return
# The current slider value is in the payload.
slider_value = self.gesture_payload.slider_value
# Change the model. Slider watches it and it will update the mesh.
self.sender.model.set_floats(self.sender.model.get_item("value"), [slider_value])
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class SliderRegistry:
"""
Created by omni.kit.viewport.registry or omni.kit.manipulator.viewport per
viewport. Keeps the manipulator and some properties that are needed to the
viewport.
"""
def __init__(self, description: Optional[Dict[str, Any]] = None):
self.__slider_manipulator = SliderManipulator(model=SliderModel(), gesture=SliderChangedGesture())
def destroy(self):
if self.__slider_manipulator:
self.__slider_manipulator.destroy()
self.__slider_manipulator = None
# PrimTransformManipulator & TransformManipulator don't have their own visibility
@property
def visible(self):
return True
@visible.setter
def visible(self, value):
pass
@property
def categories(self):
return ("manipulator",)
@property
def name(self):
return "Example Slider Manipulator" | 3,144 | Python | 34.738636 | 114 | 0.640585 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/extension.py | import omni.ext
from omni.kit.manipulator.viewport import ManipulatorFactory
from omni.kit.viewport.registry import RegisterScene
from .slider_registry import SliderRegistry
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.slider_registry = RegisterScene(SliderRegistry, "omni.example.slider")
self.slider_factory = ManipulatorFactory.create_manipulator(SliderRegistry)
def on_shutdown(self):
ManipulatorFactory.destroy_manipulator(self.slider_factory)
self.slider_factory = None
self.slider_registry.destroy()
self.slider_registry = None
| 785 | Python | 40.368419 | 119 | 0.75414 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.slider_manipulator/Tutorial/Final Scripts/slider_model.py | from omni.ui import scene as sc
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
import omni.usd
import omni.kit.commands
from pxr import Gf
class SliderModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the position and scale of the selected
object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because because we take the position directly from USD when requesting.
"""
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ValueItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value"""
def __init__(self, value=0):
super().__init__()
self.value = [value]
def __init__(self) -> None:
super().__init__()
self.scale = SliderModel.ValueItem()
self.min = SliderModel.ValueItem()
self.max = SliderModel.ValueItem(1)
self.position = SliderModel.PositionItem()
# Current selection
self.current_path = ""
self.stage_listener = None
self.usd_context = omni.usd.get_context()
self.stage: Usd.Stage = self.usd_context.get_stage()
# Track selection
self.selection = self.usd_context.get_selection()
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Slider Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_paths = self.selection.get_selected_prim_paths()
if not prim_paths:
self._item_changed(self.position)
# Revoke the Tf.Notice listener, we don't need to update anything
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
prim = self.stage.GetPrimAtPath(prim_paths[0])
if not prim.IsA(UsdGeom.Imageable):
return
self.current_path = prim_paths[0]
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim)
scale = old_scale[0]
_min = scale * 0.1
_max = scale * 2.0
self.set_floats(self.min, [_min])
self.set_floats(self.max, [_max])
self.set_floats(self.scale, [scale])
# Add a Tf.Notice listener to update the position
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self.stage)
# Position is changed
self._item_changed(self.position)
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice"""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "value":
return self.scale
if identifier == "min":
return self.min
if identifier == "max":
return self.max
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def set_floats(self, item, value):
if not self.current_path:
return
if not value or not item or item.value == value:
return
if item == self.scale:
# Set the scale when setting the value.
value[0] = min(max(value[0], self.min.value[0]), self.max.value[0])
(old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(
self.stage.GetPrimAtPath(self.current_path)
)
omni.kit.commands.execute(
"TransformPrimSRTCommand",
path=self.current_path,
new_translation=old_translation,
new_rotation_euler=old_rotation_euler,
new_scale=Gf.Vec3d(value[0], value[0], value[0]),
)
# Set directly to the item
item.value = value
# This makes the manipulator updated
self._item_changed(item)
def get_position(self):
"""Returns position of currently selected object"""
if not self.current_path:
return [0, 0, 0]
# Get position directly from USD
prim = self.stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = (bboxMax[1] + 10)
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
| 5,473 | Python | 34.089743 | 121 | 0.576466 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/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__ = ["LightManipulatorExtension"]
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
class LightManipulatorExtension(omni.ext.IExt):
def __init__(self):
self._viewport_scene = None
def on_startup(self, ext_id):
# Get the active (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_error(f"No Viewport Window to add {ext_id} scene to")
return
# Build out the scene
self._viewport_scene = ViewportScene(viewport_window, ext_id)
def on_shutdown(self):
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
| 1,294 | Python | 33.078946 | 76 | 0.705564 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_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.
#
__all__ = ["LightModel"]
import carb
from omni.ui import scene as sc
import omni.usd
from pxr import Usd, UsdGeom, UsdLux, Tf, Gf
def _flatten_matrix(matrix: Gf.Matrix4d):
m0, m1, m2, m3 = matrix[0], matrix[1], matrix[2], matrix[3]
return [
m0[0],
m0[1],
m0[2],
m0[3],
m1[0],
m1[1],
m1[2],
m1[3],
m2[0],
m2[1],
m2[2],
m2[3],
m3[0],
m3[1],
m3[2],
m3[3],
]
class LightModel(sc.AbstractManipulatorModel):
"""
User part. The model tracks the attributes of the selected light.
"""
class MatrixItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the tranformation. It doesn't contain anything
because we take the tranformation directly from USD when requesting.
"""
identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
def __init__(self):
super().__init__()
self.value = self.identity.copy()
class FloatItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single float value about some attibute"""
def __init__(self, value=0.0):
super().__init__()
self.value = value
class StringItem(sc.AbstractManipulatorItem):
"""The Model Item contains a single string value about some attibute"""
def __init__(self, value=""):
super().__init__()
self.value = value
def __init__(self):
super().__init__()
self.prim_path = LightModel.StringItem()
self.transform = LightModel.MatrixItem()
self.intensity = LightModel.FloatItem()
self.width = LightModel.FloatItem()
self.height = LightModel.FloatItem()
# Save the UsdContext name (we currently only work with single Context)
self._usd_context_name = ""
# Current selection
self._light = None
self._stage_listener = None
# Track selection change
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="Light Manipulator Selection Change"
)
def __del__(self):
self._invalidate_object()
@property
def _usd_context(self) -> Usd.Stage:
# Get the UsdContext we are attached to
return omni.usd.get_context(self._usd_context_name)
@property
def _current_path(self):
return self.prim_path.value
@property
def _time(self):
return Usd.TimeCode.Default()
def _notice_changed(self, notice, stage):
"""Called by Tf.Notice. When USD data changes, we update the ui"""
light_path = self.prim_path.value
if not light_path:
return
changed_items = set()
for p in notice.GetChangedInfoOnlyPaths():
prim_path = p.GetPrimPath().pathString
if prim_path != light_path:
# Update on any parent transformation changes too
if light_path.startswith(prim_path):
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name):
changed_items.add(self.transform)
continue
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name):
changed_items.add(self.transform)
elif self.width and p.name == "width":
changed_items.add(self.width)
elif self.height and p.name == "height":
changed_items.add(self.height)
elif self.intensity and p.name == "intensity":
changed_items.add(self.intensity)
for item in changed_items:
self._item_changed(item)
def get_as_floats(self, item):
"""get the item value directly from USD"""
if item == self.transform:
return self._get_transform(self._time)
if item == self.intensity:
return self._get_intensity(self._time)
if item == self.width:
return self._get_width(self._time)
if item == self.height:
return self._get_height(self._time)
if item:
# Get the value directly from the item
return item.value
return None
def set_floats_commands(self, item, value):
"""set the item value to USD using commands, this is useful because it supports undo/redo"""
if not self._current_path:
return
if not value or not item:
return
# we get the previous value from the model instead of USD
if item == self.height:
prev_value = self.height.value
if prev_value == value:
return
height_attr = self._light.GetHeightAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=height_attr.GetPath(), value=value, prev=prev_value)
elif item == self.width:
prev_value = self.width.value
if prev_value == value:
return
width_attr = self._light.GetWidthAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=width_attr.GetPath(), value=value, prev=prev_value)
elif item == self.intensity:
prev_value = self.intensity.value
if prev_value == value:
return
intensity_attr = self._light.GetIntensityAttr()
omni.kit.commands.execute('ChangeProperty', prop_path=intensity_attr.GetPath(), value=value, prev=prev_value)
# This makes the manipulator updated
self._item_changed(item)
def set_item_value(self, item, value):
""" This is used to set the model value instead of the usd. This is used to record previous value for
omni.kit.commands """
item.value = value
def set_floats(self, item, value):
"""set the item value directly to USD. This is useful when we want to update the usd but not record it in commands"""
if not self._current_path:
return
if not value or not item:
return
pre_value = self.get_as_floats(item)
# no need to update if the updated value is the same
if pre_value == value:
return
if item == self.height:
self._set_height(self._time, value)
elif item == self.width:
self._set_width(self._time, value)
elif item == self.intensity:
self._set_intensity(self._time, value)
def _on_stage_event(self, event):
"""Called by stage_event_stream"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_kit_selection_changed()
def _invalidate_object(self, settings):
# Revoke the Tf.Notice listener, we don't need to update anything
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
# Reset original Viewport gizmo line width
settings.set("/persistent/app/viewport/gizmo/lineWidth", 0)
# Clear any cached UsdLux.Light object
self._light = None
# Set the prim_path to empty
self.prim_path.value = ""
self._item_changed(self.prim_path)
def _on_kit_selection_changed(self):
# selection change, reset it for now
self._light = None
# Turn off any native selected light drawing
settings = carb.settings.get_settings()
settings.set("/persistent/app/viewport/gizmo/lineWidth", 0)
usd_context = self._usd_context
if not usd_context:
return self._invalidate_object(settings)
stage = usd_context.get_stage()
if not stage:
return self._invalidate_object(settings)
prim_paths = usd_context.get_selection().get_selected_prim_paths() if usd_context else None
if not prim_paths:
return self._invalidate_object(settings)
prim = stage.GetPrimAtPath(prim_paths[0])
if prim and prim.IsA(UsdLux.RectLight):
self._light = UsdLux.RectLight(prim)
if not self._light:
return self._invalidate_object(settings)
selected_path = self._light.GetPrim().GetPath().pathString
if selected_path != self.prim_path.value:
self.prim_path.value = selected_path
self._item_changed(self.prim_path)
# Add a Tf.Notice listener to update the light attributes
if not self._stage_listener:
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage)
def _get_transform(self, time: Usd.TimeCode):
"""Returns world transform of currently selected object"""
if not self._light:
return LightModel.MatrixItem.identity.copy()
# Compute matrix from world-transform in USD
world_xform = self._light.ComputeLocalToWorldTransform(time)
# Flatten Gf.Matrix4d to list
return _flatten_matrix(world_xform)
def _get_intensity(self, time: Usd.TimeCode):
"""Returns intensity of currently selected light"""
if not self._light:
return 0.0
# Get intensity directly from USD
return self._light.GetIntensityAttr().Get(time)
def _set_intensity(self, time: Usd.TimeCode, value):
"""set intensity of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetIntensityAttr().Set(value, time=time)
def _get_width(self, time: Usd.TimeCode):
"""Returns width of currently selected light"""
if not self._light:
return 0.0
# Get radius directly from USD
return self._light.GetWidthAttr().Get(time)
def _set_width(self, time: Usd.TimeCode, value):
"""set width of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetWidthAttr().Set(value, time=time)
def _get_height(self, time: Usd.TimeCode):
"""Returns height of currently selected light"""
if not self._light:
return 0.0
# Get height directly from USD
return self._light.GetHeightAttr().Get(time)
def _set_height(self, time: Usd.TimeCode, value):
"""set height of currently selected light"""
if not self._light:
return
# set height dirctly to USD
self._light.GetHeightAttr().Set(value, time=time)
| 11,040 | Python | 33.07716 | 125 | 0.600272 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/light_manipulator.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__ = ["LightManipulator"]
from omni.ui import scene as sc
from omni.ui import color as cl
import omni.kit
import omni.kit.commands
INTENSITY_SCALE = 500.0
ARROW_WIDTH = 0.015
ARROW_HEIGHT = 0.1
ARROW_P = [
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[0, 0, ARROW_HEIGHT],
#
[ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, ARROW_WIDTH, 0],
[-ARROW_WIDTH, -ARROW_WIDTH, 0],
[ARROW_WIDTH, -ARROW_WIDTH, 0],
]
ARROW_VC = [3, 3, 3, 3, 4]
ARROW_VI = [i for i in range(sum(ARROW_VC))]
class _ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact is the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class _DragGesture(sc.DragGesture):
""""Gesture to disable rectangle selection in the viewport legacy"""
def __init__(self, manipulator, orientation, flag):
super().__init__()
self._manipulator = manipulator
# record this _previous_ray_point to get the mouse moved vector
self._previous_ray_point = None
# this defines the orientation of the move, 0 means x, 1 means y, 2 means z. It's a list so that we can move a selection
self.orientations = orientation
# global flag to indicate if the manipulator changes all the width, height and intensity, rectangle manipulator
# in the example
self.is_global = len(self.orientations) > 1
# this defines the negative or positive of the move. E.g. when we move the positive x line to the right, it
# enlarges the width, and when we move the negative line to the left, it also enlarges the width
# 1 means positive and -1 means negative. It's a list so that we can reflect list orientation
self.flag = flag
def on_began(self):
# When the user drags the slider, we don't want to see the selection
# rect. In Viewport Next, it works well automatically because the
# selection rect is a manipulator with its gesture, and we add the
# slider manipulator to the same SceneView.
# In Viewport Legacy, the selection rect is not a manipulator. Thus it's
# not disabled automatically, and we need to disable it with the code.
self.__disable_selection = _ViewportLegacyDisableSelection()
# initialize the self._previous_ray_point
self._previous_ray_point = self.gesture_payload.ray_closest_point
# record the previous value for the model
self.model = self._manipulator.model
if 0 in self.orientations:
self.width_item = self.model.width
self._manipulator.model.set_item_value(self.width_item, self.model.get_as_floats(self.width_item))
if 1 in self.orientations:
self.height_item = self.model.height
self._manipulator.model.set_item_value(self.height_item, self.model.get_as_floats(self.height_item))
if 2 in self.orientations or self.is_global:
self.intensity_item = self.model.intensity
self._manipulator.model.set_item_value(self.intensity_item, self.model.get_as_floats(self.intensity_item))
def on_changed(self):
object_ray_point = self.gesture_payload.ray_closest_point
# calculate the ray moved vector
moved = [a - b for a, b in zip(object_ray_point, self._previous_ray_point)]
# transfer moved from world to object space, [0] to make it a normal, not point
moved = self._manipulator._x_xform.transform_space(sc.Space.WORLD, sc.Space.OBJECT, moved + [0])
# 2.0 because `_shape_xform.transform` is a scale matrix and it means
# the width of the rectangle is twice the scale matrix.
moved_x = moved[0] * 2.0 * self.flag[0]
moved_y = moved[1] * 2.0 * (self.flag[1] if self.is_global else self.flag[0])
moved_z = moved[2] * self.flag[0]
# update the self._previous_ray_point
self._previous_ray_point = object_ray_point
# since self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
# when we want to update the manipulator, we are actually updating self._manipulator._shape_xform.transform[0]
# for width and self._manipulator._shape_xform.transform[5] for height and
# self._manipulator._shape_xform.transform[10] for intensity
width = self._manipulator._shape_xform.transform[0]
height = self._manipulator._shape_xform.transform[5]
intensity = self._manipulator._shape_xform.transform[10]
self.width_new = width + moved_x
self.height_new = height + moved_y
# update the USD as well as update the ui
if 0 in self.orientations:
# update the data in the model
self.model.set_floats(self.width_item, self.width_new)
self._manipulator._shape_xform.transform[0] = self.width_new
if 1 in self.orientations:
# update the data in the model
self.model.set_floats(self.height_item, self.height_new)
self._manipulator._shape_xform.transform[5] = self.height_new
if 2 in self.orientations:
self._manipulator._shape_xform.transform[10] += moved_z
self.intensity_new = self._manipulator._shape_xform.transform[10] * INTENSITY_SCALE
self.model.set_floats(self.intensity_item, self.intensity_new)
if self.is_global:
# need to update the intensity in a different way
intensity_new = intensity * width * height / (self.width_new * self.height_new)
self._manipulator._shape_xform.transform[10] = intensity_new
self.intensity_new = intensity_new * INTENSITY_SCALE
self.model.set_floats(self.intensity_item, self.intensity_new)
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
if self.is_global:
# start group command
omni.kit.undo.begin_group()
if 0 in self.orientations:
self.model.set_floats_commands(self.width_item, self.width_new)
if 1 in self.orientations:
self.model.set_floats_commands(self.height_item, self.height_new)
if 2 in self.orientations or self.is_global:
self.model.set_floats_commands(self.intensity_item, self.intensity_new)
if self.is_global:
# end group command
omni.kit.undo.end_group()
class LightManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._shape_xform = None
def __del__(self):
self.model = None
def _build_shape(self):
if not self.model:
return
if self.model.width and self.model.height and self.model.intensity:
x = self.model.get_as_floats(self.model.width)
y = self.model.get_as_floats(self.model.height)
# this INTENSITY_SCALE is too make the transform a reasonable length with large intensity number
z = self.model.get_as_floats(self.model.intensity) / INTENSITY_SCALE
self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1]
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
model = self.model
if not model:
return
# if we don't have selection then just return
prim_path_item = model.prim_path
prim_path = prim_path_item.value if prim_path_item else None
if not prim_path:
return
# Style settings, as kwargs
thickness = 1
hover_thickness = 3
color = cl.yellow
shape_style = {"thickness": thickness, "color": color}
def set_thickness(sender, shapes, thickness):
for shape in shapes:
shape.thickness = thickness
self.__root_xf = sc.Transform(model.get_as_floats(model.transform))
with self.__root_xf:
self._x_xform = sc.Transform()
with self._x_xform:
self._shape_xform = sc.Transform()
# Build the shape's transform
self._build_shape()
with self._shape_xform:
# Build the shape geomtery as unit-sized
h = 0.5
z = -1.0
# the rectangle
shape1 = sc.Line((-h, h, 0), (h, h, 0), **shape_style)
shape2 = sc.Line((-h, -h, 0), (h, -h, 0), **shape_style)
shape3 = sc.Line((h, h, 0), (h, -h, 0), **shape_style)
shape4 = sc.Line((-h, h, 0), (-h, -h, 0), **shape_style)
# add gesture to the lines of the rectangle to update width or height of the light
vertical_hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_thickness(sender, [shape1, shape2], hover_thickness),
on_ended_fn=lambda sender: set_thickness(sender, [shape1, shape2], thickness),
)
shape1.gestures = [_DragGesture(self, [1], [1]), vertical_hover_gesture]
shape2.gestures = [_DragGesture(self, [1], [-1]), vertical_hover_gesture]
horizontal_hover_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_thickness(sender, [shape3, shape4], hover_thickness),
on_ended_fn=lambda sender: set_thickness(sender, [shape3, shape4], thickness),
)
shape3.gestures = [_DragGesture(self, [0], [1]), horizontal_hover_gesture]
shape4.gestures = [_DragGesture(self, [0], [-1]), horizontal_hover_gesture]
# create z-axis to indicate the intensity
z1 = sc.Line((h, h, 0), (h, h, z), **shape_style)
z2 = sc.Line((-h, -h, 0), (-h, -h, z), **shape_style)
z3 = sc.Line((h, -h, 0), (h, -h, z), **shape_style)
z4 = sc.Line((-h, h, 0), (-h, h, z), **shape_style)
def make_arrow(translate):
vert_count = len(ARROW_VI)
with sc.Transform(
transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])
* sc.Matrix44.get_rotation_matrix(0, -180, 0, True)
):
return sc.PolygonMesh(ARROW_P, [color] * vert_count, ARROW_VC, ARROW_VI, visible=False)
# arrows on the z-axis
arrow_1 = make_arrow((h, h, z))
arrow_2 = make_arrow((-h, -h, z))
arrow_3 = make_arrow((h, -h, z))
arrow_4 = make_arrow((-h, h, z))
# the line underneath the arrow which is where the gesture applies
z1_arrow = sc.Line((h, h, z), (h, h, z - ARROW_HEIGHT), **shape_style)
z2_arrow = sc.Line((-h, -h, z), (-h, -h, z - ARROW_HEIGHT), **shape_style)
z3_arrow = sc.Line((h, -h, z), (h, -h, z - ARROW_HEIGHT), **shape_style)
z4_arrow = sc.Line((-h, h, z), (-h, h, z - ARROW_HEIGHT), **shape_style)
def set_visible(sender, shapes, thickness, arrows, visible):
set_thickness(sender, shapes, thickness)
for arrow in arrows:
arrow.visible = visible
thickness_group = [z1, z1_arrow, z2, z2_arrow, z3, z3_arrow, z4, z4_arrow]
visible_group = [arrow_1, arrow_2, arrow_3, arrow_4]
visible_arrow_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_visible(sender, thickness_group, hover_thickness, visible_group, True),
on_ended_fn=lambda sender: set_visible(sender, thickness_group, thickness, visible_group, False),
)
gestures = [_DragGesture(self, [2], [-1]), visible_arrow_gesture]
z1_arrow.gestures = gestures
z2_arrow.gestures = gestures
z3_arrow.gestures = gestures
z4_arrow.gestures = gestures
# create 4 rectangles at the corner, and add gesture to update width, height and intensity at the same time
s = 0.03
def make_corner_rect(translate):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])):
return sc.Rectangle(s, s, color=0x0)
r1 = make_corner_rect((h - 0.5 * s, -h + 0.5 * s, 0))
r2 = make_corner_rect((h - 0.5 * s, h - 0.5 * s, 0))
r3 = make_corner_rect((-h + 0.5 * s, h - 0.5 * s, 0))
r4 = make_corner_rect((-h + 0.5 * s, -h + 0.5 * s, 0))
def set_color_and_visible(sender, shapes, thickness, arrows, visible, rects, color):
set_visible(sender, shapes, thickness, arrows, visible)
for rect in rects:
rect.color = color
highlight_group = [shape1, shape2, shape3, shape4] + thickness_group
color_group = [r1, r2, r3, r4]
hight_all_gesture = sc.HoverGesture(
on_began_fn=lambda sender: set_color_and_visible(sender, highlight_group, hover_thickness, visible_group, True, color_group, color),
on_ended_fn=lambda sender: set_color_and_visible(sender, highlight_group, thickness, visible_group, False, color_group, 0x0),
)
r1.gestures = [_DragGesture(self, [0, 1], [1, -1]), hight_all_gesture]
r2.gestures = [_DragGesture(self, [0, 1], [1, 1]), hight_all_gesture]
r3.gestures = [_DragGesture(self, [0, 1], [-1, 1]), hight_all_gesture]
r4.gestures = [_DragGesture(self, [0, 1], [-1, -1]), hight_all_gesture]
def on_model_updated(self, item):
# Regenerate the mesh
if not self.model:
return
if item == self.model.transform:
# If transform changed, update the root transform
self.__root_xf.transform = self.model.get_as_floats(item)
elif item == self.model.prim_path:
# If prim_path or width or height or intensity changed, redraw everything
self.invalidate()
elif item == self.model.width or item == self.model.height or item == self.model.intensity:
# Interpret None as changing multiple light shape settings
self._build_shape()
| 16,572 | Python | 48.471642 | 156 | 0.57573 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/test_manipulator.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.
##
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
import omni.kit
import omni.kit.app
import omni.kit.test
from omni.example.ui_scene.light_manipulator import LightManipulator, LightModel
import omni.usd
from omni.ui import scene as sc
from pxr import UsdLux, UsdGeom
from omni.kit.viewport.utility import next_viewport_frame_async
from omni.kit.viewport.utility.tests import setup_vieport_test_window
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.example.ui_scene.light_manipulator}/data"))
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
class TestLightManipulator(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600):
await self.create_test_area(resolution_x, resolution_y)
return await setup_vieport_test_window(resolution_x, resolution_y)
async def test_manipulator_transform(self):
viewport_window = await self.setup_viewport()
viewport = viewport_window.viewport_api
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
# Wait until the Viewport has delivered some frames
await next_viewport_frame_async(viewport, 2)
with viewport_window.get_frame(0):
# Create a default SceneView (it has a default camera-model)
scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with scene_view.scene:
LightManipulator(model=LightModel())
omni.kit.commands.execute(
"CreatePrim",
prim_path="/RectLight",
prim_type="RectLight",
select_new_prim=True,
attributes={},
)
rect_light = UsdLux.RectLight(stage.GetPrimAtPath("/RectLight"))
# change light attribute
rect_light.GetHeightAttr().Set(100)
rect_light.GetWidthAttr().Set(200)
rect_light.GetIntensityAttr().Set(10000)
# rotate the light to have a better angle
rect_light_x = UsdGeom.Xformable(rect_light)
rect_light_x.ClearXformOpOrder()
rect_light_x.AddRotateXOp().Set(30)
rect_light_x.AddRotateYOp().Set(45)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 3,133 | Python | 37.219512 | 114 | 0.684966 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.light_manipulator/omni/example/ui_scene/light_manipulator/tests/__init__.py | from .test_manipulator import TestLightManipulator | 50 | Python | 49.99995 | 50 | 0.9 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/extension.py | import omni.ext
import omni.ui as ui
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportSceneInfo
class MyExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
# 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 __init__(self) -> None:
super().__init__()
self.viewport_scene = None
def on_startup(self, ext_id):
viewport_window = get_active_viewport_window()
self.viewport_scene = ViewportSceneInfo(viewport_window, ext_id)
def on_shutdown(self):
"""Called when the extension is shutting down."""
if self.viewport_scene:
self.viewport_scene.destroy()
self.viewport_scene = None | 915 | Python | 34.230768 | 119 | 0.679781 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/viewport_scene.py | from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjInfoManipulator
from .object_info_model import ObjInfoModel
class ViewportSceneInfo():
def __init__(self, viewportWindow, ext_id) -> None:
self.sceneView = None
self.viewportWindow = viewportWindow
with self.viewportWindow.get_frame(ext_id):
self.sceneView = sc.SceneView()
with self.sceneView.scene:
ObjInfoManipulator(model=ObjInfoModel())
self.viewportWindow.viewport_api.add_scene_view(self.sceneView)
def __del__(self):
self.destroy()
def destroy(self):
if self.sceneView:
self.sceneView.scene.clear()
if self.viewportWindow:
self.viewportWindow.viewport_api.remove_scene_view(self.sceneView)
self.viewportWindow = None
self.sceneView = None | 921 | Python | 27.812499 | 82 | 0.641694 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_model.py | from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
class ObjInfoModel(sc.AbstractManipulatorModel):
"""
The model tracks the position and info of the selected object.
"""
class PositionItem(sc.AbstractManipulatorItem):
"""
The Model Item represents the position. It doesn't contain anything
because we take the position directly from USD when requesting.
"""
def __init__(self) -> None:
super().__init__()
self.value = [0, 0, 0]
def __init__(self) -> None:
super().__init__()
# Current selected prim
self.prim = None
self.current_path = ""
self.stage_listener = None
self.position = ObjInfoModel.PositionItem()
# Save the UsdContext name (we currently only work with a single Context)
self.usd_context = omni.usd.get_context()
# Track selection changes
self.events = self.usd_context.get_stage_event_stream()
self.stage_event_delegate = self.events.create_subscription_to_pop(
self.on_stage_event, name="Object Info Selection Update"
)
def on_stage_event(self, event):
"""Called by stage_event_stream. We only care about selection changes."""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
prim_path = self.usd_context.get_selection().get_selected_prim_paths()
if not prim_path:
self.current_path = ""
self._item_changed(self.position)
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(prim_path[0])
if not prim.IsA(UsdGeom.Imageable):
self.prim = None
if self.stage_listener:
self.stage_listener.Revoke()
self.stage_listener = None
return
if not self.stage_listener:
self.stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.notice_changed, stage)
self.prim = prim
self.current_path = prim_path[0]
# Position is changed because new selected object has a different position
self._item_changed(self.position)
def get_item(self, identifier):
if identifier == "name":
return self.current_path
elif identifier == "position":
return self.position
def get_as_floats(self, item):
if item == self.position:
# Requesting position
return self.get_position()
if item:
# Get the value directly from the item
return item.value
return []
def get_position(self):
"""Returns position of currently selected object"""
stage = self.usd_context.get_stage()
if not stage or self.current_path == "":
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self.current_path)
box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_])
bound = box_cache.ComputeWorldBound(prim)
range = bound.ComputeAlignedBox()
bboxMin = range.GetMin()
bboxMax = range.GetMax()
# Find the top center of the bounding box and add a small offset upward.
x_Pos = (bboxMin[0] + bboxMax[0]) * 0.5
y_Pos = bboxMax[1] + 5
z_Pos = (bboxMin[2] + bboxMax[2]) * 0.5
position = [x_Pos, y_Pos, z_Pos]
return position
# loop through all notices that get passed along until we find selected
def notice_changed(self, notice: Usd.Notice, stage: Usd.Stage) -> None:
"""Called by Tf.Notice. Used when the current selected object changes in some way."""
for p in notice.GetChangedInfoOnlyPaths():
if self.current_path in str(p.GetPrimPath()):
self._item_changed(self.position)
def destroy(self):
self.events = None
self.stage_event_delegate.unsubscribe() | 4,115 | Python | 34.482758 | 111 | 0.598056 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/Tutorial/Final Scripts/object_info_manipulator.py | from omni.ui import scene as sc
import omni.ui as ui
class ObjInfoManipulator(sc.Manipulator):
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
# NEW: update to position value and added transform functions to position the Label at the object's origin and +5 in the up direction
# we also want to make sure it is scaled properly
position = self.model.get_as_floats(self.model.get_item("position"))
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
with sc.Transform(scale_to=sc.Space.SCREEN):
# END NEW
sc.Label(f"Path: {self.model.get_item('name')}")
sc.Label(f"Path: {self.model.get_item('name')}")
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate() | 1,050 | Python | 35.241378 | 141 | 0.626667 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/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__ = ["ObjectInfoExtension"]
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
from .viewport_scene import ViewportScene
class ObjectInfoExtension(omni.ext.IExt):
"""Creates an extension which will display object info in 3D
over any object in a UI Scene.
"""
def __init__(self):
self._viewport_scene = None
def on_startup(self, ext_id: str) -> None:
"""Called when the extension is starting up.
Args:
ext_id: Extension ID provided by Kit.
"""
# Get the active Viewport (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_error(f"No Viewport Window to add {ext_id} scene to")
return
# Build out the scene
self._viewport_scene = ViewportScene(viewport_window, ext_id)
def on_shutdown(self) -> None:
"""Called when the extension is shutting down."""
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
| 1,609 | Python | 32.541666 | 76 | 0.679925 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.object_info/omni/example/ui_scene/object_info/object_info_manipulator.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__ = ["ObjectInfoManipulator"]
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.ui as ui
LEADER_LINE_CIRCLE_RADIUS = 2
LEADER_LINE_THICKNESS = 2
LEADER_LINE_SEGMENT_LENGTH = 20
VERTICAL_MULT = 1.5
HORIZ_TEXT_OFFSET = 5
LINE1_OFFSET = 3
LINE2_OFFSET = 0
class ObjectInfoManipulator(sc.Manipulator):
"""Manipulator that displays the object path and material assignment
with a leader line to the top of the object's bounding box.
"""
def on_build(self):
"""Called when the model is changed and rebuilds the whole manipulator"""
if not self.model:
return
# If we don't have a selection then just return
if self.model.get_item("name") == "":
return
position = self.model.get_as_floats(self.model.get_item("position"))
# Move everything to where the object is
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)):
# Rotate everything to face the camera
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# Leader lines with a small circle on the end
sc.Arc(LEADER_LINE_CIRCLE_RADIUS, axis=2, color=cl.yellow)
sc.Line([0, 0, 0], [0, LEADER_LINE_SEGMENT_LENGTH, 0],
color=cl.yellow, thickness=LEADER_LINE_THICKNESS)
sc.Line([0, LEADER_LINE_SEGMENT_LENGTH, 0],
[LEADER_LINE_SEGMENT_LENGTH, LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT, 0],
color=cl.yellow, thickness=LEADER_LINE_THICKNESS)
# Shift text to the end of the leader line with some offset
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(
LEADER_LINE_SEGMENT_LENGTH + HORIZ_TEXT_OFFSET,
LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT,
0)):
with sc.Transform(scale_to=sc.Space.SCREEN):
# Offset each Label vertically in screen space
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, LINE1_OFFSET, 0)):
sc.Label(f"Path: {self.model.get_item('name')}",
alignment=ui.Alignment.LEFT_BOTTOM)
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, LINE2_OFFSET, 0)):
sc.Label(f"Material: {self.model.get_item('material')}",
alignment=ui.Alignment.LEFT_TOP)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
| 3,114 | Python | 44.808823 | 108 | 0.621387 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_manipulator.py | ## Copyright (c) 2018-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.
##
__all__ = ["WidgetInfoManipulator"]
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.ui as ui
class _ViewportLegacyDisableSelection:
"""Disables selection in the Viewport Legacy"""
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact is the focused window!
# And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
except Exception:
pass
class _DragPrioritize(sc.GestureManager):
"""Refuses preventing _DragGesture."""
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED:
return True
class _DragGesture(sc.DragGesture):
""""Gesture to disable rectangle selection in the viewport legacy"""
def __init__(self):
super().__init__(manager=_DragPrioritize())
def on_began(self):
# When the user drags the slider, we don't want to see the selection
# rect. In Viewport Next, it works well automatically because the
# selection rect is a manipulator with its gesture, and we add the
# slider manipulator to the same SceneView.
# In Viewport Legacy, the selection rect is not a manipulator. Thus it's
# not disabled automatically, and we need to disable it with the code.
self.__disable_selection = _ViewportLegacyDisableSelection()
def on_ended(self):
# This re-enables the selection in the Viewport Legacy
self.__disable_selection = None
class WidgetInfoManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.destroy()
self._radius = 2
self._distance_to_top = 5
self._thickness = 2
self._radius_hovered = 20
def destroy(self):
self._root = None
self._slider_subscription = None
self._slider_model = None
self._name_label = None
def _on_build_widgets(self):
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl(0.2),
"border_color": cl(0.7),
"border_width": 2,
"border_radius": 4,
}
)
with ui.VStack(style={"font_size": 24}):
ui.Spacer(height=4)
with ui.ZStack(style={"margin": 1}, height=30):
ui.Rectangle(
style={
"background_color": cl(0.0),
}
)
ui.Line(style={"color": cl(0.7), "border_width": 2}, alignment=ui.Alignment.BOTTOM)
ui.Label("Hello world, I am a scene.Widget!", height=0, alignment=ui.Alignment.CENTER)
ui.Spacer(height=4)
self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER)
# setup some model, just for simple demonstration here
self._slider_model = ui.SimpleFloatModel()
ui.Spacer(height=10)
with ui.HStack():
ui.Spacer(width=10)
ui.Label("scale", height=0, width=0)
ui.Spacer(width=5)
ui.FloatSlider(self._slider_model)
ui.Spacer(width=10)
ui.Spacer(height=4)
ui.Spacer()
self.on_model_updated(None)
# Additional gesture that prevents Viewport Legacy selection
self._widget.gestures += [_DragGesture()]
def on_build(self):
"""Called when the model is chenged and rebuilds the whole slider"""
self._root = sc.Transform(visible=False)
with self._root:
with sc.Transform(scale_to=sc.Space.SCREEN):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)):
# Label
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED)
self._widget.frame.set_build_fn(self._on_build_widgets)
def on_model_updated(self, _):
# if we don't have selection then show nothing
if not self.model or not self.model.get_item("name"):
self._root.visible = False
return
# Update the shapes
position = self.model.get_as_floats(self.model.get_item("position"))
self._root.transform = sc.Matrix44.get_translation_matrix(*position)
self._root.visible = True
# Update the slider
def update_scale(prim_name, value):
print(f"changing scale of {prim_name}, {value}")
if self._slider_model:
self._slider_subscription = None
self._slider_model.as_float = 1.0
self._slider_subscription = self._slider_model.subscribe_value_changed_fn(
lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float)
)
# Update the shape name
if self._name_label:
self._name_label.text = f"Prim:{self.model.get_item('name')}"
| 6,631 | Python | 38.011764 | 117 | 0.58513 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/widget_info_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__ = ["WidgetInfoExtension"]
from .widget_info_scene import WidgetInfoScene
from omni.kit.viewport.utility import get_active_viewport_window
import carb
import omni.ext
class WidgetInfoExtension(omni.ext.IExt):
"""The entry point to the extension"""
def on_startup(self, ext_id):
# Get the active (which at startup is the default Viewport)
viewport_window = get_active_viewport_window()
# Issue an error if there is no Viewport
if not viewport_window:
carb.log_warn(f"No Viewport Window to add {ext_id} scene to")
self._widget_info_viewport = None
return
# Build out the scene
self._widget_info_viewport = WidgetInfoScene(viewport_window, ext_id)
def on_shutdown(self):
if self._widget_info_viewport:
self._widget_info_viewport.destroy()
self._widget_info_viewport = None
| 1,340 | Python | 35.243242 | 77 | 0.706716 |
NVIDIA-Omniverse/kit-extension-sample-ui-scene/exts/omni.example.ui_scene.widget_info/omni/example/ui_scene/widget_info/tests/test_info.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__ = ["TestInfo"]
from omni.example.ui_scene.widget_info.widget_info_manipulator import WidgetInfoManipulator
from omni.ui import scene as sc
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 WidgetInfoTestModelItem(sc.AbstractManipulatorItem):
pass
class WidgetInfoTestModel(sc.AbstractManipulatorModel):
def __init__(self):
super().__init__()
self.position = WidgetInfoTestModelItem()
def get_item(self, identifier):
if identifier == "position":
return self.position
if identifier == "name":
return "Name"
if identifier == "material":
return "Material"
def get_as_floats(self, item):
if item == self.position:
return [0, 0, 0]
class TestInfo(OmniUiTest):
async def test_general(self):
"""Testing general look of the item"""
window = await self.create_test_window(width=256, height=256)
with window.frame:
# Camera matrices
projection = [1e-2, 0, 0, 0]
projection += [0, 1e-2, 0, 0]
projection += [0, 0, -2e-7, 0]
projection += [0, 0, 1, 1]
view = sc.Matrix44.get_translation_matrix(0, 0, 0)
scene_view = sc.SceneView(sc.CameraModel(projection, view))
with scene_view.scene:
# The manipulator
model = WidgetInfoTestModel()
WidgetInfoManipulator(model=model)
await omni.kit.app.get_app().next_update_async()
model._item_changed(None)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(threshold=100, golden_img_dir=TEST_DATA_PATH, golden_img_name="general.png")
| 2,430 | Python | 32.763888 | 115 | 0.653909 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/config.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
from typing import Any, Dict
c: Dict[str, Any] = {}
# paths
c["app_dir"] = "/app"
c["state_dir"] = "/app/state"
c["results_dir"] = "/app/results"
c["uploads_dir"] = "/app/uploads"
c["tests_dir"] = "/app/src/tests"
c["ansible_dir"] = "/app/src/ansible"
c["terraform_dir"] = "/app/src/terraform"
# app image name
c["app_image_name"] = "isa"
# gcp driver
# @see https://cloud.google.com/compute/docs/gpus/grid-drivers-table
c[
"gcp_driver_url"
] = "https://storage.googleapis.com/nvidia-drivers-us-public/GRID/vGPU16.2/NVIDIA-Linux-x86_64-535.129.03-grid.run"
# aws/alicloud driver
c["generic_driver_apt_package"] = "nvidia-driver-535-server"
# default remote dirs
c["default_remote_uploads_dir"] = "/home/ubuntu/uploads"
c["default_remote_results_dir"] = "/home/ubuntu/results"
c["default_remote_workspace_dir"] = "/home/ubuntu/workspace"
# defaults
# --isaac-image
c["default_isaac_image"] = "nvcr.io/nvidia/isaac-sim:2023.1.1"
# --ssh-port
c["default_ssh_port"] = 22
# --from-image
c["azure_default_from_image"] = False
c["aws_default_from_image"] = False
# --omniverse-user
c["default_omniverse_user"] = "omniverse"
# --remote-dir
c["default_remote_uploads_dir"] = "/home/ubuntu/uploads"
c["default_remote_results_dir"] = "/home/ubuntu/results"
# --isaac-instance-type
c["aws_default_isaac_instance_type"] = "g5.2xlarge"
# str, 1-index in DeployAzureCommand.AZURE_OVKIT_INSTANCE_TYPES
c["azure_default_isaac_instance_type"] = "2"
c["gcp_default_isaac_instance_type"] = "g2-standard-8"
c["alicloud_default_isaac_instance_type"] = "ecs.gn7i-c16g1.4xlarge"
# --isaac-gpu-count
c["gcp_default_isaac_gpu_count"] = 1
# --region
c["alicloud_default_region"] = "us-east-1"
# --prefix for the created cloud resources
c["default_prefix"] = "isa"
# --oige
c["default_oige_git_checkpoint"] = "main"
# --orbit
c["default_orbit_git_checkpoint"] = "devel"
| 2,478 | Python | 27.494253 | 115 | 0.705408 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/aws.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
"""
Utils for AWS
"""
from src.python.utils import read_meta, shell_command
def aws_configure_cli(
deployment_name,
verbose=False,
):
"""
Configure AWS CLI for deployment
"""
meta = read_meta(deployment_name)
aws_access_key_id = meta["params"]["aws_access_key_id"]
aws_secret_access_key = meta["params"]["aws_secret_access_key"]
region = meta["params"]["region"]
shell_command(
f"aws configure set aws_access_key_id '{aws_access_key_id}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
shell_command(
f"aws configure set aws_secret_access_key '{aws_secret_access_key}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
shell_command(
f"aws configure set region '{region}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
def aws_stop_instance(instance_id, verbose=False):
shell_command(
f"aws ec2 stop-instances --instance-ids '{instance_id}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
def aws_start_instance(instance_id, verbose=False):
shell_command(
f"aws ec2 start-instances --instance-ids '{instance_id}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
def aws_get_instance_status(instance_id, verbose=False):
"""
Query instance status
Returns: "stopping" | "stopped" | "pending" | "running"
"""
status = (
shell_command(
f"aws ec2 describe-instances --instance-ids '{instance_id}'"
+ " | jq -r .Reservations[0].Instances[0].State.Name",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
.stdout.decode()
.strip()
)
return status
| 2,500 | Python | 25.606383 | 77 | 0.632 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/ngc.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
import pathlib
import subprocess
SELF_DIR = pathlib.Path(__file__).parent.resolve()
def check_ngc_access(ngc_api_key, org="", team="", verbose=False):
"""
Checks if NGC API key is valid and user has access to DRIVE Sim.
Returns:
- 0 - all is fine
- 100 - invalid api key
- 102 - user is not in the team
"""
proc = subprocess.run(
[f"{SELF_DIR}/ngc_check.expect", ngc_api_key, org, team],
capture_output=not verbose,
timeout=60,
)
if proc.returncode not in [0, 100, 101, 102]:
raise RuntimeError(
f"Error checking NGC API Key. Return code: {proc.returncode}"
)
return proc.returncode
| 1,301 | Python | 27.304347 | 74 | 0.680246 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/alicloud.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
"""
Utils for AliCloud
"""
from src.python.utils import read_meta, shell_command
def alicloud_configure_cli(
deployment_name,
verbose=False,
):
"""
Configure Aliyun CLI
"""
meta = read_meta(deployment_name)
aliyun_access_key = meta["params"]["aliyun_access_key"]
aliyun_secret_key = meta["params"]["aliyun_secret_key"]
region = meta["params"]["region"]
shell_command(
"aliyun configure set "
+ f"--access-key-id '{aliyun_access_key}'"
+ f" --access-key-secret '{aliyun_secret_key}'"
+ f" --region '{region}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
def alicloud_start_instance(vm_id, verbose=False):
"""
Start VM
"""
shell_command(
f"aliyun ecs StartInstance --InstanceId '{vm_id}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
def alicloud_stop_instance(vm_id, verbose=False):
"""
Stop VM
"""
shell_command(
f"aliyun ecs StopInstance --InstanceId '{vm_id}'",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
def alicloud_get_instance_status(vm_id, verbose=False):
"""
Query VM status
Returns: "Stopping" | "Stopped" | "Starting" | "Running"
"""
status = (
shell_command(
f"aliyun ecs DescribeInstances --InstanceIds '[\"{vm_id}\"]'"
+ " | jq -r .Instances.Instance[0].Status",
verbose=verbose,
exit_on_error=True,
capture_output=True,
)
.stdout.decode()
.strip()
)
return status
def alicloud_list_regions(
aliyun_access_key,
aliyun_secret_key,
verbose=False,
):
"""
List regions
"""
res = (
shell_command(
f"aliyun --access-key-id {aliyun_access_key}"
+ f" --access-key-secret {aliyun_secret_key}"
+ " --region cn-beijing ecs DescribeRegions"
+ " | jq -r '.Regions.Region[].RegionId'",
capture_output=True,
exit_on_error=True,
verbose=verbose,
)
.stdout.decode()
.strip()
)
valid_regions = res.split("\n")
return valid_regions
| 2,886 | Python | 23.675213 | 74 | 0.596674 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/deployer.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
import json
import os
import re
import shlex
import sys
from pathlib import Path
import click
from src.python.utils import (
colorize_error,
colorize_info,
colorize_prompt,
colorize_result,
read_meta,
shell_command,
)
from src.python.debug import debug_break # noqa
from src.python.ngc import check_ngc_access
class Deployer:
def __init__(self, params, config):
self.tf_outputs = {}
self.params = params
self.config = config
self.existing_behavior = None
# save original params so we can recreate command line
self.input_params = params.copy()
# convert "in_china"
self.params["in_china"] = {"yes": True, "no": False, "auto": False}[
self.params["in_china"]
]
# create state directory if it doesn't exist
os.makedirs(self.config["state_dir"], exist_ok=True)
# print complete command line
if self.params["debug"]:
click.echo(colorize_info("* Command:\n" + self.recreate_command_line()))
def __del__(self):
# update meta info
self.save_meta()
def save_meta(self):
"""
Save command parameters in json file, just in case
"""
meta_file = (
f"{self.config['state_dir']}/{self.params['deployment_name']}/meta.json"
)
data = {
"command": self.recreate_command_line(separator=" "),
"input_params": self.input_params,
"params": self.params,
"config": self.config,
}
Path(meta_file).parent.mkdir(parents=True, exist_ok=True)
Path(meta_file).write_text(json.dumps(data, indent=4))
if self.params["debug"]:
click.echo(colorize_info(f"* Meta info saved to '{meta_file}'"))
def read_meta(self):
return read_meta(
self.params["deployment_name"],
self.params["debug"],
)
def recreate_command_line(self, separator=" \\\n"):
"""
Recreate command line
"""
command_line = sys.argv[0]
for k, v in self.input_params.items():
k = k.replace("_", "-")
if isinstance(v, bool):
if v:
command_line += separator + "--" + k
else:
not_prefix = "--no-"
if k in ["from-image"]:
not_prefix = "--not-"
command_line += separator + not_prefix + k
else:
command_line += separator + "--" + k + " "
if isinstance(v, str):
command_line += "'" + shlex.quote(v) + "'"
else:
command_line += str(v)
return command_line
def ask_existing_behavior(self):
"""
Ask what to do if deployment already exists
"""
deployment_name = self.params["deployment_name"]
existing = self.params["existing"]
self.existing_behavior = existing
if existing == "ask" and os.path.isfile(
f"{self.config['state_dir']}/{deployment_name}/.tfvars"
):
self.existing_behavior = click.prompt(
text=colorize_prompt(
"* Deploymemnt exists, what would you like to do? See --help for details."
),
type=click.Choice(["repair", "modify", "replace", "run_ansible"]),
default="replace",
)
if (
self.existing_behavior == "repair"
or self.existing_behavior == "run_ansible"
):
# restore params from meta file
r = self.read_meta()
self.params = r["params"]
click.echo(
colorize_info(
f"* Repairing existing deployment \"{self.params['deployment_name']}\"..."
)
)
# update meta info (with new value for existing_behavior)
self.save_meta()
# destroy existing deployment``
if self.existing_behavior == "replace":
debug = self.params["debug"]
click.echo(colorize_info("* Deleting existing deployment..."))
shell_command(
command=f'{self.config["app_dir"]}/destroy "{deployment_name}" --yes'
+ f' {"--debug" if debug else ""}',
verbose=debug,
)
# update meta info if deployment was destroyed
self.save_meta()
def validate_ngc_api_key(self, image, restricted_image=False):
"""
Check if NGC API key allows to log in and has access to appropriate NGC image
@param image: NGC image to check access to
@param restricted_image: If image is restricted to specific org/team?
"""
debug = self.params["debug"]
ngc_api_key = self.params["ngc_api_key"]
ngc_api_key_check = self.params["ngc_api_key_check"]
# extract org and team from the image path
r = re.findall(
"^nvcr\\.io/([a-z0-9\\-_]+)/([a-z0-9\\-_]+/)?[a-z0-9\\-_]+:[a-z0-9\\-_.]+$",
image,
)
ngc_org, ngc_team = r[0]
ngc_team = ngc_team.rstrip("/")
if ngc_org == "nvidia":
click.echo(
colorize_info(
"* Access to docker image can't be checked for NVIDIA org. But you'll be fine. Fingers crossed."
)
)
return
if debug:
click.echo(colorize_info(f'* Will check access to NGC Org: "{ngc_org}"'))
click.echo(colorize_info(f'* Will check access to NGC Team: "{ngc_team}"'))
if ngc_api_key_check and ngc_api_key != "none":
click.echo(colorize_info("* Validating NGC API key... "))
r = check_ngc_access(
ngc_api_key=ngc_api_key, org=ngc_org, team=ngc_team, verbose=debug
)
if r == 100:
raise Exception(colorize_error("NGC API key is invalid."))
# only check access to org/team if restricted image is deployed
elif restricted_image and (r == 101 or r == 102):
raise Exception(
colorize_error(
f'NGC API key is valid but you don\'t have access to image "{image}".'
)
)
click.echo(colorize_info(("* NGC API Key is valid!")))
def create_tfvars(self, tfvars: dict = {}):
"""
- Check if deployment with this deployment_name exists and deal with it
- Create/update tfvars file
Expected values for "existing_behavior" arg:
- repair: keep tfvars/tfstate, don't ask for user input
- modify: keep tfstate file, update tfvars file with user input
- replace: delete tfvars/tfstate files
- run_ansible: keep tfvars/tfstate, don't ask for user input, skip terraform steps
"""
# default values common for all clouds
tfvars.update(
{
"isaac_enabled": self.params["isaac"]
if "isaac" in self.params
else False,
#
"isaac_instance_type": self.params["isaac_instance_type"]
if "isaac_instance_type" in self.params
else "none",
#
"prefix": self.params["prefix"],
"ssh_port": self.params["ssh_port"],
#
"from_image": self.params["from_image"]
if "from_image" in self.params
else False,
#
"deployment_name": self.params["deployment_name"],
}
)
debug = self.params["debug"]
deployment_name = self.params["deployment_name"]
# deal with existing deployment:
tfvars_file = f"{self.config['state_dir']}/{deployment_name}/.tfvars"
tfstate_file = f"{self.config['state_dir']}/{deployment_name}/.tfstate"
# tfvars
if os.path.exists(tfvars_file):
if (
self.existing_behavior == "modify"
or self.existing_behavior == "overwrite"
):
os.remove(tfvars_file)
if debug:
click.echo(colorize_info(f'* Deleted "{tfvars_file}"...'))
# tfstate
if os.path.exists(tfstate_file):
if self.existing_behavior == "overwrite":
os.remove(tfstate_file)
if debug:
click.echo(colorize_info(f'* Deleted "{tfstate_file}"...'))
# create tfvars file
if (
self.existing_behavior == "modify"
or self.existing_behavior == "overwrite"
or not os.path.exists(tfvars_file)
):
self._write_tfvars_file(path=tfvars_file, tfvars=tfvars)
def _write_tfvars_file(self, path: str, tfvars: dict):
"""
Write tfvars file
"""
debug = self.params["debug"]
if debug:
click.echo(colorize_info(f'* Created tfvars file "{path}"'))
# create <dn>/ directory if it doesn't exist
Path(path).parent.mkdir(parents=True, exist_ok=True)
with open(path, "w") as f:
for key, value in tfvars.items():
# convert booleans to strings
if isinstance(value, bool):
value = {
True: "true",
False: "false",
}[value]
# format key names
key = key.replace("-", "_")
# write values
if isinstance(value, str):
value = value.replace('"', '\\"')
f.write(f'{key} = "{value}"\n')
elif isinstance(value, list):
f.write(f"{key} = " + str(value).replace("'", '"') + "\n")
else:
f.write(f"{key} = {value}\n")
def create_ansible_inventory(self, write: bool = True):
"""
Create Ansible inventory, return it as text
Write to file if write=True
"""
debug = self.params["debug"]
deployment_name = self.params["deployment_name"]
ansible_vars = self.params.copy()
# add config
ansible_vars["config"] = self.config
# get missing values from terraform
for k in [
"isaac_ip",
"ovami_ip",
"cloud",
]:
if k not in self.params or ansible_vars[k] is None:
ansible_vars[k] = self.tf_output(k)
# convert booleans to ansible format
ansible_booleans = {True: "true", False: "false"}
for k, v in ansible_vars.items():
if isinstance(v, bool):
ansible_vars[k] = ansible_booleans[v]
template = Path(f"{self.config['ansible_dir']}/inventory.template").read_text()
res = template.format(**ansible_vars)
# write to file
if write:
inventory_file = f"{self.config['state_dir']}/{deployment_name}/.inventory"
Path(inventory_file).parent.mkdir(parents=True, exist_ok=True) # create dir
Path(inventory_file).write_text(res) # write file
if debug:
click.echo(
colorize_info(
f'* Created Ansible inventory file "{inventory_file}"'
)
)
return res
def initialize_terraform(self, cwd: str):
"""
Initialize Terraform via shell command
cwd: directory where terraform scripts are located
"""
debug = self.params["debug"]
shell_command(
f"terraform init -upgrade -no-color -input=false {' > /dev/null' if not debug else ''}",
verbose=debug,
cwd=cwd,
)
def run_terraform(self, cwd: str):
"""
Apply Terraform via shell command
cwd: directory where terraform scripts are located
"""
debug = self.params["debug"]
deployment_name = self.params["deployment_name"]
shell_command(
"terraform apply -auto-approve "
+ f"-state={self.config['state_dir']}/{deployment_name}/.tfstate "
+ f"-var-file={self.config['state_dir']}/{deployment_name}/.tfvars",
cwd=cwd,
verbose=debug,
)
def export_ssh_key(self):
"""
Export SSH key from Terraform state
"""
debug = self.params["debug"]
deployment_name = self.params["deployment_name"]
shell_command(
f"terraform output -state={self.config['state_dir']}/{deployment_name}/.tfstate -raw ssh_key"
+ f" > {self.config['state_dir']}/{deployment_name}/key.pem && "
+ f"chmod 0600 {self.config['state_dir']}/{deployment_name}/key.pem",
verbose=debug,
)
def run_ansible(self, playbook_name: str, cwd: str):
"""
Run Ansible playbook via shell command
"""
debug = self.params["debug"]
deployment_name = self.params["deployment_name"]
shell_command(
f"ansible-playbook -i {self.config['state_dir']}/{deployment_name}/.inventory "
+ f"{playbook_name}.yml {'-vv' if self.params['debug'] else ''}",
cwd=cwd,
verbose=debug,
)
def run_all_ansible(self):
# run ansible for isaac
if "isaac" in self.params and self.params["isaac"]:
click.echo(colorize_info("* Running Ansible for Isaac Sim..."))
self.run_ansible(playbook_name="isaac", cwd=f"{self.config['ansible_dir']}")
# run ansible for ovami
# todo: move to ./deploy-aws
if "ovami" in self.params and self.params["ovami"]:
click.echo(colorize_info("* Running Ansible for OV AMI..."))
self.run_ansible(playbook_name="ovami", cwd=f"{self.config['ansible_dir']}")
def tf_output(self, key: str, default: str = ""):
"""
Read Terraform output.
Cache read values in self._tf_outputs.
"""
if key not in self.tf_outputs:
debug = self.params["debug"]
deployment_name = self.params["deployment_name"]
r = shell_command(
f"terraform output -state='{self.config['state_dir']}/{deployment_name}/.tfstate' -raw '{key}'",
capture_output=True,
exit_on_error=False,
verbose=debug,
)
if r.returncode == 0:
self.tf_outputs[key] = r.stdout.decode()
else:
if self.params["debug"]:
click.echo(
colorize_error(
f"* Warning: Terraform output '{key}' cannot be read."
),
err=True,
)
self.tf_outputs[key] = default
# update meta file to reflect tf outputs
self.save_meta()
return self.tf_outputs[key]
def upload_user_data(self):
shell_command(
f'./upload "{self.params["deployment_name"]}" '
+ f'{"--debug" if self.params["debug"] else ""}',
cwd=self.config["app_dir"],
verbose=self.params["debug"],
exit_on_error=True,
capture_output=False,
)
# generate ssh connection command for the user
def ssh_connection_command(self, ip: str):
r = f"ssh -i state/{self.params['deployment_name']}/key.pem "
r += f"-o StrictHostKeyChecking=no ubuntu@{ip}"
if self.params["ssh_port"] != 22:
r += f" -p {self.params['ssh_port']}"
return r
def output_deployment_info(self, extra_text: str = "", print_text=True):
"""
Print connection info for the user
Save info to file (_state_dir_/_deployment_name_/info.txt)
"""
isaac = "isaac" in self.params and self.params["isaac"]
ovami = "ovami" in self.params and self.params["ovami"]
vnc_password = self.params["vnc_password"]
deployment_name = self.params["deployment_name"]
# templates
nomachine_instruction = f"""* To connect to __app__ via NoMachine:
0. Download NoMachine client at https://downloads.nomachine.com/, install and launch it.
1. Click "Add" button.
2. Enter Host: "__ip__".
3. In "Configuration" > "Use key-based authentication with a key you provide",
select file "state/{deployment_name}/key.pem".
4. Click "Connect" button.
5. Enter "ubuntu" as a username when prompted.
"""
vnc_instruction = f"""* To connect to __app__ via VNC:
- IP: __ip__
- Port: 5900
- Password: {vnc_password}"""
nonvc_instruction = f"""* To connect to __app__ via noVNC:
1. Open http://__ip__:6080/vnc.html?host=__ip__&port=6080 in your browser.
2. Click "Connect" and use password \"{vnc_password}\""""
# print connection info
instructions_file = f"{self.config['state_dir']}/{deployment_name}/info.txt"
instructions = ""
if isaac:
instructions += f"""{'*' * (29+len(self.tf_output('isaac_ip')))}
* Isaac Sim is deployed at {self.tf_output('isaac_ip')} *
{'*' * (29+len(self.tf_output('isaac_ip')))}
* To connect to Isaac Sim via SSH:
{self.ssh_connection_command(self.tf_output('isaac_ip'))}
{nonvc_instruction}
{nomachine_instruction}""".replace(
"__app__", "Isaac Sim"
).replace(
"__ip__", self.tf_output("isaac_ip")
)
# todo: move to ./deploy-aws
if ovami:
instructions += f"""\n
* OV AMI is deployed at {self.tf_output('ovami_ip')}
* To connect to OV AMI via SSH:
{self.ssh_connection_command(self.tf_output('ovami_ip'))}
* To connect to OV AMI via NICE DCV:
- IP: __ip__
{vnc_instruction}
{nomachine_instruction}
""".replace(
"__app__", "OV AMI"
).replace(
"__ip__", self.tf_output("ovami_ip")
)
# extra text
if len(extra_text) > 0:
instructions += extra_text + "\n"
# print instructions for the user
if print_text:
click.echo(colorize_result("\n" + instructions))
# create <dn>/ directory if it doesn't exist
Path(instructions_file).parent.mkdir(parents=True, exist_ok=True)
# write file
Path(instructions_file).write_text(instructions)
return instructions
| 19,262 | Python | 31.760204 | 116 | 0.53224 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/utils.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
"""
CLI Utils
"""
import json
import os
import subprocess
from glob import glob
from pathlib import Path
import click
from src.python.config import c as config
def colorize_prompt(text):
return click.style(text, fg="bright_cyan", italic=True)
def colorize_error(text):
return click.style(text, fg="bright_red", italic=True)
def colorize_info(text):
return click.style(text, fg="bright_magenta", italic=True)
def colorize_result(text):
return click.style(text, fg="bright_green", italic=True)
def shell_command(
command, verbose=False, cwd=None, exit_on_error=True, capture_output=False
):
"""
Execute shell command, print it if debug is enabled
"""
if verbose:
if cwd is not None:
click.echo(colorize_info(f"* Running `(cd {cwd} && {command})`..."))
else:
click.echo(colorize_info(f"* Running `{command}`..."))
res = subprocess.run(
command,
shell=True,
cwd=cwd,
capture_output=capture_output,
)
if res.returncode == 0:
if verbose and res.stdout is not None:
click.echo(res.stdout.decode())
elif exit_on_error:
if res.stderr is not None:
click.echo(
colorize_error(f"Error: {res.stderr.decode()}"),
err=True,
)
exit(1)
return res
def deployments():
"""List existing deployments by name"""
state_dir = config["state_dir"]
deployments = sorted(
[
os.path.basename(os.path.dirname(d))
for d in glob(os.path.join(state_dir, "*/"))
]
)
return deployments
def read_meta(deployment_name: str, verbose: bool = False):
"""
Read metadata from json file
"""
meta_file = f"{config['state_dir']}/{deployment_name}/meta.json"
if os.path.isfile(meta_file):
data = json.loads(Path(meta_file).read_text())
if verbose:
click.echo(colorize_info(f"* Meta info loaded from '{meta_file}'"))
return data
raise Exception(f"Meta file '{meta_file}' not found")
def read_tf_output(deployment_name, output, verbose=False):
"""
Read terraform output from tfstate file
"""
return (
shell_command(
f"terraform output -state={config['state_dir']}/{deployment_name}/.tfstate -raw {output}",
capture_output=True,
exit_on_error=False,
verbose=verbose,
)
.stdout.decode()
.strip()
)
def format_app_name(app_name):
"""
Format app name for user output
"""
formatted = {
"isaac": "Isaac Sim",
"ovami": "OV AMI",
}
if app_name in formatted:
return formatted[app_name]
return app_name
def format_cloud_name(cloud_name):
"""
Format cloud name for user output
"""
formatted = {
"aws": "AWS",
"azure": "Azure",
"gcp": "GCP",
"alicloud": "Alibaba Cloud",
}
if cloud_name in formatted:
return formatted[cloud_name]
return cloud_name
def gcp_login(verbose=False):
"""
Log into GCP
"""
# detect if we need to re-login
click.echo(colorize_info("* Checking GCP login status..."), nl=False)
res = shell_command(
"gcloud auth application-default print-access-token 2>&1 > /dev/null",
verbose=verbose,
exit_on_error=False,
capture_output=True,
)
logged_in = res.returncode == 0
if logged_in:
click.echo(colorize_info(" logged in!"))
if not logged_in:
click.echo(colorize_info(" not logged in"))
shell_command(
"gcloud auth application-default login --no-launch-browser --disable-quota-project --verbosity none",
verbose=verbose,
)
| 4,426 | Python | 22.42328 | 113 | 0.608676 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/azure.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
"""
Utils for Azure
"""
import click
from src.python.utils import colorize_info, read_meta, shell_command
def azure_login(verbose=False):
"""
Log into Azure
"""
# detect if we need to re-login
logged_in = (
'"Enabled"'
== shell_command(
"az account show --query state",
verbose=verbose,
exit_on_error=False,
capture_output=True,
)
.stdout.decode()
.strip()
)
if not logged_in:
click.echo(colorize_info("* Logging into Azure..."))
shell_command("az login --use-device-code", verbose=verbose)
def azure_stop_instance(vm_id, verbose=False):
shell_command(
f"az vm deallocate --ids {vm_id}",
verbose=verbose,
exit_on_error=True,
capture_output=False,
)
def azure_start_instance(vm_id, verbose=False):
shell_command(
f"az vm start --ids {vm_id}",
verbose=verbose,
exit_on_error=True,
capture_output=False,
)
| 1,639 | Python | 24.230769 | 74 | 0.640635 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/deploy_command.py | # region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
"""
Base deploy- command
"""
import os
import re
import click
import randomname
from pwgen import pwgen
from src.python.config import c as config
from src.python.debug import debug_break # noqa
from src.python.utils import colorize_error, colorize_prompt
class DeployCommand(click.core.Command):
"""
Defines common cli options for "deploy-*" commands.
"""
@staticmethod
def isaac_callback(ctx, param, value):
"""
Called after --isaac option is parsed
"""
# disable isaac instance type selection if isaac is disabled
if value is False:
for p in ctx.command.params:
if p.name.startswith("isaac"):
p.prompt = None
return value
@staticmethod
def deployment_name_callback(ctx, param, value):
# validate
if not re.match("^[a-z0-9\\-]{1,32}$", value):
raise click.BadParameter(
colorize_error(
"Only lower case letters, numbers and '-' are allowed."
+ f" Length should be between 1 and 32 characters ({len(value)} provided)."
)
)
return value
@staticmethod
def ngc_api_key_callback(ctx, param, value):
"""
Validate NGC API key
"""
# fix click bug
if value is None:
return value
# allow "none" as a special value
if "none" == value:
return value
# check if it contains what's allowed
if not re.match("^[A-Za-z0-9]{32,}$", value):
raise click.BadParameter(
colorize_error("Key contains invalid characters or too short.")
)
return value
@staticmethod
def ngc_image_callback(ctx, param, value):
"""
Called after parsing --isaac-image options are parsed
"""
# ignore case
value = value.lower()
if not re.match(
"^nvcr\\.io/[a-z0-9\\-_]+/([a-z0-9\\-_]+/)?[a-z0-9\\-_]+:[a-z0-9\\-_.]+$",
value,
):
raise click.BadParameter(
colorize_error(
"Invalid image name. "
+ "Expected: nvcr.io/<org>/[<team>/]<image>:<tag>"
)
)
return value
@staticmethod
def oige_callback(ctx, param, value):
"""
Called after parsing --oige option
"""
if "" == value:
return config["default_oige_git_checkpoint"]
return value
@staticmethod
def orbit_callback(ctx, param, value):
"""
Called after parsing --orbit option
"""
if "" == value:
return config["default_orbit_git_checkpoint"]
return value
def param_index(self, param_name):
"""
Return index of parameter with given name.
Useful for inserting new parameters at a specific position.
"""
return list(
filter(
lambda param: param[1].name == param_name,
enumerate(self.params),
)
)[0][0]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# add common options
self.params.insert(
len(self.params),
click.core.Option(
("--debug/--no-debug",),
default=False,
show_default=True,
help="Enable debug output.",
),
)
# --prefix
self.params.insert(
len(self.params),
click.core.Option(
("--prefix",),
default=config["default_prefix"],
show_default=True,
help="Prefix for all cloud resources.",
),
)
# --from-image/--not-from-image
self.params.insert(
len(self.params),
click.core.Option(
("--from-image/--not-from-image",),
default=False,
show_default=True,
help="Deploy from pre-built image, from bare OS otherwise.",
),
)
# --in-china
self.params.insert(
len(self.params),
click.core.Option(
("--in-china",),
type=click.Choice(["auto", "yes", "no"]),
prompt=False,
default="auto",
show_default=True,
help="Is deployment in China? (Local mirrors will be used.)",
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--deployment-name", "--dn"),
prompt=colorize_prompt(
'* Deployment Name (lower case letters, numbers and "-")'
),
default=randomname.get_name,
callback=DeployCommand.deployment_name_callback,
show_default="<randomly generated>",
help="Name of the deployment. Used to identify the created cloud resources and files.",
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--existing",),
type=click.Choice(
["ask", "repair", "modify", "replace", "run_ansible"]
),
default="ask",
show_default=True,
help="""What to do if deployment already exists:
\n* 'repair' will try to fix broken deployment without applying new user parameters.
\n* 'modify' will update user selected parameters and attempt to update existing cloud resources.
\n* 'replace' will attempt to delete old deployment's cloud resources first.
\n* 'run_ansible' will re-run Ansible playbooks.""",
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--isaac/--no-isaac",),
default=True,
show_default="yes",
prompt=colorize_prompt("* Deploy Isaac Sim?"),
callback=DeployCommand.isaac_callback,
help="Deploy Isaac Sim (BETA)?",
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--isaac-image",),
default=config["default_isaac_image"],
prompt=colorize_prompt("* Isaac Sim docker image"),
show_default=True,
callback=DeployCommand.ngc_image_callback,
help="Isaac Sim docker image to use.",
),
)
# --oige
help = (
"Install Omni Isaac Gym Envs? Valid values: 'no', "
+ "or <git ref in github.com/NVIDIA-Omniverse/OmniIsaacGymEnvs>"
)
self.params.insert(
len(self.params),
click.core.Option(
("--oige",),
help=help,
default="main",
show_default=True,
prompt=colorize_prompt("* " + help),
callback=DeployCommand.oige_callback,
),
)
# --orbit
help = (
"[EXPERIMENTAL] Install Isaac Sim Orbit? Valid values: 'no', "
+ "or <git ref in github.com/NVIDIA-Omniverse/orbit>"
)
self.params.insert(
len(self.params),
click.core.Option(
("--orbit",),
help=help,
default="no",
show_default=True,
prompt=colorize_prompt("* " + help),
callback=DeployCommand.orbit_callback,
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--ngc-api-key",),
type=str,
prompt=colorize_prompt(
"* NGC API Key (can be obtained at https://ngc.nvidia.com/setup/api-key)"
),
default=os.environ.get("NGC_API_KEY", ""),
show_default='"NGC_API_KEY" environment variable',
help="NGC API Key (can be obtained at https://ngc.nvidia.com/setup/api-key)",
callback=DeployCommand.ngc_api_key_callback,
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--ngc-api-key-check/--no-ngc-api-key-check",),
default=True,
help="Skip NGC API key validity check.",
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--vnc-password",),
default=lambda: pwgen(10),
help="Password for VNC access to DRIVE Sim/Isaac Sim/etc.",
show_default="<randomly generated>",
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--system-user-password",),
default=lambda: pwgen(10),
help="System user password",
show_default="<randomly generated>",
),
)
self.params.insert(
len(self.params),
click.core.Option(
("--ssh-port",),
default=config["default_ssh_port"],
help="SSH port for connecting to the deployed machines.",
show_default=True,
),
)
# --upload/--no-upload
self.params.insert(
len(self.params),
click.core.Option(
("--upload/--no-upload",),
prompt=False,
default=True,
show_default=True,
help=f"Upload user data from \"{config['uploads_dir']}\" to cloud "
+ f"instances (to \"{config['default_remote_uploads_dir']}\")?",
),
)
default_nucleus_admin_password = pwgen(10)
# --omniverse-user
self.params.insert(
len(self.params),
click.core.Option(
("--omniverse-user",),
default=config["default_omniverse_user"],
help="Username for accessing content on the Nucleus server.",
show_default=True,
),
)
# --omniverse-password
self.params.insert(
len(self.params),
click.core.Option(
("--omniverse-password",),
default=default_nucleus_admin_password,
help="Password for accessing content on the Nucleus server.",
show_default="<randomly generated>",
),
)
| 11,460 | Python | 29.975676 | 113 | 0.494503 |
NVIDIA-Omniverse/IsaacSim-Automator/src/python/ngc.test.py | #!/usr/bin/env python3
# region copyright
# Copyright 2023 NVIDIA Corporation
#
# 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.
# endregion
import os
import unittest
from src.python.ngc import check_ngc_access
class Test_NGC_Key_Validation(unittest.TestCase):
INVALID_KEY = "__invalid__"
VALID_KEY = os.environ.get("NGC_API_KEY", "__none__")
def test_invalid_key(self):
"""Test invalid key"""
r = check_ngc_access(self.INVALID_KEY)
self.assertEqual(r, 100)
def test_valid_key(self):
"""Test valid key (should be set in NGC_API_KEY env var)"""
if "__none__" == self.VALID_KEY:
self.skipTest("No NGC_API_KEY env var set")
return
r = check_ngc_access(self.VALID_KEY)
self.assertEqual(r, 0)
if __name__ == "__main__":
unittest.main()
| 1,337 | Python | 27.468085 | 74 | 0.672401 |
NVIDIA-Omniverse/IsaacSim-Automator/src/tests/deployer.test.py | #!/usr/bin/env python3
import unittest
from src.python.config import c
from src.python.deployer import Deployer
from pathlib import Path
class Test_Deployer(unittest.TestCase):
def setUp(self):
self.config = c
self.config["state_dir"] = f"{c['tests_dir']}/res/state"
self.deployer = Deployer(
params={
"debug": False,
"prefix": "isa",
"from_image": False,
"deployment_name": "test-1",
"existing": "ask",
"region": "us-east-1",
"isaac": True,
"isaac_instance_type": "g5.2xlarge",
"isaac_image": "nvcr.io/nvidia/isaac-sim:2022.2.0",
"ngc_api_key": "__ngc_api_key__",
"ngc_api_key_check": True,
"vnc_password": "__vnc_password__",
"omniverse_user": "ovuser",
"omniverse_password": "__omniverse_password__",
"ssh_port": 22,
"upload": True,
"aws_access_key_id": "__aws_access_key_id__",
"aws_secret_access_key": "__aws_secret_access_key__",
},
config=self.config,
)
def tearDown(self):
self.deployer = None
def test_output_deployment_info(self):
self.deployer.output_deployment_info(print_text=False)
file_generated = f"{self.config['state_dir']}/test-1/info.txt"
file_expected = f"{self.config['state_dir']}/test-1/info.expected.txt"
file_generated = Path(file_generated).read_text()
file_expected = Path(file_expected).read_text()
self.assertEqual(file_generated, file_expected)
if __name__ == "__main__":
unittest.main()
| 1,760 | Python | 29.894736 | 78 | 0.526136 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_trigger_intervals.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.replicator.core as rep
with rep.new_layer():
camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0))
# Create simple shapes to manipulate
plane = rep.create.plane(
semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100)
)
spheres = rep.create.sphere(
semantics=[("class", "sphere")], position=(0, 0, 100), count=6
)
# Modify the position every 5 frames
with rep.trigger.on_frame(num_frames=10, interval=5):
with spheres:
rep.modify.pose(
position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)),
scale=rep.distribution.uniform(0.1, 2),
)
# Modify color every frame for 50 frames
with rep.trigger.on_frame(num_frames=50):
with spheres:
rep.randomizer.color(
colors=rep.distribution.normal((0.1, 0.1, 0.1), (1.0, 1.0, 1.0))
)
render_product = rep.create.render_product(camera, (512, 512))
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir="trigger_intervals",
rgb=True,
)
writer.attach([render_product])
| 2,854 | Python | 41.61194 | 84 | 0.709881 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_multiple_semantic_classes.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.replicator.core as rep
with rep.new_layer():
sphere = rep.create.sphere(semantics=[("class", "sphere")], position=(0, 100, 100))
cube = rep.create.cube(semantics=[("class2", "cube")], position=(200, 200, 100))
plane = rep.create.plane(semantics=[("class3", "plane")], scale=10)
def get_shapes():
shapes = rep.get.prims(semantics=[("class", "cube"), ("class", "sphere")])
with shapes:
rep.modify.pose(
position=rep.distribution.uniform((-500, 50, -500), (500, 50, 500)),
rotation=rep.distribution.uniform((0, -180, 0), (0, 180, 0)),
scale=rep.distribution.normal(1, 0.5),
)
return shapes.node
with rep.trigger.on_frame(num_frames=2):
rep.randomizer.register(get_shapes)
# Setup Camera
camera = rep.create.camera(position=(500, 500, 500), look_at=(0, 0, 0))
render_product = rep.create.render_product(camera, (512, 512))
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir="semantics_classes",
rgb=True,
semantic_segmentation=True,
colorize_semantic_segmentation=True,
semantic_types=["class", "class2", "class3"],
)
writer.attach([render_product])
rep.orchestrator.run()
| 2,956 | Python | 41.855072 | 87 | 0.715832 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_scatter_multi_trigger.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
"""
This snippet shows how to setup multiple independent triggers that happen
at different intervals in the simulation.
"""
import omni.graph.core as og
import omni.replicator.core as rep
# A light to see
distance_light = rep.create.light(rotation=(-45, 0, 0), light_type="distant")
# Create a plane to sample on
plane_samp = rep.create.plane(scale=4, rotation=(20, 0, 0))
# Create a larger sphere to sample on the surface of
sphere_samp = rep.create.sphere(scale=2.4, position=(0, 100, -180))
# Create a larger cylinder we do not want to collide with
cylinder = rep.create.cylinder(semantics=[("class", "cylinder")], scale=(2, 1, 2))
def randomize_spheres():
# create small spheres to sample inside the plane
spheres = rep.create.sphere(scale=0.4, count=60)
# scatter small spheres
with spheres:
rep.randomizer.scatter_2d(
surface_prims=[plane_samp, sphere_samp],
no_coll_prims=[cylinder],
check_for_collisions=True,
)
# Add color to small spheres
rep.randomizer.color(
colors=rep.distribution.uniform((0.2, 0.2, 0.2), (1, 1, 1))
)
return spheres.node
rep.randomizer.register(randomize_spheres)
# Trigger will execute 5 times, every-other-frame (interval=2)
with rep.trigger.on_frame(num_frames=5, interval=2):
rep.randomizer.randomize_spheres()
# Trigger will execute 10 times, once every frame
with rep.trigger.on_frame(num_frames=10):
with cylinder:
rep.modify.visibility(rep.distribution.sequence([True, False]))
og.Controller.evaluate_sync() # Only for snippet demonstration preview, not needed for production
rep.orchestrator.preview() # Only for snippet demonstration preview, not needed for production
rp = rep.create.render_product("/OmniverseKit_Persp", (1024, 768))
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(output_dir="scatter_example", rgb=True)
writer.attach([rp])
rep.orchestrator.run()
| 3,612 | Python | 40.056818 | 98 | 0.745847 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_writer_segmentation_colors.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
A snippet showing to how create a custom writer to output specific colors
in the semantic annotator output image.
"""
import omni.replicator.core as rep
from omni.replicator.core import Writer, BackendDispatch, WriterRegistry
class MyWriter(Writer):
def __init__(self, output_dir: str):
self._frame_id = 0
self.backend = BackendDispatch({"paths": {"out_dir": output_dir}})
self.annotators = ["rgb", "semantic_segmentation"]
# Dictionary mapping of label to RGBA color
self.CUSTOM_LABELS = {
"unlabelled": (0, 0, 0, 0),
"sphere": (128, 64, 128, 255),
"cube": (244, 35, 232, 255),
"plane": (102, 102, 156, 255),
}
def write(self, data):
render_products = [k for k in data.keys() if k.startswith("rp_")]
self._write_rgb(data, "rgb")
self._write_segmentation(data, "semantic_segmentation")
self._frame_id += 1
def _write_rgb(self, data, annotator: str):
# Save the rgb data under the correct path
rgb_file_path = f"rgb_{self._frame_id}.png"
self.backend.write_image(rgb_file_path, data[annotator])
def _write_segmentation(self, data, annotator: str):
seg_filepath = f"seg_{self._frame_id}.png"
semantic_seg_data_colorized = rep.tools.colorize_segmentation(
data[annotator]["data"],
data[annotator]["info"]["idToLabels"],
mapping=self.CUSTOM_LABELS,
)
self.backend.write_image(seg_filepath, semantic_seg_data_colorized)
def on_final_frame(self):
self.backend.sync_pending_paths()
# Register new writer
WriterRegistry.register(MyWriter)
# Create a new layer for our work to be performed in.
# This is a good habit to develop for later when working on existing Usd scenes
with rep.new_layer():
light = rep.create.light(light_type="dome")
# Create a simple camera with a position and a point to look at
camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0))
# Create some simple shapes to manipulate
plane = rep.create.plane(
semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100)
)
torus = rep.create.torus(position=(200, 0, 100)) # Torus will be unlabeled
sphere = rep.create.sphere(semantics=[("class", "sphere")], position=(0, 0, 100))
cube = rep.create.cube(semantics=[("class", "cube")], position=(-200, 0, 100))
# Randomize position and scale of each object on each frame
with rep.trigger.on_frame(num_frames=10):
# Creating a group so that our modify.pose operation works on all the shapes at once
with rep.create.group([torus, sphere, cube]):
rep.modify.pose(
position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)),
scale=rep.distribution.uniform(0.1, 2),
)
# Initialize render product and attach a writer
render_product = rep.create.render_product(camera, (1024, 1024))
writer = rep.WriterRegistry.get("MyWriter")
writer.initialize(output_dir="myWriter_output")
writer.attach([render_product])
rep.orchestrator.run() # Run the simulation
| 4,866 | Python | 43.245454 | 92 | 0.690506 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_remove_semantics.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.graph.core as og
import omni.replicator.core as rep
from omni.usd._impl.utils import get_prim_at_path
from pxr import Semantics
from semantics.schema.editor import remove_prim_semantics
# Setup simple scene
with rep.new_layer():
# Simple scene setup
camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0))
# Create simple shapes to manipulate
plane = rep.create.plane(
semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100)
)
cubes = rep.create.cube(
semantics=[("class", "cube")],
position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)),
count=6,
)
spheres = rep.create.sphere(
semantics=[("class", "sphere")],
position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)),
count=6,
)
# Get prims to remove semantics on - Execute this first by itself
my_spheres = rep.get.prims(semantics=[("class", "sphere")])
og.Controller.evaluate_sync() # Trigger an OmniGraph evaluation of the graph to set the values
get_targets = rep.utils.get_node_targets(my_spheres.node, "outputs_prims")
print(get_targets)
# [Sdf.Path('/Replicator/Sphere_Xform'), Sdf.Path('/Replicator/Sphere_Xform_01'), Sdf.Path('/Replicator/Sphere_Xform_02'), Sdf.Path('/Replicator/Sphere_Xform_03'), Sdf.Path('/Replicator/Sphere_Xform_04'), Sdf.Path('/Replicator/Sphere_Xform_05')]
# Loop through each prim_path and remove all semantic data
for prim_path in get_targets:
prim = get_prim_at_path(prim_path)
# print(prim.HasAPI(Semantics.SemanticsAPI))
result = remove_prim_semantics(prim) # To remove all semantics
# result = remove_prim_semantics(prim, label_type='class') # To remove only 'class' semantics
print(result)
| 3,457 | Python | 45.729729 | 245 | 0.731559 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replcator_clear_layer.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.usd
stage = omni.usd.get_context().get_stage()
for layer in stage.GetLayerStack():
if layer.GetDisplayName() == "test":
# del layer
layer.Clear()
| 1,868 | Python | 46.923076 | 84 | 0.770343 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_annotator_segmentation.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
This is an example of how to view annotator data if needed.
"""
import asyncio
import omni.replicator.core as rep
import omni.syntheticdata as sd
async def test_semantics():
cone = rep.create.cone(semantics=[("prim", "cone")], position=(100, 0, 0))
sphere = rep.create.sphere(semantics=[("prim", "sphere")], position=(-100, 0, 0))
invalid_type = rep.create.cube(semantics=[("shape", "boxy")], position=(0, 100, 0))
# Setup semantic filter
# sd.SyntheticData.Get().set_instance_mapping_semantic_filter("prim:*")
cam = rep.create.camera(position=(500, 500, 500), look_at=(0, 0, 0))
rp = rep.create.render_product(cam, (1024, 512))
segmentation = rep.AnnotatorRegistry.get_annotator("semantic_segmentation")
segmentation.attach(rp)
# step_async() tells Omniverse to update, otherwise the annoation buffer could be empty
await rep.orchestrator.step_async()
data = segmentation.get_data()
print(data)
# Example Output:
# {
# "data": array(
# [
# [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, 0, 0, ..., 0, 0, 0],
# [0, 0, 0, ..., 0, 0, 0],
# ],
# dtype=uint32,
# ),
# "info": {
# "_uniqueInstanceIDs": array([1, 1, 1], dtype=uint8),
# "idToLabels": {
# "0": {"class": "BACKGROUND"},
# "2": {"prim": "cone"},
# "3": {"prim": "sphere"},
# "4": {"shape": "boxy"},
# },
# },
# }
asyncio.ensure_future(test_semantics())
| 3,332 | Python | 38.211764 | 91 | 0.653962 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/replicator_multi_object_visibility_toggle.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""This will create a group from a list of objects and
1. Render all the objects together
2. Toggle sole visiblity for each object & render
3. Randomize pose for all objects, repeat
This can be useful for training on object occlusions.
"""
import omni.replicator.core as rep
NUM_POSE_RANDOMIZATIONS = 10
# Make a list-of-lists of True/False for each object
# In this example of 3 objects:
# [[True, True, True]
# [True, False, False]
# [False, True, False]
# [False, False, True]]
def make_visibility_lists(num_objects):
visib = []
# Make an all-visible first pass
visib.append(tuple([True for x in range(num_objects)]))
# List to toggle one object visible at a time
for x in range(num_objects):
sub_vis = []
for i in range(num_objects):
if x == i:
sub_vis.append(True)
else:
sub_vis.append(False)
visib.append(tuple(sub_vis))
return visib
with rep.new_layer():
# Setup camera and simple light
camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0))
light = rep.create.light(rotation=(-45, 45, 0))
# Create simple shapes to manipulate
plane = rep.create.plane(
semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100)
)
torus = rep.create.torus(semantics=[("class", "torus")], position=(200, 0, 100))
sphere = rep.create.sphere(semantics=[("class", "sphere")], position=(0, 0, 100))
cube = rep.create.cube(semantics=[("class", "cube")], position=(-200, 0, 100))
# Create a group of the objects we will be manipulating
# Leaving-out camera, light, and plane from visibility toggling and pose randomization
object_group = rep.create.group([torus, sphere, cube])
# Get the number of objects to toggle, can work with any number of objects
num_objects_to_toggle = len(object_group.get_output_prims()["prims"])
# Create our lists-of-lists for visibility
visibility_sequence = make_visibility_lists(num_objects_to_toggle)
# Trigger to toggle visibility one at a time
with rep.trigger.on_frame(
max_execs=(num_objects_to_toggle + 1) * NUM_POSE_RANDOMIZATIONS
):
with object_group:
rep.modify.visibility(rep.distribution.sequence(visibility_sequence))
# Trigger to randomize position and scale, interval set to number of objects +1(1 extra for the "all visible" frame)
with rep.trigger.on_frame(
max_execs=NUM_POSE_RANDOMIZATIONS, interval=num_objects_to_toggle + 1
):
with object_group:
rep.modify.pose(
position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)),
scale=rep.distribution.uniform(0.1, 2),
)
# Initialize render product and attach writer
render_product = rep.create.render_product(camera, (512, 512))
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir="toggle_multi_visibility",
rgb=True,
semantic_segmentation=True,
)
writer.attach([render_product])
rep.orchestrator.run()
| 4,759 | Python | 40.391304 | 120 | 0.703929 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/snippets/surface_scratches/scratches_randomization.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from pathlib import Path
import carb
import omni.replicator.core as rep
import omni.usd
from pxr import Sdf, UsdGeom
"""
Instructions:
Open the example scene file "scratches_randomization.usda",
located adjacent to this script, in Omniverse prior to using this script
"""
# Get the current Usd "stage". This is where all the scene objects live
stage = omni.usd.get_context().get_stage()
with rep.new_layer():
camera = rep.create.camera(position=(-30, 38, 60), look_at=(0, 0, 0))
render_product = rep.create.render_product(camera, (1280, 720))
# Get Scene cube
cube_prim = stage.GetPrimAtPath("/World/RoundedCube2/Cube/Cube")
# Set the primvars on the cubes once
primvars_api = UsdGeom.PrimvarsAPI(cube_prim)
primvars_api.CreatePrimvar("random_color", Sdf.ValueTypeNames.Float3).Set(
(1.0, 1.0, 1.0)
)
primvars_api.CreatePrimvar("random_intensity", Sdf.ValueTypeNames.Float3).Set(
(1.0, 1.0, 1.0)
)
def change_colors():
# Change color primvars
cubes = rep.get.prims(
path_pattern="/World/RoundedCube2/Cube/Cube", prim_types=["Mesh"]
)
with cubes:
rep.modify.attribute(
"primvars:random_color",
rep.distribution.uniform((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)),
attribute_type="float3",
)
rep.modify.attribute(
"primvars:random_intensity",
rep.distribution.uniform((0.0, 0.0, 0.0), (10.0, 10.0, 10.0)),
attribute_type="float3",
)
return cubes.node
rep.randomizer.register(change_colors)
# Setup randomization of colors, different each frame
with rep.trigger.on_frame(num_frames=10):
rep.randomizer.change_colors()
# (optional) Write output images to disk
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir="~/replicator_examples/box_scratches",
rgb=True,
bounding_box_2d_tight=True,
semantic_segmentation=True,
distance_to_image_plane=True,
)
writer.attach([render_product])
carb.log_info("scratches randomization complete")
| 3,884 | Python | 37.465346 | 84 | 0.697477 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/tutorials/fall_2022_DLI/22_Change_Textures.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.replicator.core as rep
# create new objects to be used in the dataset
with rep.new_layer():
sphere = rep.create.sphere(
semantics=[("class", "sphere")], position=(0, 100, 100), count=5
)
cube = rep.create.cube(
semantics=[("class", "cube")], position=(200, 200, 100), count=5
)
cone = rep.create.cone(
semantics=[("class", "cone")], position=(200, 400, 200), count=10
)
cylinder = rep.create.cylinder(
semantics=[("class", "cylinder")], position=(200, 100, 200), count=5
)
# create new camera & render product and attach to camera
camera = rep.create.camera(position=(0, 0, 1000))
render_product = rep.create.render_product(camera, (1024, 1024))
# create plane if needed (but unused here)
plane = rep.create.plane(scale=10)
# function to get shapes that you've created above, via their semantic labels
def get_shapes():
shapes = rep.get.prims(
semantics=[
("class", "cube"),
("class", "sphere"),
("class", "cone"),
("class", "cylinder"),
]
)
with shapes:
# assign textures to the different objects
rep.randomizer.texture(
textures=[
"omniverse://localhost/NVIDIA/Materials/vMaterials_2/Ground/textures/aggregate_exposed_diff.jpg",
"omniverse://localhost/NVIDIA/Materials/vMaterials_2/Ground/textures/gravel_track_ballast_diff.jpg",
"omniverse://localhost/NVIDIA/Materials/vMaterials_2/Ground/textures/gravel_track_ballast_multi_R_rough_G_ao.jpg",
"omniverse://localhost/NVIDIA/Materials/vMaterials_2/Ground/textures/rough_gravel_rough.jpg",
]
)
# modify pose and distribution
rep.modify.pose(
position=rep.distribution.uniform((-500, 50, -500), (500, 50, 500)),
rotation=rep.distribution.uniform((0, -180, 0), (0, 180, 0)),
scale=rep.distribution.normal(1, 0.5),
)
return shapes.node
# register the get shapes function as a randomizer function
rep.randomizer.register(get_shapes)
# Setup randomization. 100 variations here from 'num_frames'
with rep.trigger.on_frame(num_frames=100):
rep.randomizer.get_shapes()
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(output_dir="~/replicator_examples/dli_example_22", rgb=True)
writer.attach([render_product])
rep.orchestrator.run()
| 4,321 | Python | 43.556701 | 134 | 0.672992 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/tutorials/fall_2022_DLI/03_replicator_advanced.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.replicator.core as rep
with rep.new_layer():
def dome_lights():
lights = rep.create.light(
light_type="Dome",
rotation=(270, 0, 0),
texture=rep.distribution.choice(
[
"omniverse://localhost/NVIDIA/Assets/Skies/Indoor/ZetoCGcom_ExhibitionHall_Interior1.hdr",
"omniverse://localhost/NVIDIA/Assets/Skies/Indoor/ZetoCG_com_WarehouseInterior2b.hdr",
]
),
)
return lights.node
rep.randomizer.register(dome_lights)
conference_tables = (
"omniverse://localhost/NVIDIA/Assets/ArchVis/Commercial/Conference/"
)
# create randomizer function conference table assets.
# This randomization includes placement and rotation of the assets on the surface.
def env_conference_table(size=5):
confTable = rep.randomizer.instantiate(
rep.utils.get_usd_files(conference_tables, recursive=False),
size=size,
mode="scene_instance",
)
with confTable:
rep.modify.pose(
position=rep.distribution.uniform((-500, 0, -500), (500, 0, 500)),
rotation=rep.distribution.uniform((-90, -180, 0), (-90, 180, 0)),
)
return confTable.node
# Register randomization
rep.randomizer.register(env_conference_table)
# Setup camera and attach it to render product
camera = rep.create.camera()
render_product = rep.create.render_product(camera, resolution=(1024, 1024))
surface = rep.create.disk(scale=100, visible=False)
# trigger on frame for an interval
with rep.trigger.on_frame(5):
rep.randomizer.env_conference_table(2)
rep.randomizer.dome_lights()
with camera:
rep.modify.pose(
position=rep.distribution.uniform((-500, 200, 1000), (500, 500, 1500)),
look_at=surface,
)
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(output_dir="~/replicator_examples/dli_example_3", rgb=True)
writer.attach([render_product])
| 3,860 | Python | 40.074468 | 110 | 0.688083 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/tutorials/fall_2022_DLI/01_hello_replicator.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.replicator.core as rep
# Create a new layer for our work to be performed in.
# This is a good habit to develop for later when working on existing Usd scenes
with rep.new_layer():
# Create a simple camera with a position and a point to look at
camera = rep.create.camera(position=(0, 500, 1000), look_at=(0, 0, 0))
# Create some simple shapes to manipulate
plane = rep.create.plane(
semantics=[("class", "plane")], position=(0, -100, 0), scale=(100, 1, 100)
)
torus = rep.create.torus(semantics=[("class", "torus")], position=(200, 0, 100))
sphere = rep.create.sphere(semantics=[("class", "sphere")], position=(0, 0, 100))
cube = rep.create.cube(semantics=[("class", "cube")], position=(-200, 0, 100))
# Randomize position and scale of each object on each frame
with rep.trigger.on_frame(num_frames=10):
# Creating a group so that our modify.pose operation works on all the shapes at once
with rep.create.group([torus, sphere, cube]):
rep.modify.pose(
position=rep.distribution.uniform((-300, 0, -300), (300, 0, 300)),
scale=rep.distribution.uniform(0.1, 2),
)
# Initialize render product and attach a writer
render_product = rep.create.render_product(camera, (1024, 1024))
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir="~/replicator_examples/dli_hello_replicator/",
rgb=True,
semantic_segmentation=True,
bounding_box_2d_tight=True,
)
writer.attach([render_product])
rep.orchestrator.run()
| 3,261 | Python | 46.970588 | 92 | 0.726771 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/tutorials/fall_2022_DLI/physics.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.replicator.core as rep
with rep.new_layer():
# Define paths for the character, the props, the environment and the surface where the assets will be scattered in.
PROPS = "omniverse://localhost/NVIDIA/Assets/Isaac/2022.1/Isaac/Props/YCB/Axis_Aligned_Physics"
SURFACE = (
"omniverse://localhost/NVIDIA/Assets/Scenes/Templates/Basic/display_riser.usd"
)
ENVS = "omniverse://localhost/NVIDIA/Assets/Scenes/Templates/Interior/ZetCG_ExhibitionHall.usd"
# Define randomizer function for Base assets. This randomization includes placement and rotation of the assets on the surface.
def env_props(size=50):
instances = rep.randomizer.instantiate(
rep.utils.get_usd_files(PROPS, recursive=True),
size=size,
mode="scene_instance",
)
with instances:
rep.modify.pose(
position=rep.distribution.uniform((-50, 5, -50), (50, 20, 50)),
rotation=rep.distribution.uniform((0, -180, 0), (0, 180, 0)),
scale=100,
)
rep.physics.rigid_body(
velocity=rep.distribution.uniform((-0, 0, -0), (0, 0, 0)),
angular_velocity=rep.distribution.uniform((-0, 0, -100), (0, 0, 0)),
)
return instances.node
# Register randomization
rep.randomizer.register(env_props)
# Setup the static elements
env = rep.create.from_usd(ENVS)
surface = rep.create.from_usd(SURFACE)
with surface:
rep.physics.collider()
# Setup camera and attach it to render product
camera = rep.create.camera()
render_product = rep.create.render_product(camera, resolution=(1024, 1024))
# sphere lights for extra randomization
def sphere_lights(num):
lights = rep.create.light(
light_type="Sphere",
temperature=rep.distribution.normal(6500, 500),
intensity=rep.distribution.normal(35000, 5000),
position=rep.distribution.uniform((-300, -300, -300), (300, 300, 300)),
scale=rep.distribution.uniform(50, 100),
count=num,
)
return lights.node
rep.randomizer.register(sphere_lights)
# trigger on frame for an interval
with rep.trigger.on_time(interval=2, num=10):
rep.randomizer.env_props(10)
rep.randomizer.sphere_lights(10)
with camera:
rep.modify.pose(
position=rep.distribution.uniform((-50, 20, 100), (50, 50, 150)),
look_at=surface,
)
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir="~/replicator_examples/dli_physics",
rgb=True,
bounding_box_2d_tight=True,
)
writer.attach([render_product])
| 4,509 | Python | 41.952381 | 130 | 0.681082 |
NVIDIA-Omniverse/synthetic-data-examples/omni.replicator/tutorials/fall_2022_DLI/02_background_randomization.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import omni.replicator.core as rep
with rep.new_layer():
def dome_lights():
lights = rep.create.light(
light_type="Dome",
rotation=(270, 0, 0),
texture=rep.distribution.choice(
[
"omniverse://localhost/NVIDIA/Assets/Skies/Cloudy/champagne_castle_1_4k.hdr",
"omniverse://localhost/NVIDIA/Assets/Skies/Clear/evening_road_01_4k.hdr",
"omniverse://localhost/NVIDIA/Assets/Skies/Cloudy/kloofendal_48d_partly_cloudy_4k.hdr",
"omniverse://localhost/NVIDIA/Assets/Skies/Clear/qwantani_4k.hdr",
]
),
)
return lights.node
rep.randomizer.register(dome_lights)
torus = rep.create.torus(semantics=[("class", "torus")], position=(0, -200, 100))
# create surface
surface = rep.create.disk(scale=5, visible=False)
# create camera & render product for the scene
camera = rep.create.camera()
render_product = rep.create.render_product(camera, resolution=(1024, 1024))
with rep.trigger.on_frame(num_frames=10, interval=10):
rep.randomizer.dome_lights()
with rep.create.group([torus]):
rep.modify.pose(
position=rep.distribution.uniform((-100, -100, -100), (200, 200, 200)),
scale=rep.distribution.uniform(0.1, 2),
)
with camera:
rep.modify.pose(
position=rep.distribution.uniform((-500, 200, 1000), (500, 500, 1500)),
look_at=surface,
)
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(output_dir="~/replicator_examples/dli_example_02", rgb=True)
writer.attach([render_product])
# Run Replicator
# rep.orchestrator.run()
| 3,520 | Python | 41.421686 | 107 | 0.685227 |
NVIDIA-Omniverse/synthetic-data-examples/end-to-end-workflows/palletjack_with_tao/palletjack_sdg/standalone_palletjack_sdg.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from omni.isaac.kit import SimulationApp
import os
import argparse
parser = argparse.ArgumentParser("Dataset generator")
parser.add_argument("--headless", type=bool, default=False, help="Launch script headless, default is False")
parser.add_argument("--height", type=int, default=544, help="Height of image")
parser.add_argument("--width", type=int, default=960, help="Width of image")
parser.add_argument("--num_frames", type=int, default=1000, help="Number of frames to record")
parser.add_argument("--distractors", type=str, default="warehouse",
help="Options are 'warehouse' (default), 'additional' or None")
parser.add_argument("--data_dir", type=str, default=os.getcwd() + "/_palletjack_data",
help="Location where data will be output")
args, unknown_args = parser.parse_known_args()
# This is the config used to launch simulation.
CONFIG = {"renderer": "RayTracedLighting", "headless": args.headless,
"width": args.width, "height": args.height, "num_frames": args.num_frames}
simulation_app = SimulationApp(launch_config=CONFIG)
## This is the path which has the background scene in which objects will be added.
ENV_URL = "/Isaac/Environments/Simple_Warehouse/warehouse.usd"
import carb
import omni
import omni.usd
from omni.isaac.core.utils.nucleus import get_assets_root_path
from omni.isaac.core.utils.stage import get_current_stage, open_stage
from pxr import Semantics
import omni.replicator.core as rep
from omni.isaac.core.utils.semantics import get_semantics
# Increase subframes if shadows/ghosting appears of moving objects
# See known issues: https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator.html#known-issues
rep.settings.carb_settings("/omni/replicator/RTSubframes", 4)
# This is the location of the palletjacks in the simready asset library
PALLETJACKS = ["http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Equipment/Pallet_Trucks/Scale_A/PalletTruckScale_A01_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Equipment/Pallet_Trucks/Heavy_Duty_A/HeavyDutyPalletTruck_A01_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Equipment/Pallet_Trucks/Low_Profile_A/LowProfilePalletTruck_A01_PR_NVD_01.usd"]
# The warehouse distractors which will be added to the scene and randomized
DISTRACTORS_WAREHOUSE = 2 * ["/Isaac/Environments/Simple_Warehouse/Props/S_TrafficCone.usd",
"/Isaac/Environments/Simple_Warehouse/Props/S_WetFloorSign.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BarelPlastic_A_01.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BarelPlastic_A_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BarelPlastic_A_03.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BarelPlastic_B_01.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BarelPlastic_B_01.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BarelPlastic_B_03.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BarelPlastic_C_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BottlePlasticA_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BottlePlasticB_01.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BottlePlasticA_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BottlePlasticA_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BottlePlasticD_01.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BottlePlasticE_01.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_BucketPlastic_B.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxB_01_1262.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxB_01_1268.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxB_01_1482.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxB_01_1683.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxB_01_291.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxD_01_1454.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CardBoxD_01_1513.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CratePlastic_A_04.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CratePlastic_B_03.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CratePlastic_B_05.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CratePlastic_C_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_CratePlastic_E_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_PushcartA_02.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_RackPile_04.usd",
"/Isaac/Environments/Simple_Warehouse/Props/SM_RackPile_03.usd"]
## Additional distractors which can be added to the scene
DISTRACTORS_ADDITIONAL = ["/Isaac/Environments/Hospital/Props/Pharmacy_Low.usd",
"/Isaac/Environments/Hospital/Props/SM_BedSideTable_01b.usd",
"/Isaac/Environments/Hospital/Props/SM_BooksSet_26.usd",
"/Isaac/Environments/Hospital/Props/SM_BottleB.usd",
"/Isaac/Environments/Hospital/Props/SM_BottleA.usd",
"/Isaac/Environments/Hospital/Props/SM_BottleC.usd",
"/Isaac/Environments/Hospital/Props/SM_Cart_01a.usd",
"/Isaac/Environments/Hospital/Props/SM_Chair_02a.usd",
"/Isaac/Environments/Hospital/Props/SM_Chair_01a.usd",
"/Isaac/Environments/Hospital/Props/SM_Computer_02b.usd",
"/Isaac/Environments/Hospital/Props/SM_Desk_04a.usd",
"/Isaac/Environments/Hospital/Props/SM_DisposalStand_02.usd",
"/Isaac/Environments/Hospital/Props/SM_FirstAidKit_01a.usd",
"/Isaac/Environments/Hospital/Props/SM_GasCart_01c.usd",
"/Isaac/Environments/Hospital/Props/SM_Gurney_01b.usd",
"/Isaac/Environments/Hospital/Props/SM_HospitalBed_01b.usd",
"/Isaac/Environments/Hospital/Props/SM_MedicalBag_01a.usd",
"/Isaac/Environments/Hospital/Props/SM_Mirror.usd",
"/Isaac/Environments/Hospital/Props/SM_MopSet_01b.usd",
"/Isaac/Environments/Hospital/Props/SM_SideTable_02a.usd",
"/Isaac/Environments/Hospital/Props/SM_SupplyCabinet_01c.usd",
"/Isaac/Environments/Hospital/Props/SM_SupplyCart_01e.usd",
"/Isaac/Environments/Hospital/Props/SM_TrashCan.usd",
"/Isaac/Environments/Hospital/Props/SM_Washbasin.usd",
"/Isaac/Environments/Hospital/Props/SM_WheelChair_01a.usd",
"/Isaac/Environments/Office/Props/SM_WaterCooler.usd",
"/Isaac/Environments/Office/Props/SM_TV.usd",
"/Isaac/Environments/Office/Props/SM_TableC.usd",
"/Isaac/Environments/Office/Props/SM_Recliner.usd",
"/Isaac/Environments/Office/Props/SM_Personenleitsystem_Red1m.usd",
"/Isaac/Environments/Office/Props/SM_Lamp02_162.usd",
"/Isaac/Environments/Office/Props/SM_Lamp02.usd",
"/Isaac/Environments/Office/Props/SM_HandDryer.usd",
"/Isaac/Environments/Office/Props/SM_Extinguisher.usd"]
# The textures which will be randomized for the wall and floor
TEXTURES = ["/Isaac/Materials/Textures/Patterns/nv_asphalt_yellow_weathered.jpg",
"/Isaac/Materials/Textures/Patterns/nv_tile_hexagonal_green_white.jpg",
"/Isaac/Materials/Textures/Patterns/nv_rubber_woven_charcoal.jpg",
"/Isaac/Materials/Textures/Patterns/nv_granite_tile.jpg",
"/Isaac/Materials/Textures/Patterns/nv_tile_square_green.jpg",
"/Isaac/Materials/Textures/Patterns/nv_marble.jpg",
"/Isaac/Materials/Textures/Patterns/nv_brick_reclaimed.jpg",
"/Isaac/Materials/Textures/Patterns/nv_concrete_aged_with_lines.jpg",
"/Isaac/Materials/Textures/Patterns/nv_wooden_wall.jpg",
"/Isaac/Materials/Textures/Patterns/nv_stone_painted_grey.jpg",
"/Isaac/Materials/Textures/Patterns/nv_wood_shingles_brown.jpg",
"/Isaac/Materials/Textures/Patterns/nv_tile_hexagonal_various.jpg",
"/Isaac/Materials/Textures/Patterns/nv_carpet_abstract_pattern.jpg",
"/Isaac/Materials/Textures/Patterns/nv_wood_siding_weathered_green.jpg",
"/Isaac/Materials/Textures/Patterns/nv_animalfur_pattern_greys.jpg",
"/Isaac/Materials/Textures/Patterns/nv_artificialgrass_green.jpg",
"/Isaac/Materials/Textures/Patterns/nv_bamboo_desktop.jpg",
"/Isaac/Materials/Textures/Patterns/nv_brick_reclaimed.jpg",
"/Isaac/Materials/Textures/Patterns/nv_brick_red_stacked.jpg",
"/Isaac/Materials/Textures/Patterns/nv_fireplace_wall.jpg",
"/Isaac/Materials/Textures/Patterns/nv_fabric_square_grid.jpg",
"/Isaac/Materials/Textures/Patterns/nv_granite_tile.jpg",
"/Isaac/Materials/Textures/Patterns/nv_marble.jpg",
"/Isaac/Materials/Textures/Patterns/nv_gravel_grey_leaves.jpg",
"/Isaac/Materials/Textures/Patterns/nv_plastic_blue.jpg",
"/Isaac/Materials/Textures/Patterns/nv_stone_red_hatch.jpg",
"/Isaac/Materials/Textures/Patterns/nv_stucco_red_painted.jpg",
"/Isaac/Materials/Textures/Patterns/nv_rubber_woven_charcoal.jpg",
"/Isaac/Materials/Textures/Patterns/nv_stucco_smooth_blue.jpg",
"/Isaac/Materials/Textures/Patterns/nv_wood_shingles_brown.jpg",
"/Isaac/Materials/Textures/Patterns/nv_wooden_wall.jpg"]
def update_semantics(stage, keep_semantics=[]):
""" Remove semantics from the stage except for keep_semantic classes"""
for prim in stage.Traverse():
if prim.HasAPI(Semantics.SemanticsAPI):
processed_instances = set()
for property in prim.GetProperties():
is_semantic = Semantics.SemanticsAPI.IsSemanticsAPIPath(property.GetPath())
if is_semantic:
instance_name = property.SplitName()[1]
if instance_name in processed_instances:
# Skip repeated instance, instances are iterated twice due to their two semantic properties (class, data)
continue
processed_instances.add(instance_name)
sem = Semantics.SemanticsAPI.Get(prim, instance_name)
type_attr = sem.GetSemanticTypeAttr()
data_attr = sem.GetSemanticDataAttr()
for semantic_class in keep_semantics:
# Check for our data classes needed for the model
if data_attr.Get() == semantic_class:
continue
else:
# remove semantics of all other prims
prim.RemoveProperty(type_attr.GetName())
prim.RemoveProperty(data_attr.GetName())
prim.RemoveAPI(Semantics.SemanticsAPI, instance_name)
# needed for loading textures correctly
def prefix_with_isaac_asset_server(relative_path):
assets_root_path = get_assets_root_path()
if assets_root_path is None:
raise Exception("Nucleus server not found, could not access Isaac Sim assets folder")
return assets_root_path + relative_path
def full_distractors_list(distractor_type="warehouse"):
"""Distractor type allowed are warehouse, additional or None. They load corresponding objects and add
them to the scene for DR"""
full_dist_list = []
if distractor_type == "warehouse":
for distractor in DISTRACTORS_WAREHOUSE:
full_dist_list.append(prefix_with_isaac_asset_server(distractor))
elif distractor_type == "additional":
for distractor in DISTRACTORS_ADDITIONAL:
full_dist_list.append(prefix_with_isaac_asset_server(distractor))
else:
print("No Distractors being added to the current scene for SDG")
return full_dist_list
def full_textures_list():
full_tex_list = []
for texture in TEXTURES:
full_tex_list.append(prefix_with_isaac_asset_server(texture))
return full_tex_list
def add_palletjacks():
rep_obj_list = [rep.create.from_usd(palletjack_path, semantics=[("class", "palletjack")], count=2) for palletjack_path in PALLETJACKS]
rep_palletjack_group = rep.create.group(rep_obj_list)
return rep_palletjack_group
def add_distractors(distractor_type="warehouse"):
full_distractors = full_distractors_list(distractor_type)
distractors = [rep.create.from_usd(distractor_path, count=1) for distractor_path in full_distractors]
distractor_group = rep.create.group(distractors)
return distractor_group
# This will handle replicator
def run_orchestrator():
rep.orchestrator.run()
# Wait until started
while not rep.orchestrator.get_is_started():
simulation_app.update()
# Wait until stopped
while rep.orchestrator.get_is_started():
simulation_app.update()
rep.BackendDispatch.wait_until_done()
rep.orchestrator.stop()
def main():
# Open the environment in a new stage
print(f"Loading Stage {ENV_URL}")
open_stage(prefix_with_isaac_asset_server(ENV_URL))
stage = get_current_stage()
# Run some app updates to make sure things are properly loaded
for i in range(100):
if i % 10 == 0:
print(f"App uppdate {i}..")
simulation_app.update()
textures = full_textures_list()
rep_palletjack_group = add_palletjacks()
rep_distractor_group = add_distractors(distractor_type=args.distractors)
# We only need labels for the palletjack objects
update_semantics(stage=stage, keep_semantics=["palletjack"])
# Create camera with Replicator API for gathering data
cam = rep.create.camera(clipping_range=(0.1, 1000000))
# trigger replicator pipeline
with rep.trigger.on_frame(num_frames=CONFIG["num_frames"]):
# Move the camera around in the scene, focus on the center of warehouse
with cam:
rep.modify.pose(position=rep.distribution.uniform((-9.2, -11.8, 0.4), (7.2, 15.8, 4)),
look_at=(0, 0, 0))
# Get the Palletjack body mesh and modify its color
with rep.get.prims(path_pattern="SteerAxles"):
rep.randomizer.color(colors=rep.distribution.uniform((0, 0, 0), (1, 1, 1)))
# Randomize the pose of all the added palletjacks
with rep_palletjack_group:
rep.modify.pose(position=rep.distribution.uniform((-6, -6, 0), (6, 12, 0)),
rotation=rep.distribution.uniform((0, 0, 0), (0, 0, 360)),
scale=rep.distribution.uniform((0.01, 0.01, 0.01), (0.01, 0.01, 0.01)))
# Modify the pose of all the distractors in the scene
with rep_distractor_group:
rep.modify.pose(position=rep.distribution.uniform((-6, -6, 0), (6, 12, 0)),
rotation=rep.distribution.uniform((0, 0, 0), (0, 0, 360)),
scale=rep.distribution.uniform(1, 1.5))
# Randomize the lighting of the scene
with rep.get.prims(path_pattern="RectLight"):
rep.modify.attribute("color", rep.distribution.uniform((0, 0, 0), (1, 1, 1)))
rep.modify.attribute("intensity", rep.distribution.normal(100000.0, 600000.0))
rep.modify.visibility(rep.distribution.choice([True, False, False, False, False, False, False]))
# select floor material
random_mat_floor = rep.create.material_omnipbr(diffuse_texture=rep.distribution.choice(textures),
roughness=rep.distribution.uniform(0, 1),
metallic=rep.distribution.choice([0, 1]),
emissive_texture=rep.distribution.choice(textures),
emissive_intensity=rep.distribution.uniform(0, 1000),)
with rep.get.prims(path_pattern="SM_Floor"):
rep.randomizer.materials(random_mat_floor)
# select random wall material
random_mat_wall = rep.create.material_omnipbr(diffuse_texture=rep.distribution.choice(textures),
roughness=rep.distribution.uniform(0, 1),
metallic=rep.distribution.choice([0, 1]),
emissive_texture=rep.distribution.choice(textures),
emissive_intensity=rep.distribution.uniform(0, 1000),)
with rep.get.prims(path_pattern="SM_Wall"):
rep.randomizer.materials(random_mat_wall)
# Set up the writer
writer = rep.WriterRegistry.get("KittiWriter")
# output directory of writer
output_directory = args.data_dir
print("Outputting data to ", output_directory)
# use writer for bounding boxes, rgb and segmentation
writer.initialize(output_dir=output_directory,
omit_semantic_type=True,)
# attach camera render products to wrieter so that data is outputted
RESOLUTION = (CONFIG["width"], CONFIG["height"])
render_product = rep.create.render_product(cam, RESOLUTION)
writer.attach(render_product)
# run rep pipeline
run_orchestrator()
simulation_app.update()
if __name__ == "__main__":
try:
main()
except Exception as e:
carb.log_error(f"Exception: {e}")
import traceback
traceback.print_exc()
finally:
simulation_app.close()
| 20,199 | Python | 52.439153 | 191 | 0.634388 |
NVIDIA-Omniverse/synthetic-data-examples/end-to-end-workflows/object_detection_fruit/training/code/visualize.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import json
import hashlib
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from optparse import OptionParser
"""
Takes in the data from a specific label id and maps it to the proper color for the bounding box
"""
def data_to_colour(data):
if isinstance(data, str):
data = bytes(data, "utf-8")
else:
data = bytes(data)
m = hashlib.sha256()
m.update(data)
key = int(m.hexdigest()[:8], 16)
r = ((((key >> 0) & 0xFF) + 1) * 33) % 255
g = ((((key >> 8) & 0xFF) + 1) * 33) % 255
b = ((((key >> 16) & 0xFF) + 1) * 33) % 255
# illumination normalization to 128
inv_norm_i = 128 * (3.0 / (r + g + b))
return (
int(r * inv_norm_i) / 255,
int(g * inv_norm_i) / 255,
int(b * inv_norm_i) / 255,
)
"""
Takes in the path to the rgb image for the background, then it takes bounding box data, the labels and the place to store the visualization. It outputs a colorized bounding box.
"""
def colorize_bbox_2d(rgb_path, data, id_to_labels, file_path):
rgb_img = Image.open(rgb_path)
colors = [data_to_colour(bbox["semanticId"]) for bbox in data]
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(rgb_img)
for bbox_2d, color, index in zip(data, colors, range(len(data))):
labels = id_to_labels[str(index)]
rect = patches.Rectangle(
xy=(bbox_2d["x_min"], bbox_2d["y_min"]),
width=bbox_2d["x_max"] - bbox_2d["x_min"],
height=bbox_2d["y_max"] - bbox_2d["y_min"],
edgecolor=color,
linewidth=2,
label=labels,
fill=False,
)
ax.add_patch(rect)
plt.legend(loc="upper left")
plt.savefig(file_path)
"""
Parses command line options. Requires input directory, output directory, and number for image to use.
"""
def parse_input():
usage = "usage: visualize.py [options] arg1 arg2 arg3"
parser = OptionParser(usage)
parser.add_option(
"-d",
"--data_dir",
dest="data_dir",
help="Directory location for Omniverse synthetic data",
)
parser.add_option(
"-o", "--out_dir", dest="out_dir", help="Directory location for output image"
)
parser.add_option(
"-n", "--number", dest="number", help="Number of image to use for visualization"
)
(options, args) = parser.parse_args()
return options, args
def main():
options, args = parse_input()
out_dir = options.data_dir
rgb = "png/rgb_" + options.number + ".png"
rgb_path = os.path.join(out_dir, rgb)
bbox2d_tight_file_name = "npy/bounding_box_2d_tight_" + options.number + ".npy"
data = np.load(os.path.join(options.data_dir, bbox2d_tight_file_name))
# Check for labels
bbox2d_tight_labels_file_name = (
"json/bounding_box_2d_tight_labels_" + options.number + ".json"
)
with open(
os.path.join(options.data_dir, bbox2d_tight_labels_file_name), "r"
) as json_data:
bbox2d_tight_id_to_labels = json.load(json_data)
# colorize and save image
colorize_bbox_2d(
rgb_path,
data,
bbox2d_tight_id_to_labels,
os.path.join(options.out_dir, "bbox2d_tight.png"),
)
if __name__ == "__main__":
main()
| 5,013 | Python | 32.651006 | 177 | 0.658687 |
NVIDIA-Omniverse/synthetic-data-examples/end-to-end-workflows/object_detection_fruit/training/code/export.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import os
import torch
import torchvision
from optparse import OptionParser
def parse_input():
usage = "usage: export.py [options] arg1 "
parser = OptionParser(usage)
parser.add_option(
"-d",
"--pytorch_dir",
dest="pytorch_dir",
help="Location of output PyTorch model",
)
parser.add_option(
"-o",
"--output_dir",
dest="output_dir",
help="Export and save ONNX model to this path",
)
(options, args) = parser.parse_args()
return options, args
def main():
torch.manual_seed(0)
options, args = parse_input()
model = torch.load(options.pytorch_dir)
model.eval()
OUTPUT_DIR = options.output_dir
os.makedirs(OUTPUT_DIR, exist_ok=True)
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(
weights="DEFAULT", num_classes=91
)
model.eval()
dummy_input = torch.rand(1, 3, 1024, 1024)
torch.onnx.export(
model,
dummy_input,
os.path.join(OUTPUT_DIR, "model.onnx"),
opset_version=11,
input_names=["input"],
output_names=["output"],
)
if __name__ == "__main__":
main()
| 2,865 | Python | 33.119047 | 84 | 0.704363 |
NVIDIA-Omniverse/synthetic-data-examples/end-to-end-workflows/object_detection_fruit/training/code/train.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from PIL import Image
import os
import numpy as np
import torch
import torch.utils.data
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision import transforms as T
import json
import shutil
from optparse import OptionParser
from torch.utils.tensorboard import SummaryWriter
class FruitDataset(torch.utils.data.Dataset):
def __init__(self, root, transforms):
self.root = root
self.transforms = transforms
list_ = os.listdir(root)
for file_ in list_:
name, ext = os.path.splitext(file_)
ext = ext[1:]
if ext == "":
continue
if os.path.exists(root + "/" + ext):
shutil.move(root + "/" + file_, root + "/" + ext + "/" + file_)
else:
os.makedirs(root + "/" + ext)
shutil.move(root + "/" + file_, root + "/" + ext + "/" + file_)
self.imgs = list(sorted(os.listdir(os.path.join(root, "png"))))
self.label = list(sorted(os.listdir(os.path.join(root, "json"))))
self.box = list(sorted(os.listdir(os.path.join(root, "npy"))))
def __getitem__(self, idx):
img_path = os.path.join(self.root, "png", self.imgs[idx])
img = Image.open(img_path).convert("RGB")
label_path = os.path.join(self.root, "json", self.label[idx])
with open(os.path.join("root", label_path), "r") as json_data:
json_labels = json.load(json_data)
box_path = os.path.join(self.root, "npy", self.box[idx])
dat = np.load(str(box_path))
boxes = []
labels = []
for i in dat:
obj_val = i[0]
xmin = torch.as_tensor(np.min(i[1]), dtype=torch.float32)
xmax = torch.as_tensor(np.max(i[3]), dtype=torch.float32)
ymin = torch.as_tensor(np.min(i[2]), dtype=torch.float32)
ymax = torch.as_tensor(np.max(i[4]), dtype=torch.float32)
if (ymax > ymin) & (xmax > xmin):
boxes.append([xmin, ymin, xmax, ymax])
area = (xmax - xmin) * (ymax - ymin)
labels += [json_labels.get(str(obj_val)).get("class")]
label_dict = {}
static_labels = {
"apple": 0,
"avocado": 1,
"kiwi": 2,
"lime": 3,
"lychee": 4,
"pomegranate": 5,
"onion": 6,
"strawberry": 7,
"lemon": 8,
"orange": 9,
}
labels_out = []
for i in range(len(labels)):
label_dict[i] = labels[i]
for i in label_dict:
fruit = label_dict[i]
final_fruit_label = static_labels[fruit]
labels_out += [final_fruit_label]
target = {}
target["boxes"] = torch.as_tensor(boxes, dtype=torch.float32)
target["labels"] = torch.as_tensor(labels_out, dtype=torch.int64)
target["image_id"] = torch.tensor([idx])
target["area"] = area
if self.transforms is not None:
img = self.transforms(img)
return img, target
def __len__(self):
return len(self.imgs)
"""
Parses command line options. Requires input data directory, output torch file, and number epochs used to train.
"""
def parse_input():
usage = "usage: train.py [options] arg1 arg2 "
parser = OptionParser(usage)
parser.add_option(
"-d",
"--data_dir",
dest="data_dir",
help="Directory location for Omniverse synthetic data.",
)
parser.add_option(
"-o",
"--output_file",
dest="output_file",
help="Save torch model to this file and location (file ending in .pth)",
)
parser.add_option(
"-e",
"--epochs",
dest="epochs",
help="Give number of epochs to be used for training",
)
(options, args) = parser.parse_args()
return options, args
def get_transform(train):
transforms = []
transforms.append(T.PILToTensor())
transforms.append(T.ConvertImageDtype(torch.float))
return T.Compose(transforms)
def collate_fn(batch):
return tuple(zip(*batch))
def create_model(num_classes):
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights="DEFAULT")
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
return model
def main():
writer = SummaryWriter()
options, args = parse_input()
dataset = FruitDataset(options.data_dir, get_transform(train=True))
train_size = int(len(dataset) * 0.7)
valid_size = int(len(dataset) * 0.2)
test_size = len(dataset) - valid_size - train_size
train, valid, test = torch.utils.data.random_split(
dataset, [train_size, valid_size, test_size]
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=16, shuffle=True, num_workers=4, collate_fn=collate_fn
)
validloader = torch.utils.data.DataLoader(
valid, batch_size=16, shuffle=True, num_workers=4, collate_fn=collate_fn
)
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
num_classes = 10
num_epochs = int(options.epochs)
model = create_model(num_classes)
model.to(device)
params = [p for p in model.parameters() if p.requires_grad]
optimizer = torch.optim.SGD(params, lr=0.001)
len_dataloader = len(data_loader)
model.train()
for epoch in range(num_epochs):
optimizer.zero_grad()
i = 0
for imgs, annotations in data_loader:
i += 1
imgs = list(img.to(device) for img in imgs)
annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations]
loss_dict = model(imgs, annotations)
losses = sum(loss for loss in loss_dict.values())
writer.add_scalar("Loss/train", losses, epoch)
losses.backward()
optimizer.step()
print(f"Iteration: {i}/{len_dataloader}, Loss: {losses}")
writer.close()
torch.save(model, options.output_file)
if __name__ == "__main__":
main()
| 7,902 | Python | 32.487288 | 111 | 0.621362 |
NVIDIA-Omniverse/synthetic-data-examples/end-to-end-workflows/object_detection_fruit/data_generation/code/generate_data_gui.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import datetime
now = datetime.datetime.now()
from functools import partial
import omni.replicator.core as rep
with rep.new_layer():
# Define paths for the character, the props, the environment and the surface where the assets will be scattered in.
CRATE = "omniverse://localhost/NVIDIA/Samples/Marbles/assets/standalone/SM_room_crate_3/SM_room_crate_3.usd"
SURFACE = (
"omniverse://localhost/NVIDIA/Assets/Scenes/Templates/Basic/display_riser.usd"
)
ENVS = "omniverse://localhost/NVIDIA/Assets/Scenes/Templates/Interior/ZetCG_ExhibitionHall.usd"
FRUIT_PROPS = {
"apple": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Fruit/Apple.usd",
"avocado": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Fruit/Avocado01.usd",
"kiwi": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Fruit/Kiwi01.usd",
"lime": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Fruit/Lime01.usd",
"lychee": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Fruit/Lychee01.usd",
"pomegranate": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Fruit/Pomegranate01.usd",
"onion": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Vegetables/RedOnion.usd",
"strawberry": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Food/Berries/strawberry.usd",
"lemon": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Decor/Tchotchkes/Lemon_01.usd",
"orange": "omniverse://localhost/NVIDIA/Assets/ArchVis/Residential/Decor/Tchotchkes/Orange_01.usd",
}
# Define randomizer function for Base assets. This randomization includes placement and rotation of the assets on the surface.
def random_props(file_name, class_name, max_number=1, one_in_n_chance=3):
instances = rep.randomizer.instantiate(
file_name, size=max_number, mode="scene_instance"
)
print(file_name)
with instances:
rep.modify.semantics([("class", class_name)])
rep.modify.pose(
position=rep.distribution.uniform((-8, 5, -25), (8, 30, 25)),
rotation=rep.distribution.uniform((-180, -180, -180), (180, 180, 180)),
scale=rep.distribution.uniform((0.8), (1.2)),
)
rep.modify.visibility(
rep.distribution.choice([True], [False] * (one_in_n_chance))
)
return instances.node
# Define randomizer function for sphere lights.
def sphere_lights(num):
lights = rep.create.light(
light_type="Sphere",
temperature=rep.distribution.normal(6500, 500),
intensity=rep.distribution.normal(30000, 5000),
position=rep.distribution.uniform((-300, -300, -300), (300, 300, 300)),
scale=rep.distribution.uniform(50, 100),
count=num,
)
return lights.node
rep.randomizer.register(random_props)
# Setup the static elements
env = rep.create.from_usd(ENVS)
surface = rep.create.from_usd(SURFACE)
with surface:
rep.physics.collider()
crate = rep.create.from_usd(CRATE)
with crate:
rep.physics.collider("none")
rep.physics.mass(mass=10000)
rep.modify.pose(position=(0, 20, 0), rotation=(0, 0, 90))
# Setup camera and attach it to render product
camera = rep.create.camera()
render_product = rep.create.render_product(camera, resolution=(1024, 1024))
rep.randomizer.register(sphere_lights)
# trigger on frame for an interval
with rep.trigger.on_frame(num_frames=100):
for n, f in FRUIT_PROPS.items():
random_props(f, n)
rep.randomizer.sphere_lights(5)
with camera:
rep.modify.pose(
position=rep.distribution.uniform((-3, 114, -17), (-1, 116, -15)),
look_at=(0, 20, 0),
)
# Initialize and attach writer
writer = rep.WriterRegistry.get("BasicWriter")
now = now.strftime("%Y-%m-%d")
output_dir = "fruit_data_" + now
writer.initialize(output_dir=output_dir, rgb=True, bounding_box_2d_tight=True)
writer.attach([render_product])
| 5,923 | Python | 47.162601 | 130 | 0.690866 |
NVIDIA-Omniverse/synthetic-data-examples/end-to-end-workflows/object_detection_fruit/deployment/code/deploy.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: BSD-3-Clause
#
# Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import tritonclient.grpc as grpcclient
from optparse import OptionParser
# load image data
import cv2
import numpy as np
from matplotlib import pyplot as plt
import subprocess
def install(name):
subprocess.call(["pip", "install", name])
"""
Parses command line options. Requires input sample png
"""
def parse_input():
usage = "usage: deploy.py [options] arg1 "
parser = OptionParser(usage)
parser.add_option(
"-p", "--png", dest="png", help="Directory location for single sample image."
)
(options, args) = parser.parse_args()
return options, args
def main():
options, args = parse_input()
target_width, target_height = 1024, 1024
# add path to test image
image_sample = options.png
image_bgr = cv2.imread(image_sample)
image_bgr
image_bgr = cv2.resize(image_bgr, (target_width, target_height))
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
image = np.float32(image_rgb)
# preprocessing
image = image / 255
image = np.moveaxis(image, -1, 0) # HWC to CHW
image = image[np.newaxis, :] # add batch dimension
image = np.float32(image)
plt.imshow(image_rgb)
inference_server_url = "0.0.0.0:9001"
triton_client = grpcclient.InferenceServerClient(url=inference_server_url)
# find out info about model
model_name = "fasterrcnn_resnet50"
triton_client.get_model_config(model_name)
# create input
input_name = "input"
inputs = [grpcclient.InferInput(input_name, image.shape, "FP32")]
inputs[0].set_data_from_numpy(image)
output_name = "output"
outputs = [grpcclient.InferRequestedOutput("output")]
results = triton_client.infer(model_name, inputs, outputs=outputs)
output = results.as_numpy("output")
# annotate
annotated_image = image_bgr.copy()
if output.size > 0: # ensure something is found
for box in output:
box_top_left = int(box[0]), int(box[1])
box_bottom_right = int(box[2]), int(box[3])
text_origin = int(box[0]), int(box[3])
border_color = (50, 0, 100)
text_color = (255, 255, 255)
font_scale = 0.9
thickness = 1
# bounding box
cv2.rectangle(
annotated_image,
box_top_left,
box_bottom_right,
border_color,
thickness=5,
lineType=cv2.LINE_8,
)
plt.imshow(cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB))
if __name__ == "__main__":
main()
| 4,261 | Python | 31.287879 | 85 | 0.680357 |
NVIDIA-Omniverse/synthetic-data-examples/training_examples/sdg_pallet_model/predict.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 argparse
import utils
import cv2
import torch
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument(
"engine",
type=str,
help="The file path of the TensorRT engine."
)
parser.add_argument(
"image",
type=str,
help="The file path of the image provided as input for inference."
)
parser.add_argument(
"--output",
type=str,
default=None,
help="The path to output the inference visualization."
)
parser.add_argument(
"--inference-size",
type=str,
default="512x512",
help="The height and width that the image is resized to for inference."
" Denoted as (height)x(width)."
)
parser.add_argument(
"--peak-window",
type=str,
default="7x7",
help="The size of the window used when finding local peaks. Denoted as "
" (window_height)x(window_width)."
)
parser.add_argument(
'--peak-threshold',
type=float,
default=0.5,
help="The heatmap threshold to use when finding peaks. Values must be "
" larger than this value to be considered peaks."
)
parser.add_argument(
'--line-thickness',
type=int,
default=1,
help="The line thickness for drawn boxes"
)
args = parser.parse_args()
# Parse inference height, width from arguments
inference_size = tuple(int(x) for x in args.inference_size.split('x'))
peak_window = tuple(int(x) for x in args.peak_window.split('x'))
if args.output is None:
output_path = '.'.join(args.image.split('.')[:-1]) + "_output.jpg"
else:
output_path = args.output
# Create offset grid
offset_grid = utils.make_offset_grid(inference_size).to("cuda")
# Load model
model = utils.load_trt_engine_wrapper(
args.engine,
input_names=["input"],
output_names=["heatmap", "vectormap"]
)
# Load image
image = cv2.imread(args.image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Pad and resize image (aspect ratio preserving resize)
image, _, _ = utils.pad_resize(image, inference_size)
with torch.no_grad():
# Format image for inference
x = utils.format_bgr8_image(image)
x = x.to("cuda")
# Execute model
heatmap, vectormap = model(x)
# Scale and offset vectormap
keypointmap = utils.vectormap_to_keypointmap(
offset_grid,
vectormap
)
# Find local peaks
peak_mask = utils.find_heatmap_peak_mask(
heatmap,
peak_window,
args.peak_threshold
)
# Extract keypoints at local peak
keypoints = keypointmap[0][peak_mask[0, 0]]
# Draw
vis_image = utils.draw_box(
image,
keypoints,
color=(118, 186, 0),
thickness=args.line_thickness
)
vis_image = cv2.cvtColor(vis_image, cv2.COLOR_RGB2BGR)
cv2.imwrite(output_path, vis_image)
| 3,833 | Python | 26.191489 | 98 | 0.610749 |
NVIDIA-Omniverse/synthetic-data-examples/training_examples/sdg_pallet_model/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 torch
import torch.nn.functional as F
import numpy as np
import cv2
import einops
import tensorrt as trt
import torch2trt
from typing import Sequence
BOX_EDGES = [
[0, 1],
[1, 5],
[5, 4],
[4, 0],
[2, 3],
[3, 7],
[7, 6],
[6, 2],
[0, 2],
[1, 3],
[4, 6],
[5, 7]
]
def make_offset_grid(
size,
stride=(1, 1)
):
grid = torch.stack(
torch.meshgrid(
stride[0] * (torch.arange(size[0]) + 0.5),
stride[1] * (torch.arange(size[1]) + 0.5)
),
dim=-1
)
return grid
def vectormap_to_keypointmap(
offset_grid,
vector_map,
vector_scale: float = 1./256.
):
vector_map = vector_map / vector_scale
keypoint_map = einops.rearrange(vector_map, "b (k d) h w -> b h w k d", d=2)
keypoint_map = keypoint_map + offset_grid[:, :, None, :]
# yx -> xy
keypoint_map = keypoint_map[..., [1, 0]]
return keypoint_map
def find_heatmap_peak_mask(heatmap, window=3, threshold=0.5):
all_indices = torch.arange(
heatmap.numel(),
device=heatmap.device
)
all_indices = all_indices.reshape(heatmap.shape)
if isinstance(window, int):
window = (window, window)
values, max_indices = F.max_pool2d_with_indices(
heatmap,
kernel_size=window,
stride=1,
padding=(window[0] // 2, window[1] // 2)
)
is_above_threshold = heatmap >= threshold
is_max = max_indices == all_indices
is_peak = is_above_threshold & is_max
return is_peak
def draw_box(image_bgr, keypoints, color=(118, 186, 0), thickness=1):
num_objects = int(keypoints.shape[0])
for i in range(num_objects):
keypoints_i = keypoints[i]
kps_i = [(int(x), int(y)) for x, y in keypoints_i]
edges = BOX_EDGES
for e in edges:
cv2.line(
image_bgr,
kps_i[e[0]],
kps_i[e[1]],
(118, 186, 0),
thickness=thickness
)
return image_bgr
def pad_resize(image, output_shape):
ar_i = image.shape[1] / image.shape[0]
ar_o = output_shape[1] / output_shape[0]
# resize
if ar_i > ar_o:
w_i = output_shape[1]
h_i = min(int(w_i / ar_i), output_shape[0])
else:
h_i = output_shape[0]
w_i = min(int(h_i * ar_i), output_shape[1])
# paste
pad_left = (output_shape[1] - w_i) // 2
pad_top = (output_shape[0] - h_i) // 2
image_resize = cv2.resize(image, (w_i, h_i))
out = np.zeros_like(
image,
shape=(output_shape[0], output_shape[1], image.shape[2])
)
out[pad_top:pad_top + h_i, pad_left:pad_left + w_i] = image_resize
pad = (pad_top, pad_left)
scale = (image.shape[0] / h_i, image.shape[1] / w_i)
return out, pad, scale
def load_trt_engine(path: str):
with trt.Logger() as logger, trt.Runtime(logger) as runtime:
with open(path, 'rb') as f:
engine_bytes = f.read()
engine = runtime.deserialize_cuda_engine(engine_bytes)
return engine
def load_trt_engine_wrapper(
path: str,
input_names: Sequence,
output_names: Sequence
):
engine = load_trt_engine(path)
wrapper = torch2trt.TRTModule(
engine=engine,
input_names=input_names,
output_names=output_names
)
return wrapper
def format_bgr8_image(image, device="cuda"):
x = torch.from_numpy(image)
x = x.permute(2, 0, 1)[None, ...]
x = (x / 255 - 0.45) / 0.25
return x | 4,290 | Python | 22.194594 | 98 | 0.577156 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/isaac_tutorials/scripts/ros2_publisher.py | #!/usr/bin/env python3
# Copyright (c) 2020-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.
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import JointState
import numpy as np
import time
class TestROS2Bridge(Node):
def __init__(self):
super().__init__("test_ros2bridge")
# Create the publisher. This publisher will publish a JointState message to the /joint_command topic.
self.publisher_ = self.create_publisher(JointState, "joint_command", 10)
# Create a JointState message
self.joint_state = JointState()
self.joint_state.name = [
"panda_joint1",
"panda_joint2",
"panda_joint3",
"panda_joint4",
"panda_joint5",
"panda_joint6",
"panda_joint7",
"panda_finger_joint1",
"panda_finger_joint2",
]
num_joints = len(self.joint_state.name)
# make sure kit's editor is playing for receiving messages
self.joint_state.position = np.array([0.0] * num_joints, dtype=np.float64).tolist()
self.default_joints = [0.0, -1.16, -0.0, -2.3, -0.0, 1.6, 1.1, 0.4, 0.4]
# limiting the movements to a smaller range (this is not the range of the robot, just the range of the movement
self.max_joints = np.array(self.default_joints) + 0.5
self.min_joints = np.array(self.default_joints) - 0.5
# position control the robot to wiggle around each joint
self.time_start = time.time()
timer_period = 0.05 # seconds
self.timer = self.create_timer(timer_period, self.timer_callback)
def timer_callback(self):
self.joint_state.header.stamp = self.get_clock().now().to_msg()
joint_position = (
np.sin(time.time() - self.time_start) * (self.max_joints - self.min_joints) * 0.5 + self.default_joints
)
self.joint_state.position = joint_position.tolist()
# Publish the message to the topic
self.publisher_.publish(self.joint_state)
def main(args=None):
rclpy.init(args=args)
ros2_publisher = TestROS2Bridge()
rclpy.spin(ros2_publisher)
# Destroy the node explicitly
ros2_publisher.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
| 2,662 | Python | 31.084337 | 119 | 0.644252 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/carter_navigation/launch/carter_navigation.launch.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.
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
use_sim_time = LaunchConfiguration("use_sim_time", default="True")
map_dir = LaunchConfiguration(
"map",
default=os.path.join(
get_package_share_directory("carter_navigation"), "maps", "carter_warehouse_navigation.yaml"
),
)
param_dir = LaunchConfiguration(
"params_file",
default=os.path.join(
get_package_share_directory("carter_navigation"), "params", "carter_navigation_params.yaml"
),
)
nav2_bringup_launch_dir = os.path.join(get_package_share_directory("nav2_bringup"), "launch")
rviz_config_dir = os.path.join(get_package_share_directory("carter_navigation"), "rviz2", "carter_navigation.rviz")
return LaunchDescription(
[
DeclareLaunchArgument("map", default_value=map_dir, description="Full path to map file to load"),
DeclareLaunchArgument(
"params_file", default_value=param_dir, description="Full path to param file to load"
),
DeclareLaunchArgument(
"use_sim_time", default_value="true", description="Use simulation (Omniverse Isaac Sim) clock if true"
),
IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(nav2_bringup_launch_dir, "rviz_launch.py")),
launch_arguments={"namespace": "", "use_namespace": "False", "rviz_config": rviz_config_dir}.items(),
),
IncludeLaunchDescription(
PythonLaunchDescriptionSource([nav2_bringup_launch_dir, "/bringup_launch.py"]),
launch_arguments={"map": map_dir, "use_sim_time": use_sim_time, "params_file": param_dir}.items(),
),
Node(
package='pointcloud_to_laserscan', executable='pointcloud_to_laserscan_node',
remappings=[('cloud_in', ['/front_3d_lidar/point_cloud']),
('scan', ['/scan'])],
parameters=[{
'target_frame': 'front_3d_lidar',
'transform_tolerance': 0.01,
'min_height': -0.4,
'max_height': 1.5,
'angle_min': -1.5708, # -M_PI/2
'angle_max': 1.5708, # M_PI/2
'angle_increment': 0.0087, # M_PI/360.0
'scan_time': 0.3333,
'range_min': 0.05,
'range_max': 100.0,
'use_inf': True,
'inf_epsilon': 1.0,
# 'concurrency_level': 1,
}],
name='pointcloud_to_laserscan'
)
]
)
| 3,521 | Python | 42.481481 | 119 | 0.601534 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/carter_navigation/launch/carter_navigation_individual.launch.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.
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, ExecuteProcess, IncludeLaunchDescription
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PythonExpression, TextSubstitution
from launch_ros.actions import Node
def generate_launch_description():
# Get the launch directory
nav2_launch_dir = os.path.join(get_package_share_directory("nav2_bringup"), "launch")
# Create the launch configuration variables
slam = LaunchConfiguration("slam")
namespace = LaunchConfiguration("namespace")
use_namespace = LaunchConfiguration("use_namespace")
map_yaml_file = LaunchConfiguration("map")
use_sim_time = LaunchConfiguration("use_sim_time")
params_file = LaunchConfiguration("params_file")
default_bt_xml_filename = LaunchConfiguration("default_bt_xml_filename")
autostart = LaunchConfiguration("autostart")
# Declare the launch arguments
declare_namespace_cmd = DeclareLaunchArgument("namespace", default_value="", description="Top-level namespace")
declare_use_namespace_cmd = DeclareLaunchArgument(
"use_namespace", default_value="false", description="Whether to apply a namespace to the navigation stack"
)
declare_slam_cmd = DeclareLaunchArgument("slam", default_value="False", description="Whether run a SLAM")
declare_map_yaml_cmd = DeclareLaunchArgument(
"map",
default_value=os.path.join(nav2_launch_dir, "maps", "carter_warehouse_navigation.yaml"),
description="Full path to map file to load",
)
declare_use_sim_time_cmd = DeclareLaunchArgument(
"use_sim_time", default_value="True", description="Use simulation (Isaac Sim) clock if true"
)
declare_params_file_cmd = DeclareLaunchArgument(
"params_file",
default_value=os.path.join(nav2_launch_dir, "params", "nav2_params.yaml"),
description="Full path to the ROS2 parameters file to use for all launched nodes",
)
declare_bt_xml_cmd = DeclareLaunchArgument(
"default_bt_xml_filename",
default_value=os.path.join(
get_package_share_directory("nav2_bt_navigator"), "behavior_trees", "navigate_w_replanning_and_recovery.xml"
),
description="Full path to the behavior tree xml file to use",
)
declare_autostart_cmd = DeclareLaunchArgument(
"autostart", default_value="true", description="Automatically startup the nav2 stack"
)
bringup_cmd = IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(nav2_launch_dir, "bringup_launch.py")),
launch_arguments={
"namespace": namespace,
"use_namespace": use_namespace,
"slam": slam,
"map": map_yaml_file,
"use_sim_time": use_sim_time,
"params_file": params_file,
"default_bt_xml_filename": default_bt_xml_filename,
"autostart": autostart,
}.items(),
)
# Create the launch description and populate
ld = LaunchDescription()
# Declare the launch options
ld.add_action(declare_namespace_cmd)
ld.add_action(declare_use_namespace_cmd)
ld.add_action(declare_slam_cmd)
ld.add_action(declare_map_yaml_cmd)
ld.add_action(declare_use_sim_time_cmd)
ld.add_action(declare_params_file_cmd)
ld.add_action(declare_bt_xml_cmd)
ld.add_action(declare_autostart_cmd)
ld.add_action(bringup_cmd)
return ld
| 4,076 | Python | 39.366336 | 120 | 0.711237 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/carter_navigation/launch/multiple_robot_carter_navigation_hospital.launch.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.
"""
Example for spawing multiple robots in Gazebo.
This is an example on how to create a launch file for spawning multiple robots into Gazebo
and launch multiple instances of the navigation stack, each controlling one robot.
The robots co-exist on a shared environment and are controlled by independent nav stacks
"""
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, ExecuteProcess, GroupAction, IncludeLaunchDescription, LogInfo
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, TextSubstitution
from launch_ros.actions import Node
def generate_launch_description():
# Get the launch and rviz directories
carter_nav2_bringup_dir = get_package_share_directory("carter_navigation")
nav2_bringup_dir = get_package_share_directory("nav2_bringup")
nav2_bringup_launch_dir = os.path.join(nav2_bringup_dir, "launch")
rviz_config_dir = os.path.join(carter_nav2_bringup_dir, "rviz2", "carter_navigation_namespaced.rviz")
# Names and poses of the robots
robots = [{"name": "carter1"}, {"name": "carter2"}, {"name": "carter3"}]
# Common settings
ENV_MAP_FILE = "carter_hospital_navigation.yaml"
use_sim_time = LaunchConfiguration("use_sim_time", default="True")
map_yaml_file = LaunchConfiguration("map")
default_bt_xml_filename = LaunchConfiguration("default_bt_xml_filename")
autostart = LaunchConfiguration("autostart")
rviz_config_file = LaunchConfiguration("rviz_config")
use_rviz = LaunchConfiguration("use_rviz")
log_settings = LaunchConfiguration("log_settings", default="true")
# Declare the launch arguments
declare_map_yaml_cmd = DeclareLaunchArgument(
"map",
default_value=os.path.join(carter_nav2_bringup_dir, "maps", ENV_MAP_FILE),
description="Full path to map file to load",
)
declare_robot1_params_file_cmd = DeclareLaunchArgument(
"carter1_params_file",
default_value=os.path.join(
carter_nav2_bringup_dir, "params", "hospital", "multi_robot_carter_navigation_params_1.yaml"
),
description="Full path to the ROS2 parameters file to use for robot1 launched nodes",
)
declare_robot2_params_file_cmd = DeclareLaunchArgument(
"carter2_params_file",
default_value=os.path.join(
carter_nav2_bringup_dir, "params", "hospital", "multi_robot_carter_navigation_params_2.yaml"
),
description="Full path to the ROS2 parameters file to use for robot2 launched nodes",
)
declare_robot3_params_file_cmd = DeclareLaunchArgument(
"carter3_params_file",
default_value=os.path.join(
carter_nav2_bringup_dir, "params", "hospital", "multi_robot_carter_navigation_params_3.yaml"
),
description="Full path to the ROS2 parameters file to use for robot3 launched nodes",
)
declare_bt_xml_cmd = DeclareLaunchArgument(
"default_bt_xml_filename",
default_value=os.path.join(
get_package_share_directory("nav2_bt_navigator"), "behavior_trees", "navigate_w_replanning_and_recovery.xml"
),
description="Full path to the behavior tree xml file to use",
)
declare_autostart_cmd = DeclareLaunchArgument(
"autostart", default_value="True", description="Automatically startup the stacks"
)
declare_rviz_config_file_cmd = DeclareLaunchArgument(
"rviz_config", default_value=rviz_config_dir, description="Full path to the RVIZ config file to use."
)
declare_use_rviz_cmd = DeclareLaunchArgument("use_rviz", default_value="True", description="Whether to start RVIZ")
# Define commands for launching the navigation instances
nav_instances_cmds = []
for robot in robots:
params_file = LaunchConfiguration(robot["name"] + "_params_file")
group = GroupAction(
[
IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(nav2_bringup_launch_dir, "rviz_launch.py")),
condition=IfCondition(use_rviz),
launch_arguments={
"namespace": TextSubstitution(text=robot["name"]),
"use_namespace": "True",
"rviz_config": rviz_config_file,
}.items(),
),
IncludeLaunchDescription(
PythonLaunchDescriptionSource(
os.path.join(carter_nav2_bringup_dir, "launch", "carter_navigation_individual.launch.py")
),
launch_arguments={
"namespace": robot["name"],
"use_namespace": "True",
"map": map_yaml_file,
"use_sim_time": use_sim_time,
"params_file": params_file,
"default_bt_xml_filename": default_bt_xml_filename,
"autostart": autostart,
"use_rviz": "False",
"use_simulator": "False",
"headless": "False",
}.items(),
),
Node(
package='pointcloud_to_laserscan', executable='pointcloud_to_laserscan_node',
remappings=[('cloud_in', ['front_3d_lidar/point_cloud']),
('scan', ['scan'])],
parameters=[{
'target_frame': 'front_3d_lidar',
'transform_tolerance': 0.01,
'min_height': -0.4,
'max_height': 1.5,
'angle_min': -1.5708, # -M_PI/2
'angle_max': 1.5708, # M_PI/2
'angle_increment': 0.0087, # M_PI/360.0
'scan_time': 0.3333,
'range_min': 0.05,
'range_max': 100.0,
'use_inf': True,
'inf_epsilon': 1.0,
# 'concurrency_level': 1,
}],
name='pointcloud_to_laserscan',
namespace = robot["name"]
),
LogInfo(condition=IfCondition(log_settings), msg=["Launching ", robot["name"]]),
LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " map yaml: ", map_yaml_file]),
LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " params yaml: ", params_file]),
LogInfo(
condition=IfCondition(log_settings),
msg=[robot["name"], " behavior tree xml: ", default_bt_xml_filename],
),
LogInfo(
condition=IfCondition(log_settings), msg=[robot["name"], " rviz config file: ", rviz_config_file]
),
LogInfo(condition=IfCondition(log_settings), msg=[robot["name"], " autostart: ", autostart]),
]
)
nav_instances_cmds.append(group)
# Create the launch description and populate
ld = LaunchDescription()
# Declare the launch options
ld.add_action(declare_map_yaml_cmd)
ld.add_action(declare_robot1_params_file_cmd)
ld.add_action(declare_robot2_params_file_cmd)
ld.add_action(declare_robot3_params_file_cmd)
ld.add_action(declare_bt_xml_cmd)
ld.add_action(declare_use_rviz_cmd)
ld.add_action(declare_autostart_cmd)
ld.add_action(declare_rviz_config_file_cmd)
for simulation_instance_cmd in nav_instances_cmds:
ld.add_action(simulation_instance_cmd)
return ld
| 8,338 | Python | 42.432291 | 120 | 0.601823 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/setup.py | from setuptools import setup
from glob import glob
import os
package_name = "isaac_ros_navigation_goal"
setup(
name=package_name,
version="0.0.1",
packages=[package_name, package_name + "/goal_generators"],
data_files=[
("share/ament_index/resource_index/packages", ["resource/" + package_name]),
("share/" + package_name, ["package.xml"]),
(os.path.join("share", package_name, "launch"), glob("launch/*.launch.py")),
("share/" + package_name + "/assets", glob("assets/*")),
],
install_requires=["setuptools"],
zip_safe=True,
maintainer="isaac sim",
maintainer_email="[email protected]",
description="Package to set goals for navigation stack.",
license="NVIDIA Isaac ROS Software License",
tests_require=["pytest"],
entry_points={"console_scripts": ["SetNavigationGoal = isaac_ros_navigation_goal.set_goal:main"]},
)
| 906 | Python | 33.884614 | 102 | 0.651214 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/test/test_flake8.py | # Copyright 2017 Open Source Robotics Foundation, Inc.
#
# 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 ament_flake8.main import main_with_errors
import pytest
@pytest.mark.flake8
@pytest.mark.linter
def test_flake8():
rc, errors = main_with_errors(argv=[])
assert rc == 0, "Found %d code style errors / warnings:\n" % len(errors) + "\n".join(errors)
| 864 | Python | 35.041665 | 96 | 0.741898 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/launch/isaac_ros_navigation_goal.launch.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.
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
def generate_launch_description():
map_yaml_file = LaunchConfiguration(
"map_yaml_path",
default=os.path.join(
get_package_share_directory("isaac_ros_navigation_goal"), "assets", "carter_warehouse_navigation.yaml"
),
)
goal_text_file = LaunchConfiguration(
"goal_text_file_path",
default=os.path.join(get_package_share_directory("isaac_ros_navigation_goal"), "assets", "goals.txt"),
)
navigation_goal_node = Node(
name="set_navigation_goal",
package="isaac_ros_navigation_goal",
executable="SetNavigationGoal",
parameters=[
{
"map_yaml_path": map_yaml_file,
"iteration_count": 3,
"goal_generator_type": "RandomGoalGenerator",
"action_server_name": "navigate_to_pose",
"obstacle_search_distance_in_meters": 0.2,
"goal_text_file_path": goal_text_file,
"initial_pose": [-6.4, -1.04, 0.0, 0.0, 0.0, 0.99, 0.02],
}
],
output="screen",
)
return LaunchDescription([navigation_goal_node])
| 1,782 | Python | 35.387754 | 114 | 0.654882 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/obstacle_map.py | import numpy as np
import yaml
import os
import math
from PIL import Image
class GridMap:
def __init__(self, yaml_file_path):
self.__get_meta_from_yaml(yaml_file_path)
self.__get_raw_map()
self.__add_max_range_to_meta()
# print(self.__map_meta)
def __get_meta_from_yaml(self, yaml_file_path):
"""
Reads map meta from the yaml file.
Parameters
----------
yaml_file_path: path of the yaml file.
"""
with open(yaml_file_path, "r") as f:
file_content = f.read()
self.__map_meta = yaml.safe_load(file_content)
self.__map_meta["image"] = os.path.join(os.path.dirname(yaml_file_path), self.__map_meta["image"])
def __get_raw_map(self):
"""
Reads the map image and generates the grid map.\n
Grid map is a 2D boolean matrix where True=>occupied space & False=>Free space.
"""
img = Image.open(self.__map_meta.get("image"))
img = np.array(img)
# Anything greater than free_thresh is considered as occupied
if self.__map_meta["negate"]:
res = np.where((img / 255)[:, :, 0] > self.__map_meta["free_thresh"])
else:
res = np.where(((255 - img) / 255)[:, :, 0] > self.__map_meta["free_thresh"])
self.__grid_map = np.zeros(shape=(img.shape[:2]), dtype=bool)
for i in range(res[0].shape[0]):
self.__grid_map[res[0][i], res[1][i]] = 1
def __add_max_range_to_meta(self):
"""
Calculates and adds the max value of pose in x & y direction to the meta.
"""
max_x = self.__grid_map.shape[1] * self.__map_meta["resolution"] + self.__map_meta["origin"][0]
max_y = self.__grid_map.shape[0] * self.__map_meta["resolution"] + self.__map_meta["origin"][1]
self.__map_meta["max_x"] = round(max_x, 2)
self.__map_meta["max_y"] = round(max_y, 2)
def __pad_obstacles(self, distance):
pass
def get_range(self):
"""
Returns the bounds of pose values in x & y direction.\n
Returns
-------
[List]:\n
Where list[0][0]: min value in x direction
list[0][1]: max value in x direction
list[1][0]: min value in y direction
list[1][1]: max value in y direction
"""
return [
[self.__map_meta["origin"][0], self.__map_meta["max_x"]],
[self.__map_meta["origin"][1], self.__map_meta["max_y"]],
]
def __transform_to_image_coordinates(self, point):
"""
Transforms a pose in meters to image pixel coordinates.
Parameters
----------
Point: A point as list. where list[0]=>pose.x and list[1]=pose.y
Returns
-------
[Tuple]: tuple[0]=>pixel value in x direction. i.e column index.
tuple[1]=> pixel vlaue in y direction. i.e row index.
"""
p_x, p_y = point
i_x = math.floor((p_x - self.__map_meta["origin"][0]) / self.__map_meta["resolution"])
i_y = math.floor((p_y - self.__map_meta["origin"][1]) / self.__map_meta["resolution"])
# because origin in yaml is at bottom left of image
i_y = self.__grid_map.shape[0] - i_y
return i_x, i_y
def __transform_distance_to_pixels(self, distance):
"""
Converts the distance in meters to number of pixels based on the resolution.
Parameters
----------
distance: value in meters
Returns
-------
[Integer]: number of pixel which represent the same distance.
"""
return math.ceil(distance / self.__map_meta["resolution"])
def __is_obstacle_in_distance(self, img_point, distance):
"""
Checks if any obstacle is in vicinity of the given image point.
Parameters
----------
img_point: pixel values of the point
distance: distnace in pixels in which there shouldn't be any obstacle.
Returns
-------
[Bool]: True if any obstacle found else False.
"""
# need to make sure that patch xmin & ymin are >=0,
# because of python's negative indexing capability
row_start_idx = 0 if img_point[1] - distance < 0 else img_point[1] - distance
col_start_idx = 0 if img_point[0] - distance < 0 else img_point[0] - distance
# image point acts as the center of the square, where each side of square is of size
# 2xdistance
patch = self.__grid_map[row_start_idx : img_point[1] + distance, col_start_idx : img_point[0] + distance]
obstacles = np.where(patch == True)
return len(obstacles[0]) > 0
def is_valid_pose(self, point, distance=0.2):
"""
Checks if a given pose is "distance" away from a obstacle.
Parameters
----------
point: pose in 2D space. where point[0]=pose.x and point[1]=pose.y
distance: distance in meters.
Returns
-------
[Bool]: True if pose is valid else False
"""
assert len(point) == 2
img_point = self.__transform_to_image_coordinates(point)
img_pixel_distance = self.__transform_distance_to_pixels(distance)
# Pose is not valid if there is obstacle in the vicinity
return not self.__is_obstacle_in_distance(img_point, img_pixel_distance)
| 5,443 | Python | 33.455696 | 113 | 0.553188 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/set_goal.py | import rclpy
from rclpy.action import ActionClient
from rclpy.node import Node
from nav2_msgs.action import NavigateToPose
from .obstacle_map import GridMap
from .goal_generators import RandomGoalGenerator, GoalReader
import sys
from geometry_msgs.msg import PoseWithCovarianceStamped
import time
class SetNavigationGoal(Node):
def __init__(self):
super().__init__("set_navigation_goal")
self.declare_parameters(
namespace="",
parameters=[
("iteration_count", 1),
("goal_generator_type", "RandomGoalGenerator"),
("action_server_name", "navigate_to_pose"),
("obstacle_search_distance_in_meters", 0.2),
("frame_id", "map"),
("map_yaml_path", None),
("goal_text_file_path", None),
("initial_pose", None),
],
)
self.__goal_generator = self.__create_goal_generator()
action_server_name = self.get_parameter("action_server_name").value
self._action_client = ActionClient(self, NavigateToPose, action_server_name)
self.MAX_ITERATION_COUNT = self.get_parameter("iteration_count").value
assert self.MAX_ITERATION_COUNT > 0
self.curr_iteration_count = 1
self.__initial_goal_publisher = self.create_publisher(PoseWithCovarianceStamped, "/initialpose", 1)
self.__initial_pose = self.get_parameter("initial_pose").value
self.__is_initial_pose_sent = True if self.__initial_pose is None else False
def __send_initial_pose(self):
"""
Publishes the initial pose.
This function is only called once that too before sending any goal pose
to the mission server.
"""
goal = PoseWithCovarianceStamped()
goal.header.frame_id = self.get_parameter("frame_id").value
goal.header.stamp = self.get_clock().now().to_msg()
goal.pose.pose.position.x = self.__initial_pose[0]
goal.pose.pose.position.y = self.__initial_pose[1]
goal.pose.pose.position.z = self.__initial_pose[2]
goal.pose.pose.orientation.x = self.__initial_pose[3]
goal.pose.pose.orientation.y = self.__initial_pose[4]
goal.pose.pose.orientation.z = self.__initial_pose[5]
goal.pose.pose.orientation.w = self.__initial_pose[6]
self.__initial_goal_publisher.publish(goal)
def send_goal(self):
"""
Sends the goal to the action server.
"""
if not self.__is_initial_pose_sent:
self.get_logger().info("Sending initial pose")
self.__send_initial_pose()
self.__is_initial_pose_sent = True
# Assumption is that initial pose is set after publishing first time in this duration.
# Can be changed to more sophisticated way. e.g. /particlecloud topic has no msg until
# the initial pose is set.
time.sleep(10)
self.get_logger().info("Sending first goal")
self._action_client.wait_for_server()
goal_msg = self.__get_goal()
if goal_msg is None:
rclpy.shutdown()
sys.exit(1)
self._send_goal_future = self._action_client.send_goal_async(
goal_msg, feedback_callback=self.__feedback_callback
)
self._send_goal_future.add_done_callback(self.__goal_response_callback)
def __goal_response_callback(self, future):
"""
Callback function to check the response(goal accpted/rejected) from the server.\n
If the Goal is rejected it stops the execution for now.(We can change to resample the pose if rejected.)
"""
goal_handle = future.result()
if not goal_handle.accepted:
self.get_logger().info("Goal rejected :(")
rclpy.shutdown()
return
self.get_logger().info("Goal accepted :)")
self._get_result_future = goal_handle.get_result_async()
self._get_result_future.add_done_callback(self.__get_result_callback)
def __get_goal(self):
"""
Get the next goal from the goal generator.
Returns
-------
[NavigateToPose][goal] or None if the next goal couldn't be generated.
"""
goal_msg = NavigateToPose.Goal()
goal_msg.pose.header.frame_id = self.get_parameter("frame_id").value
goal_msg.pose.header.stamp = self.get_clock().now().to_msg()
pose = self.__goal_generator.generate_goal()
# couldn't sample a pose which is not close to obstacles. Rare but might happen in dense maps.
if pose is None:
self.get_logger().error(
"Could not generate next goal. Returning. Possible reasons for this error could be:"
)
self.get_logger().error(
"1. If you are using GoalReader then please make sure iteration count <= number of goals avaiable in file."
)
self.get_logger().error(
"2. If RandomGoalGenerator is being used then it was not able to sample a pose which is given distance away from the obstacles."
)
return
self.get_logger().info("Generated goal pose: {0}".format(pose))
goal_msg.pose.pose.position.x = pose[0]
goal_msg.pose.pose.position.y = pose[1]
goal_msg.pose.pose.orientation.x = pose[2]
goal_msg.pose.pose.orientation.y = pose[3]
goal_msg.pose.pose.orientation.z = pose[4]
goal_msg.pose.pose.orientation.w = pose[5]
return goal_msg
def __get_result_callback(self, future):
"""
Callback to check result.\n
It calls the send_goal() function in case current goal sent count < required goals count.
"""
# Nav2 is sending empty message for success as well as for failure.
result = future.result().result
self.get_logger().info("Result: {0}".format(result.result))
if self.curr_iteration_count < self.MAX_ITERATION_COUNT:
self.curr_iteration_count += 1
self.send_goal()
else:
rclpy.shutdown()
def __feedback_callback(self, feedback_msg):
"""
This is feeback callback. We can compare/compute/log while the robot is on its way to goal.
"""
# self.get_logger().info('FEEDBACK: {}\n'.format(feedback_msg))
pass
def __create_goal_generator(self):
"""
Creates the GoalGenerator object based on the specified ros param value.
"""
goal_generator_type = self.get_parameter("goal_generator_type").value
goal_generator = None
if goal_generator_type == "RandomGoalGenerator":
if self.get_parameter("map_yaml_path").value is None:
self.get_logger().info("Yaml file path is not given. Returning..")
sys.exit(1)
yaml_file_path = self.get_parameter("map_yaml_path").value
grid_map = GridMap(yaml_file_path)
obstacle_search_distance_in_meters = self.get_parameter("obstacle_search_distance_in_meters").value
assert obstacle_search_distance_in_meters > 0
goal_generator = RandomGoalGenerator(grid_map, obstacle_search_distance_in_meters)
elif goal_generator_type == "GoalReader":
if self.get_parameter("goal_text_file_path").value is None:
self.get_logger().info("Goal text file path is not given. Returning..")
sys.exit(1)
file_path = self.get_parameter("goal_text_file_path").value
goal_generator = GoalReader(file_path)
else:
self.get_logger().info("Invalid goal generator specified. Returning...")
sys.exit(1)
return goal_generator
def main():
rclpy.init()
set_goal = SetNavigationGoal()
result = set_goal.send_goal()
rclpy.spin(set_goal)
if __name__ == "__main__":
main()
| 7,971 | Python | 37.887805 | 144 | 0.605696 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/goal_reader.py | from .goal_generator import GoalGenerator
class GoalReader(GoalGenerator):
def __init__(self, file_path):
self.__file_path = file_path
self.__generator = self.__get_goal()
def generate_goal(self, max_num_of_trials=1000):
try:
return next(self.__generator)
except StopIteration:
return
def __get_goal(self):
for row in open(self.__file_path, "r"):
yield list(map(float, row.strip().split(" ")))
| 486 | Python | 26.055554 | 58 | 0.584362 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/random_goal_generator.py | import numpy as np
from .goal_generator import GoalGenerator
class RandomGoalGenerator(GoalGenerator):
"""
Random goal generator.
parameters
----------
grid_map: GridMap Object
distance: distance in meters to check vicinity for obstacles.
"""
def __init__(self, grid_map, distance):
self.__grid_map = grid_map
self.__distance = distance
def generate_goal(self, max_num_of_trials=1000):
"""
Generate the goal.
Parameters
----------
max_num_of_trials: maximum number of pose generations when generated pose keep is not a valid pose.
Returns
-------
[List][Pose]: Pose in format [pose.x,pose.y,orientaion.x,orientaion.y,orientaion.z,orientaion.w]
"""
range_ = self.__grid_map.get_range()
trial_count = 0
while trial_count < max_num_of_trials:
x = np.random.uniform(range_[0][0], range_[0][1])
y = np.random.uniform(range_[1][0], range_[1][1])
orient_x = np.random.uniform(0, 1)
orient_y = np.random.uniform(0, 1)
orient_z = np.random.uniform(0, 1)
orient_w = np.random.uniform(0, 1)
if self.__grid_map.is_valid_pose([x, y], self.__distance):
goal = [x, y, orient_x, orient_y, orient_z, orient_w]
return goal
trial_count += 1
| 1,405 | Python | 30.954545 | 107 | 0.560854 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/__init__.py | from .random_goal_generator import RandomGoalGenerator
from .goal_reader import GoalReader
| 91 | Python | 29.666657 | 54 | 0.857143 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/foxy_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/goal_generator.py | from abc import ABC, abstractmethod
class GoalGenerator(ABC):
"""
Parent class for the Goal generators
"""
def __init__(self):
pass
@abstractmethod
def generate_goal(self, max_num_of_trials=2000):
"""
Generate the goal.
Parameters
----------
max_num_of_trials: maximum number of pose generations when generated pose keep is not a valid pose.
Returns
-------
[List][Pose]: Pose in format [pose.x,pose.y,orientaion.x,orientaion.y,orientaion.z,orientaion.w]
"""
pass
| 582 | Python | 21.423076 | 107 | 0.580756 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/isaac_tutorials/scripts/ros_publisher.py | #!/usr/bin/env python
# Copyright (c) 2021-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.
import rospy
from sensor_msgs.msg import JointState
import numpy as np
import time
rospy.init_node("test_rosbridge", anonymous=True)
pub = rospy.Publisher("/joint_command", JointState, queue_size=10)
joint_state = JointState()
joint_state.name = [
"panda_joint1",
"panda_joint2",
"panda_joint3",
"panda_joint4",
"panda_joint5",
"panda_joint6",
"panda_joint7",
"panda_finger_joint1",
"panda_finger_joint2",
]
num_joints = len(joint_state.name)
# make sure kit's editor is playing for receiving messages ##
joint_state.position = np.array([0.0] * num_joints)
default_joints = [0.0, -1.16, -0.0, -2.3, -0.0, 1.6, 1.1, 0.4, 0.4]
# limiting the movements to a smaller range (this is not the range of the robot, just the range of the movement
max_joints = np.array(default_joints) + 0.5
min_joints = np.array(default_joints) - 0.5
# position control the robot to wiggle around each joint
time_start = time.time()
rate = rospy.Rate(20)
while not rospy.is_shutdown():
joint_state.position = np.sin(time.time() - time_start) * (max_joints - min_joints) * 0.5 + default_joints
pub.publish(joint_state)
rate.sleep()
| 1,618 | Python | 29.547169 | 111 | 0.717553 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/isaac_tutorials/scripts/ros_service_client.py | #!/usr/bin/env python
# Copyright (c) 2021-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.
import rospy
import numpy as np
from isaac_ros_messages.srv import IsaacPose
from isaac_ros_messages.srv import IsaacPoseRequest
from geometry_msgs.msg import Pose
def teleport_client(msg):
rospy.wait_for_service("teleport")
try:
teleport = rospy.ServiceProxy("teleport", IsaacPose)
teleport(msg)
return
except rospy.ServiceException as e:
print("Service call failed: %s" % e)
# compose teleport messages
cube_pose = Pose()
cube_pose.position.x = np.random.uniform(-2, 2)
cube_pose.position.y = 0
cube_pose.position.z = 0
cube_pose.orientation.w = 1
cube_pose.orientation.x = 0
cube_pose.orientation.y = 0
cube_pose.orientation.z = 0
cone_pose = Pose()
cone_pose.position.x = 0
cone_pose.position.y = np.random.uniform(-2, 2)
cone_pose.position.z = 0
cone_pose.orientation.w = 1
cone_pose.orientation.x = 0
cone_pose.orientation.y = 0
cone_pose.orientation.z = 0
teleport_msg = IsaacPoseRequest()
teleport_msg.names = ["/World/Cube", "/World/Cone"]
teleport_msg.poses = [cube_pose, cone_pose]
teleport_client(teleport_msg)
| 1,530 | Python | 27.886792 | 76 | 0.744444 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/isaac_moveit/scripts/panda_combined_joints_publisher.py | #!/usr/bin/env python
# Copyright (c) 2021-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.
import rospy
from sensor_msgs.msg import JointState
joints_dict = {}
def joint_states_callback(message):
joint_commands = JointState()
joint_commands.header = message.header
for i, name in enumerate(message.name):
# Storing arm joint names and positions
joints_dict[name] = message.position[i]
if name == "panda_finger_joint1":
# Adding additional panda_finger_joint2 state info (extra joint used in isaac sim)
# panda_finger_joint2 mirrors panda_finger_joint1
joints_dict["panda_finger_joint2"] = message.position[i]
joint_commands.name = joints_dict.keys()
joint_commands.position = joints_dict.values()
# Publishing combined message containing all arm and finger joints
pub.publish(joint_commands)
return
if __name__ == "__main__":
rospy.init_node("panda_combined_joints_publisher")
pub = rospy.Publisher("/joint_command", JointState, queue_size=1)
rospy.Subscriber("/joint_command_desired", JointState, joint_states_callback, queue_size=1)
rospy.spin()
| 1,535 | Python | 30.346938 | 95 | 0.718567 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/cortex_control_franka/src/python/franka_gripper_commander.py | # Copyright (c) 2019-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.
# Simple action client interface to the gripper action server.
from __future__ import absolute_import, division, print_function, unicode_literals
from franka_gripper.msg import GraspAction, GraspGoal, GraspEpsilon, MoveAction, MoveGoal
import numpy as np
import rospy
import actionlib
import argparse
# A gripper opening width of 0.8 appears full open, but Franka claims it will cause issues.
# The nominal maximum opening width is 0.7. Here we compromise between the two.
open_pos = 0.75
class FrankaGripperCommander(object):
def __init__(self, verbose=False):
self.verbose = verbose
self.grasp_client = actionlib.SimpleActionClient("/franka_gripper/grasp", GraspAction)
self.move_client = actionlib.SimpleActionClient("/franka_gripper/move", MoveAction)
if self.verbose:
print("Waiting for grasp client...")
self.grasp_client.wait_for_server()
if self.verbose:
print("Waiting for move client...")
self.move_client.wait_for_server()
def close(self, width=0.0, speed=0.03, force=40.0, grasp_eps=(0.2, 0.2), wait=True):
grasp_goal = GraspGoal()
grasp_goal.width = width
grasp_goal.speed = speed
grasp_goal.force = force
grasp_goal.epsilon = GraspEpsilon(inner=grasp_eps[0], outer=grasp_eps[1])
self.grasp_client.send_goal(grasp_goal)
if wait:
self.grasp_client.wait_for_result()
if self.verbose:
print("result:", self.grasp_client.get_result())
def move(self, width, speed=0.03, wait=True):
move_goal = MoveGoal()
move_goal.width = width
move_goal.speed = speed
print("sending goal")
self.move_client.send_goal(move_goal)
if wait:
print("waiting for finish")
self.move_client.wait_for_result()
if self.verbose:
print("result:", self.move_client.get_result())
print("move complete")
def open(self, speed=0.03, wait=True):
self.move(open_pos, speed=speed, wait=wait)
if __name__ == "__main__":
def Grasp(args):
print("Grasping...")
client = actionlib.SimpleActionClient("/franka_gripper/grasp", GraspAction)
# Waits until the action server has started up and started
# listening for goals.
client.wait_for_server()
# Creates a goal to send to the action server.
grasp_goal = GraspGoal()
grasp_goal.width = args.grasp_width
grasp_goal.speed = args.speed
grasp_goal.force = args.force
grasp_goal.epsilon = GraspEpsilon(inner=args.eps_inner, outer=args.eps_outer)
# Sends the goal to the action server.
print(">>>>", grasp_goal)
client.send_goal(grasp_goal)
# Waits for the server to finish performing the action.
client.wait_for_result()
# Prints out the result of executing the action
print("result:", client.get_result())
def Move(args):
print("Moving...")
client = actionlib.SimpleActionClient("/franka_gripper/move", MoveAction)
# Waits until the action server has started up and started
# listening for goals.
client.wait_for_server()
# Creates a goal to send to the action server.
move_goal = GraspGoal()
move_goal.width = args.width
move_goal.speed = args.speed
# Sends the goal to the action server.
client.send_goal(move_goal)
# Waits for the server to finish performing the action.
client.wait_for_result()
# Prints out the result of executing the action
print("result:", client.get_result())
def FrankaGripperCommanderTest(args):
print("Creating gripper commander...")
gripper_commander = FrankaGripperCommander()
print("Closing...")
gripper_commander.close()
print("Opening to all the way...")
gripper_commander.move(0.08)
print("Opening to .2...")
gripper_commander.move(0.02)
print("Opening to .5...")
gripper_commander.move(0.05)
print("Closing...")
gripper_commander.close()
print("Opening to all the way...")
gripper_commander.move(0.08)
def RobustnessTest(args):
commander = FrankaGripperCommander()
mode = "open"
while not rospy.is_shutdown():
if mode == "open":
commander.open(speed=0.2, wait=False)
print("opening...")
mode = "close"
elif mode == "close":
commander.close(speed=0.2, wait=False)
print("closing...")
mode = "open"
else:
raise RuntimeError("Invalid mode:", mode)
wait_time = abs(np.random.normal(loc=0.5, scale=0.75))
print(" wait:", wait_time)
rospy.sleep(wait_time)
parser = argparse.ArgumentParser("gripper_test")
parser.add_argument(
"--mode", type=str, required=True, help="Which mode: close, move, gripper_commander_test, robustness_test."
)
parser.add_argument(
"--width",
type=float,
default=None,
help="How wide in meters. Note that the gripper can open to about .8m wide.",
)
parser.add_argument("--speed", type=float, default=0.03, help="How fast to go in meter per second.")
parser.add_argument("--force", type=float, default=0.03, help="How strongly to grip.")
parser.add_argument(
"--grasp_width",
type=float,
default=0.0,
help="Width of the grasp. Defaults to closing all the way. "
"In conjunction with the default error (set wide) the default "
"behavior is to just close until it feels something.",
)
parser.add_argument(
"--eps_inner", type=float, default=0.2, help="Inner epsilon threshold. Defaults to enabling any error."
)
parser.add_argument(
"--eps_outer", type=float, default=0.2, help="Outer epsilon threshold. Defaults to enabling any error."
)
args = parser.parse_args()
rospy.init_node("gripper_test")
if args.mode == "move":
Move(args)
elif args.mode == "close":
Grasp(args)
elif args.mode == "gripper_commander_test":
FrankaGripperCommanderTest(args)
elif args.mode == "robustness_test":
RobustnessTest(args)
else:
print("ERROR -- unrecognized mode:", args.mode)
| 6,912 | Python | 33.914141 | 115 | 0.624421 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/cortex_control_franka/src/python/franka_gripper_command_relay.py | #!/usr/bin/python
# Copyright (c) 2019-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.
# Simple action client interface to the gripper action server.
from __future__ import print_function
import argparse
import json
import threading
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import String
from franka_gripper_commander import FrankaGripperCommander
pinch_width = 0.0265
speed = 0.2
class SimGripperCommander(object):
def __init__(self):
pass
def move(self, width, speed, wait=True):
print("[move] width: %.4f, speed %.2f" % (width, speed))
def close(self, width=0.0, speed=0.03, force=40.0, grasp_eps=(0.2, 0.2), wait=True):
print("[close] width: %.4f, speed: %.2f, force: %.2f" % (width, speed, force))
class FrankaGripperCommandRelay(object):
def __init__(self, is_sim=False):
print("Setting up gripper commander")
self.is_sim = is_sim
if self.is_sim:
print("<is sim>")
self.gripper_commander = SimGripperCommander()
else:
print("<is real>")
self.gripper_commander = FrankaGripperCommander(verbose=True)
self.start_time = rospy.Time.now()
self.last_tick_time = self.start_time
self.seconds_between_tick_prints = 0.1
self.command_queue = []
self.command_queue_lock = threading.Lock()
print("Starting subscriber...")
self.command_sub = rospy.Subscriber("/cortex/gripper/command", String, self.command_callback)
print("<ready and listening>")
def command_callback(self, msg):
try:
command = json.loads(msg.data)
try:
self.command_queue_lock.acquire()
self.command_queue.append(command)
finally:
self.command_queue_lock.release()
except ValueError as ve:
print("Jsg parse error -- could not parse command:\n", msg.data)
except Exception as e:
print("Exception in processing command:", e)
print("message data:\n", msg.data)
def process_latest_commands(self):
now = rospy.Time.now()
if (now - self.last_tick_time).to_sec() >= self.seconds_between_tick_prints:
self.last_tick_time = now
try:
self.command_queue_lock.acquire()
command_queue = self.command_queue
self.command_queue = []
finally:
self.command_queue_lock.release()
for command in command_queue:
self.process_latest_command(command)
def process_latest_command(self, cmd):
try:
print("\nprocessing command:", cmd["command"])
if cmd["command"] == "move_to":
print("moving to:", cmd["width"])
self.gripper_commander.move(cmd["width"], speed=speed, wait=True)
elif cmd["command"] == "close_to_grasp":
print("closing to grasp")
self.gripper_commander.close(speed=speed)
else:
print("WARNING -- unrecognized gripper command:", cmd["command"])
except Exception as e:
print("ERROR processing command:\n", cmd)
print("exception:", e)
def run(self):
rate = rospy.Rate(60.0)
while not rospy.is_shutdown():
self.process_latest_commands()
rate.sleep()
if __name__ == "__main__":
node_name = "franka_gripper_commander_relay"
rospy.init_node(node_name)
parser = argparse.ArgumentParser(node_name)
parser.add_argument("--is_sim", action="store_true", help="Set to start in simulated env.")
parser.add_argument("--open", action="store_true", help="Open the gripper then exit.")
parser.add_argument("--close", action="store_true", help="Close the gripper then exit.")
parser.add_argument("--close_pinch", action="store_true", help="Close the gripper then exit.")
args = parser.parse_args()
if args.open:
gripper_commander = FrankaGripperCommander(verbose=True)
gripper_commander.open(speed=speed)
elif args.close:
gripper_commander = FrankaGripperCommander(verbose=True)
gripper_commander.close(speed=speed)
elif args.close_pinch:
gripper_commander = FrankaGripperCommander(verbose=True)
gripper_commander.move(pinch_width, speed=speed, wait=True)
else:
listener = FrankaGripperCommandRelay(args.is_sim)
listener.run()
| 4,852 | Python | 34.166666 | 101 | 0.628607 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/cortex_control_franka/src/python/set_high_collision_thresholds.py | #!/usr/bin/env python
# Copyright (c) 2021-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.
# Simple action client interface to the gripper action server.
import rospy
from franka_control.srv import SetJointImpedance
from franka_control.srv import SetJointImpedanceRequest
from franka_control.srv import SetForceTorqueCollisionBehavior
from franka_control.srv import SetForceTorqueCollisionBehaviorRequest
rospy.init_node("set_control_parameters")
force_torque_srv = "/franka_control/set_force_torque_collision_behavior"
lower_torque_thresholds_nominal = [1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0]
upper_torque_thresholds_nominal = [1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0]
lower_force_thresholds_nominal = [1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0]
upper_force_thresholds_nominal = [1000.0, 1000.0, 1000.0, 1000.0, 1000.0, 1000.0]
ft_req = SetForceTorqueCollisionBehaviorRequest()
ft_req.lower_torque_thresholds_nominal = lower_torque_thresholds_nominal
ft_req.upper_torque_thresholds_nominal = upper_torque_thresholds_nominal
ft_req.lower_force_thresholds_nominal = lower_force_thresholds_nominal
ft_req.upper_force_thresholds_nominal = upper_force_thresholds_nominal
print(ft_req)
rospy.loginfo("Waiting for services...")
rospy.wait_for_service(force_torque_srv)
rospy.loginfo("Services ready.")
ft_srv = rospy.ServiceProxy(force_torque_srv, SetForceTorqueCollisionBehavior)
resp = ft_srv(ft_req)
failed = False
if not resp.success:
rospy.logerr("Could not set force torque collision behavior!")
failed = True
else:
rospy.loginfo("Set force torque collision behavior!")
if failed:
raise RuntimeError("Failed to set control parameters")
| 2,062 | Python | 39.45098 | 90 | 0.78613 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/isaac_ros_navigation_goal/setup.py | from setuptools import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=["goal_generators", "obstacle_map"], package_dir={"": "isaac_ros_navigation_goal"}
)
setup(**d)
| 230 | Python | 27.874997 | 95 | 0.743478 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/set_goal.py | #!/usr/bin/env python
from __future__ import absolute_import
import rospy
import actionlib
import sys
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from obstacle_map import GridMap
from goal_generators import RandomGoalGenerator, GoalReader
from geometry_msgs.msg import PoseWithCovarianceStamped
class SetNavigationGoal:
def __init__(self):
self.__goal_generator = self.__create_goal_generator()
action_server_name = rospy.get_param("action_server_name", "move_base")
self._action_client = actionlib.SimpleActionClient(action_server_name, MoveBaseAction)
self.MAX_ITERATION_COUNT = rospy.get_param("iteration_count", 1)
assert self.MAX_ITERATION_COUNT > 0
self.curr_iteration_count = 1
self.__initial_goal_publisher = rospy.Publisher("initialpose", PoseWithCovarianceStamped, queue_size=1)
self.__initial_pose = rospy.get_param("initial_pose", None)
self.__is_initial_pose_sent = True if self.__initial_pose is None else False
def __send_initial_pose(self):
"""
Publishes the initial pose.
This function is only called once that too before sending any goal pose
to the mission server.
"""
goal = PoseWithCovarianceStamped()
goal.header.frame_id = rospy.get_param("frame_id", "map")
goal.header.stamp = rospy.get_rostime()
goal.pose.pose.position.x = self.__initial_pose[0]
goal.pose.pose.position.y = self.__initial_pose[1]
goal.pose.pose.position.z = self.__initial_pose[2]
goal.pose.pose.orientation.x = self.__initial_pose[3]
goal.pose.pose.orientation.y = self.__initial_pose[4]
goal.pose.pose.orientation.z = self.__initial_pose[5]
goal.pose.pose.orientation.w = self.__initial_pose[6]
rospy.sleep(1)
self.__initial_goal_publisher.publish(goal)
def send_goal(self):
"""
Sends the goal to the action server.
"""
if not self.__is_initial_pose_sent:
rospy.loginfo("Sending initial pose")
self.__send_initial_pose()
self.__is_initial_pose_sent = True
# Assumption is that initial pose is set after publishing first time in this duration.
# Can be changed to more sophisticated way. e.g. /particlecloud topic has no msg until
# the initial pose is set.
rospy.sleep(10)
rospy.loginfo("Sending first goal")
self._action_client.wait_for_server()
goal_msg = self.__get_goal()
if goal_msg is None:
rospy.signal_shutdown("Goal message not generated.")
sys.exit(1)
self._action_client.send_goal(goal_msg, feedback_cb=self.__goal_response_callback)
def __goal_response_callback(self, feedback):
"""
Callback function to check the response(goal accpted/rejected) from the server.\n
If the Goal is rejected it stops the execution for now.(We can change to resample the pose if rejected.)
"""
if self.verify_goal_state():
rospy.loginfo("Waiting to reach goal")
wait = self._action_client.wait_for_result()
if self.verify_goal_state():
self.__get_result_callback(True)
def verify_goal_state(self):
print("Action Client State:", self._action_client.get_state(), self._action_client.get_goal_status_text())
if self._action_client.get_state() not in [0, 1, 3]:
rospy.signal_shutdown("Goal Rejected :(")
return False
return True
def __get_goal(self):
goal_msg = MoveBaseGoal()
goal_msg.target_pose.header.frame_id = rospy.get_param("frame_id", "map")
goal_msg.target_pose.header.stamp = rospy.get_rostime()
pose = self.__goal_generator.generate_goal()
# couldn't sample a pose which is not close to obstacles. Rare but might happen in dense maps.
if pose is None:
rospy.logerr("Could not generate next goal. Returning. Possible reasons for this error could be:")
rospy.logerr(
"1. If you are using GoalReader then please make sure iteration count <= no of goals avaiable in file."
)
rospy.logerr(
"2. If RandomGoalGenerator is being used then it was not able to sample a pose which is given distance away from the obstacles."
)
return
rospy.loginfo("Generated goal pose: {0}".format(pose))
goal_msg.target_pose.pose.position.x = pose[0]
goal_msg.target_pose.pose.position.y = pose[1]
goal_msg.target_pose.pose.orientation.x = pose[2]
goal_msg.target_pose.pose.orientation.y = pose[3]
goal_msg.target_pose.pose.orientation.z = pose[4]
goal_msg.target_pose.pose.orientation.w = pose[5]
return goal_msg
def __get_result_callback(self, wait):
if wait and self.curr_iteration_count < self.MAX_ITERATION_COUNT:
self.curr_iteration_count += 1
self.send_goal()
else:
rospy.signal_shutdown("Iteration done or Goal not reached.")
# in this callback func we can compare/compute/log something while the robot is on its way to goal.
def __feedback_callback(self, feedback_msg):
pass
def __create_goal_generator(self):
goal_generator_type = rospy.get_param("goal_generator_type", "RandomGoalGenerator")
goal_generator = None
if goal_generator_type == "RandomGoalGenerator":
if rospy.get_param("map_yaml_path", None) is None:
rospy.loginfo("Yaml file path is not given. Returning..")
sys.exit(1)
yaml_file_path = rospy.get_param("map_yaml_path", None)
grid_map = GridMap(yaml_file_path)
obstacle_search_distance_in_meters = rospy.get_param("obstacle_search_distance_in_meters", 0.2)
assert obstacle_search_distance_in_meters > 0
goal_generator = RandomGoalGenerator(grid_map, obstacle_search_distance_in_meters)
elif goal_generator_type == "GoalReader":
if rospy.get_param("goal_text_file_path", None) is None:
rospy.loginfo("Goal text file path is not given. Returning..")
sys.exit(1)
file_path = rospy.get_param("goal_text_file_path", None)
goal_generator = GoalReader(file_path)
else:
rospy.loginfo("Invalid goal generator specified. Returning...")
sys.exit(1)
return goal_generator
def main():
rospy.init_node("set_goal_py")
set_goal = SetNavigationGoal()
result = set_goal.send_goal()
rospy.spin()
if __name__ == "__main__":
main()
| 6,772 | Python | 40.552147 | 144 | 0.627732 |
NVIDIA-Omniverse/usd_scene_construction_utils/setup.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 setuptools import setup, find_packages
setup(
name="usd_scene_construction_utils",
version="0.0.1",
description="",
py_modules=["usd_scene_construction_utils"]
) | 864 | Python | 35.041665 | 98 | 0.752315 |
NVIDIA-Omniverse/usd_scene_construction_utils/usd_scene_construction_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 os
import numpy as np
import math
from typing import Optional, Sequence, Tuple
from typing_extensions import Literal
from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade
def new_in_memory_stage() -> Usd.Stage:
"""Creates a new in memory USD stage.
Returns:
Usd.Stage: The USD stage.
"""
stage = Usd.Stage.CreateInMemory()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
return stage
def new_omniverse_stage() -> Usd.Stage:
"""Creates a new Omniverse USD stage.
This method creates a new Omniverse USD stage. This will clear the active
omniverse stage, replacing it with a new one.
Returns:
Usd.Stage: The Omniverse USD stage.
"""
try:
import omni.usd
except ImportError:
raise ImportError("Omniverse not found. This method is unavailable.")
omni.usd.get_context().new_stage()
stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
return stage
def get_omniverse_stage() -> Usd.Stage:
"""Returns the current Omniverse USD stage.
Returns:
Usd.Stage: The currently active Omniverse USD stage.
"""
try:
import omni.usd
except ImportError:
raise ImportError("Omniverse not found. This method is unavailable.")
stage = omni.usd.get_context().get_stage()
return stage
def add_usd_ref(stage: Usd.Stage, path: str, usd_path: str) -> Usd.Prim:
"""Adds an external USD reference to a USD stage.
Args:
stage (:class:`Usd.Stage`): The USD stage to modify.
path (str): The path to add the USD reference.
usd_path (str): The filepath or URL of the USD reference (ie: a Nucleus
server URL).
Returns:
Usd.Prim: The created USD prim.
"""
stage.DefinePrim(path, "Xform")
prim_ref = stage.DefinePrim(os.path.join(path, "ref"))
prim_ref.GetReferences().AddReference(usd_path)
return get_prim(stage, path)
def _make_box_mesh(size: Tuple[float, float, float]):
# private utility function used by make_box
numFaces = 6
numVertexPerFace = 4
# Generate vertices on box
vertices = []
for i in [-1, 1]:
for j in [-1, 1]:
for k in [-1, 1]:
vertices.append((i * size[0], j * size[1], k * size[2]))
# Make faces for box (ccw convention)
faceVertexCounts = [numVertexPerFace] * numFaces
faceVertexIndices = [
2, 0, 1, 3,
4, 6, 7, 5,
0, 4, 5, 1,
6, 2, 3, 7,
0, 2, 6, 4,
5, 7, 3, 1,
]
# Make normals for face vertices
_faceVertexNormals = [
(-1, 0, 0),
(1, 0, 0),
(0, -1, 0),
(0, 1, 0),
(0, 0, -1),
(0, 0, 1),
]
faceVertexNormals = []
for n in _faceVertexNormals:
for i in range(numVertexPerFace):
faceVertexNormals.append(n)
# Assign uv-mapping for face vertices
_faceUvMaps = [
(0, 0), (1, 0), (1, 1), (0, 1)
]
faceUvMaps = []
for i in range(numFaces):
for uvm in _faceUvMaps:
faceUvMaps.append(uvm)
return (vertices, faceVertexCounts, faceVertexIndices, faceVertexNormals,
faceUvMaps)
def add_box(stage: Usd.Stage, path: str, size: Tuple[float, float, float]) -> Usd.Prim:
"""Adds a 3D box to a USD stage.
This adds a 3D box to the USD stage. The box is created with it's center
at (x, y, z) = (0, 0, 0).
Args:
stage (:class:`Usd.Stage`): The USD stage to modify.
path (str): The path to add the USD prim.
size (Tuple[float, float, float]): The size of the box (x, y, z sizes).
Returns:
Usd.Prim: The created USD prim.
"""
half_size = (size[0] / 2, size[1] / 2, size[2] / 2)
stage.DefinePrim(path, "Xform")
(vertices, faceVertexCounts, faceVertexIndices, faceVertexNormals,
faceUvMaps) = _make_box_mesh(half_size)
# create mesh at {path}/mesh, but return prim at {path}
prim: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, os.path.join(path, "mesh"))
prim.CreateExtentAttr().Set([
(-half_size[0], -half_size[1], -half_size[2]),
(half_size[0], half_size[1], half_size[2])
])
prim.CreateFaceVertexCountsAttr().Set(faceVertexCounts)
prim.CreateFaceVertexIndicesAttr().Set(faceVertexIndices)
var = UsdGeom.Primvar(prim.CreateNormalsAttr())
var.Set(faceVertexNormals)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
var = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("primvars:st", Sdf.ValueTypeNames.Float2Array)
var.Set(faceUvMaps)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
prim.CreatePointsAttr().Set(vertices)
prim.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
return get_prim(stage, path)
def add_xform(stage: Usd.Stage, path: str):
"""Adds a USD transform (Xform) to a USD stage.
This method adds a USD Xform to the USD stage at a given path. This is
helpful when you want to add hierarchy to a scene. After you create a
transform, any USD prims located under the transform path will be children
of the transform and can be moved as a group.
Args:
stage (:class:`Usd.Stage`): The USD stage to modify.
path (str): The path to add the USD prim.
Returns:
Usd.Prim: The created USD prim.
"""
stage.DefinePrim(path, "Xform")
return get_prim(stage, path)
def add_plane(
stage: Usd.Stage,
path: str,
size: Tuple[float, float],
uv: Tuple[float, float]=(1, 1)):
"""Adds a 2D plane to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
size (Tuple[float, float]): The size of the 2D plane (x, y).
uv (Tuple[float, float]): The UV mapping for textures applied to the
plane. For example, uv=(1, 1), means the texture will be spread
to fit the full size of the plane. uv=(10, 10) means the texture
will repeat 10 times along each dimension. uv=(5, 10) means the
texture will be scaled to repeat 5 times along the x dimension and
10 times along the y direction.
Returns:
Usd.Prim: The created USD prim.
"""
stage.DefinePrim(path, "Xform")
# create mesh at {path}/mesh, but return prim at {path}
prim: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, os.path.join(path, "mesh"))
prim.CreateExtentAttr().Set([
(-size[0], -size[1], 0),
(size[0], size[1], 0)
])
prim.CreateFaceVertexCountsAttr().Set([4])
prim.CreateFaceVertexIndicesAttr().Set([0, 1, 3, 2])
var = UsdGeom.Primvar(prim.CreateNormalsAttr())
var.Set([(0, 0, 1)] * 4)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
var = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("primvars:st",
Sdf.ValueTypeNames.Float2Array)
var.Set(
[(0, 0), (uv[0], 0), (uv[0], uv[1]), (0, uv[1])]
)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
prim.CreatePointsAttr().Set([
(-size[0], -size[1], 0),
(size[0], -size[1], 0),
(-size[0], size[1], 0),
(size[0], size[1], 0),
])
prim.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
return get_prim(stage, path)
def add_dome_light(stage: Usd.Stage, path: str, intensity: float = 1000,
angle: float = 180, exposure: float=0.) -> UsdLux.DomeLight:
"""Adds a dome light to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
intensity (float): The intensity of the dome light (default 1000).
angle (float): The angle of the dome light (default 180)
exposure (float): THe exposure of the dome light (default 0)
Returns:
UsdLux.DomeLight: The created Dome light.
"""
light = UsdLux.DomeLight.Define(stage, path)
# intensity
light.CreateIntensityAttr().Set(intensity)
light.CreateTextureFormatAttr().Set(UsdLux.Tokens.latlong)
light.CreateExposureAttr().Set(exposure)
# cone angle
shaping = UsdLux.ShapingAPI(light)
shaping.Apply(light.GetPrim())
shaping.CreateShapingConeAngleAttr().Set(angle)
shaping.CreateShapingConeSoftnessAttr()
shaping.CreateShapingFocusAttr()
shaping.CreateShapingFocusTintAttr()
shaping.CreateShapingIesFileAttr()
return light
def add_sphere_light(stage: Usd.Stage, path: str, intensity=30000,
radius=50, angle=180, exposure=0.):
"""Adds a sphere light to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
radius (float): The radius of the sphere light
intensity (float): The intensity of the sphere light (default 1000).
angle (float): The angle of the sphere light (default 180)
exposure (float): THe exposure of the sphere light (default 0)
Returns:
UsdLux.SphereLight: The created sphere light.
"""
light = UsdLux.SphereLight.Define(stage, path)
# intensity
light.CreateIntensityAttr().Set(intensity)
light.CreateRadiusAttr().Set(radius)
light.CreateExposureAttr().Set(exposure)
# cone angle
shaping = UsdLux.ShapingAPI(light)
shaping.Apply(light.GetPrim())
shaping.CreateShapingConeAngleAttr().Set(angle)
shaping.CreateShapingConeSoftnessAttr()
shaping.CreateShapingFocusAttr()
shaping.CreateShapingFocusTintAttr()
shaping.CreateShapingIesFileAttr()
return light
def add_mdl_material(stage: Usd.Stage, path: str, material_url: str,
material_name: Optional[str] = None) -> UsdShade.Material:
"""Adds an Omniverse MDL material to a USD stage.
*Omniverse only*
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
material_url (str): The URL of the material, such as on a Nucelus server.
material_name (Optional[str]): An optional name to give the material. If
one is not provided, it will default to the filename of the material
URL (excluding the extension).
returns:
UsdShade.Material: The created USD material.
"""
try:
import omni.usd
except ImportError:
raise ImportError("Omniverse not found. This method is unavailable.")
# Set default mtl_name
if material_name is None:
material_name = os.path.basename(material_url).split('.')[0]
# Create material using omniverse kit
if not stage.GetPrimAtPath(path):
success, result = omni.kit.commands.execute(
"CreateMdlMaterialPrimCommand",
mtl_url=material_url,
mtl_name=material_name,
mtl_path=path
)
# Get material from stage
material = UsdShade.Material(stage.GetPrimAtPath(path))
return material
def add_camera(
stage: Usd.Stage,
path: str,
focal_length: float = 35,
horizontal_aperature: float = 20.955,
vertical_aperature: float = 20.955,
clipping_range: Tuple[float, float] = (0.1, 100000)
) -> UsdGeom.Camera:
"""Adds a camera to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
focal_length (float): The focal length of the camera (default 35).
horizontal_aperature (float): The horizontal aperature of the camera
(default 20.955).
vertical_aperature (float): The vertical aperature of the camera
(default 20.955).
clipping_range (Tuple[float, float]): The clipping range of the camera.
returns:
UsdGeom.Camera: The created USD camera.
"""
camera = UsdGeom.Camera.Define(stage, path)
camera.CreateFocalLengthAttr().Set(focal_length)
camera.CreateHorizontalApertureAttr().Set(horizontal_aperature)
camera.CreateVerticalApertureAttr().Set(vertical_aperature)
camera.CreateClippingRangeAttr().Set(clipping_range)
return camera
def get_prim(stage: Usd.Stage, path: str) -> Usd.Prim:
"""Returns a prim at the specified path in a USD stage.
Args:
stage (Usd.Stage): The USD stage to query.
path (str): The path of the prim.
Returns:
Usd.Prim: The USD prim at the specified path.
"""
return stage.GetPrimAtPath(path)
def get_material(stage: Usd.Stage, path: str) -> UsdShade.Material:
"""Returns a material at the specified path in a USD stage.
Args:
stage (Usd.Stage): The USD stage to query.
path (str): The path of the material.
Returns:
UsdShade.Material: The USD material at the specified path.
"""
prim = get_prim(stage, path)
return UsdShade.Material(prim)
def export_stage(stage: Usd.Stage, filepath: str, default_prim=None):
"""Exports a USD stage to a given filepath.
Args:
stage (Usd.Stage): The USD stage to export.
path (str): The filepath to export the USD stage to.
default_prim (Optional[str]): The path of the USD prim in the
stage to set as the default prim. This is useful when you
want to use the exported USD as a reference, or when you want
to place the USD in Omniverse.
"""
if default_prim is not None:
stage.SetDefaultPrim(get_prim(stage, default_prim))
stage.Export(filepath)
def add_semantics(prim: Usd.Prim, type: str, name: str):
"""Adds semantics to a USD prim.
This function adds semantics to a USD prim. This is useful for assigning
classes to objects when generating synthetic data with Omniverse Replicator.
For example:
add_semantics(dog_prim, "class", "dog")
add_semantics(cat_prim, "class", "cat")
Args:
prim (Usd.Prim): The USD prim to modify.
type (str): The semantics type. This depends on how the data is ingested.
Typically, when using Omniverse replicator you will set this to "class".
name (str): The value of the semantic type. Typically, this would
correspond to the class label.
Returns:
Usd.Prim: The USD prim with added semantics.
"""
prim.AddAppliedSchema(f"SemanticsAPI:{type}_{name}")
prim.CreateAttribute(f"semantic:{type}_{name}:params:semanticType",
Sdf.ValueTypeNames.String).Set(type)
prim.CreateAttribute(f"semantic:{type}_{name}:params:semanticData",
Sdf.ValueTypeNames.String).Set(name)
return prim
def bind_material(prim: Usd.Prim, material: UsdShade.Material):
"""Binds a USD material to a USD prim.
Args:
prim (Usd.Prim): The USD prim to modify.
material (UsdShade.Material): The USD material to bind to the USD prim.
Returns:
Usd.Prim: The modified USD prim with the specified material bound to it.
"""
prim.ApplyAPI(UsdShade.MaterialBindingAPI)
UsdShade.MaterialBindingAPI(prim).Bind(material,
UsdShade.Tokens.strongerThanDescendants)
return prim
def collapse_xform(prim: Usd.Prim):
"""Collapses all xforms on a given USD prim.
This method collapses all Xforms on a given prim. For example,
a series of rotations, translations would be combined into a single matrix
operation.
Args:
prim (Usd.Prim): The Usd.Prim to collapse the transforms of.
Returns:
Usd.Prim: The Usd.Prim.
"""
x = UsdGeom.Xformable(prim)
local = x.GetLocalTransformation()
prim.RemoveProperty("xformOp:translate")
prim.RemoveProperty("xformOp:transform")
prim.RemoveProperty("xformOp:rotateX")
prim.RemoveProperty("xformOp:rotateY")
prim.RemoveProperty("xformOp:rotateZ")
var = x.MakeMatrixXform()
var.Set(local)
return prim
def get_xform_op_order(prim: Usd.Prim):
"""Returns the order of Xform ops on a given prim."""
x = UsdGeom.Xformable(prim)
op_order = x.GetXformOpOrderAttr().Get()
if op_order is not None:
op_order = list(op_order)
return op_order
else:
return []
def set_xform_op_order(prim: Usd.Prim, op_order: Sequence[str]):
"""Sets the order of Xform ops on a given prim"""
x = UsdGeom.Xformable(prim)
x.GetXformOpOrderAttr().Set(op_order)
return prim
def xform_op_move_end_to_front(prim: Usd.Prim):
"""Pops the last xform op on a given prim and adds it to the front."""
order = get_xform_op_order(prim)
end = order.pop(-1)
order.insert(0, end)
set_xform_op_order(prim, order)
return prim
def get_num_xform_ops(prim: Usd.Prim) -> int:
"""Returns the number of xform ops on a given prim."""
return len(get_xform_op_order(prim))
def apply_xform_matrix(prim: Usd.Prim, transform: np.ndarray):
"""Applies a homogeneous transformation matrix to the current prim's xform list.
Args:
prim (Usd.Prim): The USD prim to transform.
transform (np.ndarray): The 4x4 homogeneous transform matrix to apply.
Returns:
Usd.Prim: The modified USD prim with the provided transform applied after current transforms.
"""
x = UsdGeom.Xformable(prim)
x.AddTransformOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(
Gf.Matrix4d(transform)
)
xform_op_move_end_to_front(prim)
return prim
def scale(prim: Usd.Prim, scale: Tuple[float, float, float]):
"""Scales a prim along the (x, y, z) dimensions.
Args:
prim (Usd.Prim): The USD prim to scale.
scale (Tuple[float, float, float]): The scaling factors for the (x, y, z) dimensions.
Returns:
Usd.Prim: The scaled prim.
"""
x = UsdGeom.Xformable(prim)
x.AddScaleOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(scale)
xform_op_move_end_to_front(prim)
return prim
def translate(prim: Usd.Prim, offset: Tuple[float, float, float]):
"""Translates a prim along the (x, y, z) dimensions.
Args:
prim (Usd.Prim): The USD prim to translate.
offset (Tuple[float, float, float]): The offsets for the (x, y, z) dimensions.
Returns:
Usd.Prim: The translated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddTranslateOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(offset)
xform_op_move_end_to_front(prim)
return prim
def rotate_x(prim: Usd.Prim, angle: float):
"""Rotates a prim around the X axis.
Args:
prim (Usd.Prim): The USD prim to rotate.
angle (float): The rotation angle in degrees.
Returns:
Usd.Prim: The rotated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddRotateXOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(angle)
xform_op_move_end_to_front(prim)
return prim
def rotate_y(prim: Usd.Prim, angle: float):
"""Rotates a prim around the Y axis.
Args:
prim (Usd.Prim): The USD prim to rotate.
angle (float): The rotation angle in degrees.
Returns:
Usd.Prim: The rotated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddRotateYOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(angle)
xform_op_move_end_to_front(prim)
return prim
def rotate_z(prim: Usd.Prim, angle: float):
"""Rotates a prim around the Z axis.
Args:
prim (Usd.Prim): The USD prim to rotate.
angle (float): The rotation angle in degrees.
Returns:
Usd.Prim: The rotated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddRotateZOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(angle)
xform_op_move_end_to_front(prim)
return prim
def stack_prims(prims: Sequence[Usd.Prim], axis: int = 2, gap: float = 0, align_center=False):
"""Stacks prims on top of each other (or side-by-side).
This function stacks prims by placing them so their bounding boxes
are adjacent along a given axis.
Args:
prim (Usd.Prim): The USD prims to stack.
axis (int): The axis along which to stack the prims. x=0, y=1, z=2. Default 2.
gap (float): The spacing to add between stacked elements.
Returns:
Sequence[Usd.Prim]: The stacked prims.
"""
for i in range(1, len(prims)):
prev = prims[i - 1]
cur = prims[i]
bb_cur_min, bb_cur_max = compute_bbox(cur)
bb_prev_min, bb_prev_max = compute_bbox(prev)
if align_center:
offset = [
(bb_cur_max[0] + bb_cur_min[0]) / 2. - (bb_prev_max[0] + bb_prev_min[0]) / 2.,
(bb_cur_max[1] + bb_cur_min[1]) / 2. - (bb_prev_max[1] + bb_prev_min[1]) / 2.,
(bb_cur_max[2] + bb_cur_min[2]) / 2. - (bb_prev_max[2] + bb_prev_min[2]) / 2.
]
else:
offset = [0, 0, 0]
offset[axis] = bb_prev_max[axis] - bb_cur_min[axis]
if isinstance(gap, list):
offset[axis] = offset[axis] + gap[i]
else:
offset[axis] = offset[axis] + gap
translate(cur, tuple(offset))
return prims
def compute_bbox(prim: Usd.Prim) -> \
Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
"""Computes the axis-aligned bounding box for a USD prim.
Args:
prim (Usd.Prim): The USD prim to compute the bounding box of.
Returns:
Tuple[Tuple[float, float, float], Tuple[float, float, float]] The ((min_x, min_y, min_z), (max_x, max_y, max_z)) values of the bounding box.
"""
bbox_cache: UsdGeom.BBoxCache = UsdGeom.BBoxCache(
time=Usd.TimeCode.Default(),
includedPurposes=[UsdGeom.Tokens.default_],
useExtentsHint=True
)
total_bounds = Gf.BBox3d()
for p in Usd.PrimRange(prim):
total_bounds = Gf.BBox3d.Combine(
total_bounds, Gf.BBox3d(bbox_cache.ComputeWorldBound(p).ComputeAlignedRange())
)
box = total_bounds.ComputeAlignedBox()
return (box.GetMin(), box.GetMax())
def compute_bbox_size(prim: Usd.Prim) -> Tuple[float, float, float]:
"""Computes the (x, y, z) size of the axis-aligned bounding box for a prim."""
bbox_min, bbox_max = compute_bbox(prim)
size = (
bbox_max[0] - bbox_min[0],
bbox_max[1] - bbox_min[1],
bbox_max[2] - bbox_min[2]
)
return size
def compute_bbox_center(prim: Usd.Prim) -> Tuple[float, float, float]:
"""Computes the (x, y, z) center of the axis-aligned bounding box for a prim."""
bbox_min, bbox_max = compute_bbox(prim)
center = (
(bbox_max[0] + bbox_min[0]) / 2,
(bbox_max[1] + bbox_min[1]) / 2,
(bbox_max[2] + bbox_min[2]) / 2
)
return center
def set_visibility(prim: Usd.Prim,
visibility: Literal["inherited", "invisible"] = "inherited"):
"""Sets the visibility of a prim.
Args:
prim (Usd.Prim): The prim to control the visibility of.
visibility (str): The visibility of the prim. "inherited" if the
prim is visibile as long as it's parent is visible, or invisible if
it's parent is invisible. Otherwise, "invisible" if the prim is
invisible regardless of it's parent's visibility.
Returns:
Usd.Prim: The USD prim.
"""
attr = prim.GetAttribute("visibility")
if attr is None:
prim.CreateAttribute("visibility")
attr.Set(visibility)
return prim
def get_visibility(prim: Usd.Prim):
"""Returns the visibility of a given prim.
See set_visibility for details.
"""
return prim.GetAttribute("visibility").Get()
def rad2deg(x):
"""Convert radians to degrees."""
return 180. * x / math.pi
def deg2rad(x):
"""Convert degrees to radians."""
return math.pi * x / 180.
def compute_sphere_point(
elevation: float,
azimuth: float,
distance: float
) -> Tuple[float, float, float]:
"""Compute a sphere point given an elevation, azimuth and distance.
Args:
elevation (float): The elevation in degrees.
azimuth (float): The azimuth in degrees.
distance (float): The distance.
Returns:
Tuple[float, float, float]: The sphere coordinate.
"""
elevation = rad2deg(elevation)
azimuth = rad2deg(azimuth)
elevation = elevation
camera_xy_distance = math.cos(elevation) * distance
camera_x = math.cos(azimuth) * camera_xy_distance
camera_y = math.sin(azimuth) * camera_xy_distance
camera_z = math.sin(elevation) * distance
eye = (
float(camera_x),
float(camera_y),
float(camera_z)
)
return eye
def compute_look_at_matrix(
at: Tuple[float, float, float],
up: Tuple[float, float, float],
eye: Tuple[float, float, float]
) -> np.ndarray:
"""Computes a 4x4 homogeneous "look at" transformation matrix.
Args:
at (Tuple[float, float, float]): The (x, y, z) location that the transform
should be facing. For example (0, 0, 0) if the transformation should
face the origin.
up (Tuple[float, float, float]): The up axis fot the transform. ie:
(0, 0, 1) for the up-axis to correspond to the z-axis.
eye (Tuple[float, float]): The (x, y, z) location of the transform.
For example, (100, 100, 100) if we want to place a camera at
(x=100,y=100,z=100)
Returns:
np.ndarray: The 4x4 homogeneous transformation matrix.
"""
at = np.array(at)
up = np.array(up)
up = up / np.linalg.norm(up)
eye = np.array(eye)
# forward axis (z)
z_axis = np.array(eye) - np.array(at)
z_axis = z_axis / np.linalg.norm(z_axis)
# right axis (x)
x_axis = np.cross(up, z_axis)
x_axis = x_axis / np.linalg.norm(x_axis)
# up axis
y_axis = np.cross(z_axis, x_axis)
y_axis = y_axis / np.linalg.norm(y_axis)
matrix = np.array([
[x_axis[0], x_axis[1], x_axis[2], 0.0],
[y_axis[0], y_axis[1], y_axis[2], 0.0],
[z_axis[0], z_axis[1], z_axis[2], 0.0],
[eye[0], eye[1], eye[2], 1.0]
])
return matrix
| 26,895 | Python | 29.844037 | 148 | 0.625469 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/bind_mdl_material/main.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 sys
import os
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import (
add_mdl_material,
new_omniverse_stage,
add_plane,
add_box,
stack_prims,
bind_material,
add_dome_light
)
stage = new_omniverse_stage()
# Add cardboard material
cardboard = add_mdl_material(
stage,
"/scene/cardboard",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl"
)
# Add concrete material
concrete = add_mdl_material(
stage,
"/scene/concrete",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Smooth.mdl"
)
# Add floor plane
floor = add_plane(stage, "/scene/floor", size=(500, 500))
# Add box
box = add_box(stage, "/scene/box", size=(100, 100, 100))
# Stack box on floor
stack_prims([floor, box], axis=2)
# Bind materials to objects
bind_material(floor, concrete)
bind_material(box, cardboard)
# Add dome light
light = add_dome_light(stage, "/scene/dome_light") | 1,784 | Python | 28.262295 | 112 | 0.732063 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/hand_truck_w_boxes/main.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 sys
import os
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import (
add_usd_ref,
rotate_x,
rotate_y,
rotate_z,
scale,
compute_bbox,
add_xform,
compute_bbox_center,
translate,
set_visibility,
new_omniverse_stage,
add_dome_light,
add_plane,
add_mdl_material,
bind_material
)
import random
from typing import Tuple
box_asset_url = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Flat_A/FlatBox_A02_15x21x8cm_PR_NVD_01.usd"
hand_truck_asset_url = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Equipment/Hand_Trucks/Convertible_Aluminum_A/ConvertableAlumHandTruck_A02_PR_NVD_01.usd"
def add_box_of_size(
stage,
path: str,
size: Tuple[float, float, float]
):
"""Adds a box and re-scales it to match the specified dimensions
"""
# Add USD box
prim = add_usd_ref(stage, path, usd_path=box_asset_url)
rotate_x(prim, random.choice([-90, 0, 90, 180]))
rotate_y(prim, random.choice([-90, 0, 90, 180]))
# Scale USD box to fit dimensions
usd_min, usd_max = compute_bbox(prim)
usd_size = (
usd_max[0] - usd_min[0],
usd_max[1] - usd_min[1],
usd_max[2] - usd_min[2]
)
required_scale = (
size[0] / usd_size[0],
size[1] / usd_size[1],
size[2] / usd_size[2]
)
scale(prim, required_scale)
return prim
def add_random_box_stack(
stage,
path: str,
count_range=(1, 5),
size_range=((30, 30, 10), (50, 50, 25)),
angle_range=(-5, 5),
jitter_range=(-3,3)
):
container = add_xform(stage, path)
count = random.randint(*count_range)
# get sizes and sort
sizes = [
(
random.uniform(size_range[0][0], size_range[1][0]),
random.uniform(size_range[0][1], size_range[1][1]),
random.uniform(size_range[0][2], size_range[1][2])
)
for i in range(count)
]
sizes = sorted(sizes, key=lambda x: x[0]**2 + x[1]**2, reverse=True)
boxes = []
for i in range(count):
box_i = add_box_of_size(stage, os.path.join(path, f"box_{i}"), sizes[i])
boxes.append(box_i)
if count > 0:
center = compute_bbox_center(boxes[0])
for i in range(1, count):
prev_box, cur_box = boxes[i - 1], boxes[i]
cur_bbox = compute_bbox(cur_box)
cur_center = compute_bbox_center(cur_box)
prev_bbox = compute_bbox(prev_box)
offset = (
center[0] - cur_center[0],
center[1] - cur_center[1],
prev_bbox[1][2] - cur_bbox[0][2]
)
translate(cur_box, offset)
# add some noise
for i in range(count):
rotate_z(boxes[i], random.uniform(*angle_range))
translate(boxes[i], (
random.uniform(*jitter_range),
random.uniform(*jitter_range),
0
))
return container, boxes
def add_random_box_stacks(
stage,
path: str,
count_range=(0, 3),
):
container = add_xform(stage, path)
stacks = []
count = random.randint(*count_range)
for i in range(count):
stack, items = add_random_box_stack(stage, os.path.join(path, f"stack_{i}"))
stacks.append(stack)
for i in range(count):
cur_stack = stacks[i]
cur_bbox = compute_bbox(cur_stack)
cur_center = compute_bbox_center(cur_stack)
translate(cur_stack, (0, -cur_center[1], -cur_bbox[0][2]))
if i > 0:
prev_bbox = compute_bbox(stacks[i - 1])
translate(cur_stack, (prev_bbox[1][0] - cur_bbox[0][0], 0, 0))
return container, stacks
def add_hand_truck_with_boxes(stage, path: str):
container = add_xform(stage, path)
hand_truck_path = f"{path}/truck"
box_stacks_path = f"{path}/box_stacks"
add_usd_ref(
stage,
hand_truck_path,
hand_truck_asset_url
)
box_stacks_container, box_stacks = add_random_box_stacks(stage, box_stacks_path, count_range=(1,4))
rotate_z(box_stacks_container, 90)
translate(
box_stacks_container,
offset=(0, random.uniform(8, 12), 28)
)
# remove out of bounds stacks
last_visible = box_stacks[0]
for i in range(len(box_stacks)):
_, stack_bbox_max = compute_bbox(box_stacks[i])
print(stack_bbox_max)
if stack_bbox_max[1] > 74:
set_visibility(box_stacks[i], "invisible")
else:
last_visible = box_stacks[i]
# wiggle inide bounds
boxes_bbox = compute_bbox(last_visible)
wiggle = (82 - boxes_bbox[1][1])
translate(box_stacks_container, (0, random.uniform(0, wiggle), 1))
return container
stage = new_omniverse_stage()
light = add_dome_light(stage, "/scene/dome_light")
floor = add_plane(stage, "/scene/floor", size=(1000, 1000))
concrete = add_mdl_material(
stage,
"/scene/materials/concrete",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Polished.mdl"
)
bind_material(floor, concrete)
all_objects_container = add_xform(stage, "/scene/objects")
for i in range(5):
for j in range(5):
path = f"/scene/objects/hand_truck_{i}_{j}"
current_object = add_hand_truck_with_boxes(stage, path)
rotate_z(current_object, random.uniform(-15, 15))
translate(current_object, (100*i, 150*j, 0))
objects_center = compute_bbox_center(all_objects_container)
translate(all_objects_container, (-objects_center[0], -objects_center[1], 0)) | 6,545 | Python | 30.171428 | 211 | 0.609778 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/pallet_with_boxes/main.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 sys
import os
import random
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils/examples/pallet_with_boxes") # use your install path
from usd_scene_construction_utils import *
PALLET_URIS = [
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Pallets/Wood/Block_A/BlockPallet_A01_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Pallets/Wood/Block_B/BlockPallet_B01_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Pallets/Wood/Wing_A/WingPallet_A01_PR_NVD_01.usd"
]
CARDBOARD_BOX_URIS = [
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Cube_A/CubeBox_A02_16cm_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Flat_A/FlatBox_A05_26x26x11cm_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Printer_A/PrintersBox_A05_23x28x25cm_PR_NVD_01.usd"
]
def add_pallet(stage, path: str):
prim = add_usd_ref(stage, path, random.choice(PALLET_URIS))
add_semantics(prim, "class", "pallet")
return prim
def add_cardboard_box(stage, path: str):
prim = add_usd_ref(stage, path, random.choice(CARDBOARD_BOX_URIS))
add_semantics(prim, "class", "box")
return prim
def add_pallet_with_box(stage, path: str):
container = add_xform(stage, path)
pallet = add_pallet(stage, os.path.join(path, "pallet"))
box = add_cardboard_box(stage, os.path.join(path, "box"))
pallet_bbox = compute_bbox(pallet)
box_bbox = compute_bbox(box)
translate(box,(0, 0, pallet_bbox[1][2] - box_bbox[0][2]))
rotate_z(pallet, random.uniform(-25, 25))
return container
def add_tree(stage, path: str):
url = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Vegetation/Trees/American_Beech.usd"
return add_usd_ref(stage, path, url)
stage = new_omniverse_stage()
brick = add_mdl_material(stage, "/scene/brick", "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Brick_Pavers.mdl")
pallet_box = add_pallet_with_box(stage, "/scene/pallet")
floor = add_plane(stage, "/scene/floor", size=(1000, 1000), uv=(20., 20.))
tree = add_tree(stage, "/scene/tree")
translate(tree, (100, -150, 0))
bind_material(floor, brick)
light = add_dome_light(stage, "/scene/dome_light") | 3,446 | Python | 46.219177 | 180 | 0.74231 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/add_camera/main.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 sys
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import (
new_in_memory_stage,
add_box,
add_camera,
compute_look_at_matrix,
apply_xform_matrix,
export_stage
)
stage = new_in_memory_stage()
box = add_box(stage, "/scene/box", size=(100, 100, 100))
camera = add_camera(stage, "/scene/camera")
matrix = compute_look_at_matrix(
at=(0, 0, 0),
up=(0, 0, 1),
eye=(500, 500, 500)
)
apply_xform_matrix(camera, matrix)
export_stage(stage, "add_camera.usda", default_prim="/scene")
| 1,302 | Python | 27.955555 | 98 | 0.72043 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/render_with_replicator/main.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 sys
import os
import random
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import *
# set to your output dir
OUTPUT_DIR = f"{Path.home()}/usd_scene_construction_utils/examples/render_with_replicator/output"
def add_box_stack(stage, path: str, box_material):
container = add_xform(stage, path)
boxes = []
for i in range(3):
box_path = f"{path}/box_{i}"
box = add_box(stage, box_path, (random.uniform(20, 30), random.uniform(20, 30), 10))
add_semantics(box, "class", "box_stack")
bind_material(box, box_material)
rotate_z(box, random.uniform(-10, 10))
boxes.append(box)
stack_prims(boxes, axis=2)
return container
def build_scene(stage):
# Add cardboard material
cardboard = add_mdl_material(
stage,
"/scene/cardboard",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl"
)
# Add concrete material
concrete = add_mdl_material(
stage,
"/scene/concrete",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Smooth.mdl"
)
# Add floor plane
floor = add_plane(stage, "/scene/floor", size=(500, 500))
bind_material(floor, concrete)
# Add box
box_stack = add_box_stack(stage, "/scene/box_stack", box_material=cardboard)
# Stack box on floor
stack_prims([floor, box_stack], axis=2)
# Add dome light
add_dome_light(stage, "/scene/dome_light")
import omni.replicator.core as rep
with rep.new_layer():
stage = new_omniverse_stage()
build_scene(stage)
camera = rep.create.camera()
render_product = rep.create.render_product(camera, (1024, 1024))
box_stack = rep.get.prims(path_pattern="^/scene/box_stack$")
# Setup randomization
with rep.trigger.on_frame(num_frames=100):
with box_stack:
rep.modify.pose(position=rep.distribution.uniform((-100, -100, 0), (100, 100, 0)))
with camera:
rep.modify.pose(position=rep.distribution.uniform((0, 0, 0), (400, 400, 400)), look_at=(0, 0, 0))
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir=OUTPUT_DIR,
rgb=True,
bounding_box_2d_tight=True,
distance_to_camera=True,
bounding_box_3d=True,
camera_params=True,
instance_id_segmentation=True,
colorize_instance_id_segmentation=False
)
writer.attach([render_product]) | 3,298 | Python | 31.029126 | 115 | 0.671922 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/hello_box/main.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 sys
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
import random
from usd_scene_construction_utils import *
stage = new_omniverse_stage()
# Create floor
floor = add_plane(stage, "/scene/floor", (1000, 1000))
# Add a dome light
light = add_dome_light(stage, "/scene/dome_light")
# Create a grid of boxes
all_boxes = add_xform(stage, "/scene/boxes")
for i in range(5):
for j in range(5):
path = f"/scene/boxes/box_{i}_{j}"
# Add box of random size
size = (
random.uniform(20, 50),
random.uniform(20, 50),
random.uniform(20, 50),
)
box = add_box(stage, path, size=size)
# Set position in xy grid
translate(box, (100*i, 100*j, 0))
# Align z with floor
box_min, _ = compute_bbox(box)
translate(box, (0, 0, -box_min[2]))
# Translate all boxes to have xy center at (0, 0)
boxes_center = compute_bbox_center(all_boxes)
translate("/scene/boxes", (-boxes_center[0], -boxes_center[1], 0))
| 1,760 | Python | 31.018181 | 98 | 0.674432 |
NVIDIA-Omniverse/usd_scene_construction_utils/docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'USD Scene Construction Utilities'
copyright = '2023, NVIDIA'
author = 'NVIDIA'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
'sphinxcontrib.katex',
'sphinx.ext.autosectionlabel',
'sphinx_copybutton',
'sphinx_panels',
'myst_parser',
]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
| 1,307 | Python | 30.142856 | 87 | 0.627391 |
NVIDIA-Omniverse/kit-extension-sample-spawn-prims/exts/omni.example.spawn_prims/omni/example/spawn_prims/extension.py | # Copyright (c) 2023, 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 omni.ext
import omni.ui as ui
import omni.kit.commands
# 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 MyExtension starts.
Args:
ext_id : id of the extension that is
"""
print("[omni.example.spawn_prims] MyExtension startup")
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
# VStack which will layout UI elements vertically
with ui.VStack():
def on_click(prim_type):
"""
Creates a mesh primitive of the given type.
Args:
prim_type : The type of primitive to
"""
# omni.kit.commands.execute will execute the given command that is passed followed by the commands arguments
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type=prim_type,
above_ground=True)
# Button UI Elements
ui.Button("Spawn Cube", clicked_fn=lambda: on_click("Cube"))
ui.Button("Spawn Cone", clicked_fn=lambda: on_click("Cone"))
ui.Button("Spawn Cylinder", clicked_fn=lambda: on_click("Cylinder"))
ui.Button("Spawn Disk", clicked_fn=lambda: on_click("Disk"))
ui.Button("Spawn Plane", clicked_fn=lambda: on_click("Plane"))
ui.Button("Spawn Sphere", clicked_fn=lambda: on_click("Sphere"))
ui.Button("Spawn Torus", clicked_fn=lambda: on_click("Torus"))
def on_shutdown(self):
"""
Called when the extension is shutting down.
"""
print("[omni.example.spawn_prims] MyExtension shutdown")
| 2,742 | Python | 46.293103 | 128 | 0.61488 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/scripts/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 carb.settings
import omni.ui as ui
from omni.kit.window.extensions.common import get_icons_path
# Pilaged from omni.kit.widnow.property style.py
LABEL_WIDTH = 120
BUTTON_WIDTH = 120
HORIZONTAL_SPACING = 4
VERTICAL_SPACING = 5
COLOR_X = 0xFF5555AA
COLOR_Y = 0xFF76A371
COLOR_Z = 0xFFA07D4F
COLOR_W = 0xFFAA5555
def get_style():
icons_path = get_icons_path()
KIT_GREEN = 0xFF8A8777
KIT_GREEN_CHECKBOX = 0xFF9A9A9A
BORDER_RADIUS = 1.5
FONT_SIZE = 14.0
TOOLTIP_STYLE = (
{
"background_color": 0xFFD1F7FF,
"color": 0xFF333333,
"margin_width": 0,
"margin_height": 0,
"padding": 0,
"border_width": 0,
"border_radius": 1.5,
"border_color": 0x0,
},
)
style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle")
if not style_settings:
style_settings = "NvidiaDark"
if style_settings == "NvidiaLight":
WINDOW_BACKGROUND_COLOR = 0xFF444444
BUTTON_BACKGROUND_COLOR = 0xFF545454
BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E
BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778
BUTTON_LABEL_DISABLED_COLOR = 0xFF606060
FRAME_TEXT_COLOR = 0xFF545454
FIELD_BACKGROUND = 0xFF545454
FIELD_SECONDARY = 0xFFABABAB
FIELD_TEXT_COLOR = 0xFFD6D6D6
FIELD_TEXT_COLOR_READ_ONLY = 0xFF9C9C9C
FIELD_TEXT_COLOR_HIDDEN = 0x01000000
COLLAPSABLEFRAME_BORDER_COLOR = 0x0
COLLAPSABLEFRAME_BACKGROUND_COLOR = 0x7FD6D6D6
COLLAPSABLEFRAME_TEXT_COLOR = 0xFF545454
COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFFC9C9C9
COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFFD6D6D6
COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFFCCCFBF
COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B
COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR = 0xFFD6D6D6
COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR = 0xFFE6E6E6
LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD
LABEL_MIXED_COLOR = 0xFFD6D6D6
LIGHT_FONT_SIZE = 14.0
LIGHT_BORDER_RADIUS = 3
style = {
"Window": {"background_color": WINDOW_BACKGROUND_COLOR},
"Button": {"background_color": BUTTON_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 2},
"Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR},
"Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR},
"Button.Label:disabled": {"color": 0xFFD6D6D6},
"Button.Label": {"color": 0xFFD6D6D6},
"Field::models": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"secondary_color": FIELD_SECONDARY,
},
"Field::models_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
},
"Field::models_readonly": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_READ_ONLY,
"border_radius": LIGHT_BORDER_RADIUS,
"secondary_color": FIELD_SECONDARY,
},
"Field::models_readonly_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
},
"Field::models:pressed": {"background_color": 0xFFCECECE},
"Field": {"background_color": 0xFF535354, "color": 0xFFCCCCCC},
"Label": {"font_size": 12, "color": FRAME_TEXT_COLOR},
"Label::label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Label::label": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Label::title": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Label::mixed_overlay": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Label::mixed_overlay_normal": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"ComboBox::choices": {
"font_size": 12,
"color": 0xFFD6D6D6,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
"ComboBox::xform_op": {
"font_size": 10,
"color": 0xFF333333,
"background_color": 0xFF9C9C9C,
"secondary_color": 0x0,
"selected_color": 0xFFACACAF,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
"ComboBox::xform_op:hovered": {"background_color": 0x0},
"ComboBox::xform_op:selected": {"background_color": 0xFF545454},
"ComboBox": {
"font_size": 10,
"color": 0xFFE6E6E6,
"background_color": 0xFF545454,
"secondary_color": 0xFF545454,
"selected_color": 0xFFACACAF,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
# "ComboBox": {"background_color": 0xFF535354, "selected_color": 0xFFACACAF, "color": 0xFFD6D6D6},
"ComboBox:hovered": {"background_color": 0xFF545454},
"ComboBox:selected": {"background_color": 0xFF545454},
"ComboBox::choices_mixed": {
"font_size": LIGHT_FONT_SIZE,
"color": 0xFFD6D6D6,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"secondary_selected_color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
"ComboBox:hovered:choices": {"background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND},
"Slider": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.FILLED,
},
"Slider::value": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR, # COLLAPSABLEFRAME_TEXT_COLOR
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
},
"Slider::value_mixed": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
},
"Slider::multivalue": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::multivalue_mixed": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Checkbox": {
"margin": 0,
"padding": 0,
"radius": 0,
"font_size": 10,
"background_color": 0xFFA8A8A8,
"background_color": 0xFFA8A8A8,
},
"CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F},
"CheckBox::greenCheck_mixed": {
"font_size": 10,
"background_color": KIT_GREEN,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
},
"CollapsableFrame": {
"background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"color": COLLAPSABLEFRAME_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"border_color": 0x0,
"border_width": 1,
"font_size": LIGHT_FONT_SIZE,
"padding": 6,
"Tooltip": TOOLTIP_STYLE,
},
"CollapsableFrame::groupFrame": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"padding": 6,
},
"CollapsableFrame::groupFrame:hovered": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::groupFrame:pressed": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:hovered": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:pressed": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR,
},
"CollapsableFrame.Header": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FRAME_TEXT_COLOR,
"color": FRAME_TEXT_COLOR,
},
"CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR},
"CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR},
"ScrollingFrame": {"margin": 0, "padding": 3, "border_radius": LIGHT_BORDER_RADIUS},
"TreeView": {
"background_color": 0xFFE0E0E0,
"background_selected_color": 0x109D905C,
"secondary_color": 0xFFACACAC,
},
"TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0},
"TreeView.Header": {"color": 0xFFCCCCCC},
"TreeView.Header::background": {
"background_color": 0xFF535354,
"border_color": 0xFF707070,
"border_width": 0.5,
},
"TreeView.Header::columnname": {"margin": 3},
"TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF},
"TreeView.Item": {"color": 0xFF535354, "font_size": 16},
"TreeView.Item::object_name": {"margin": 3},
"TreeView.Item::object_name_grey": {"color": 0xFFACACAC},
"TreeView.Item::object_name_missing": {"color": 0xFF6F72FF},
"TreeView.Item:selected": {"color": 0xFF2A2825},
"TreeView:selected": {"background_color": 0x409D905C},
"Label::vector_label": {"font_size": 14, "color": LABEL_VECTORLABEL_COLOR},
"Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT},
"Rectangle::mixed_overlay": {
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"border_width": 3,
},
"Rectangle": {
"border_radius": LIGHT_BORDER_RADIUS,
"color": 0xFFC2C2C2,
"background_color": 0xFFC2C2C2,
}, # FIELD_BACKGROUND},
"Rectangle::xform_op:hovered": {"background_color": 0x0},
"Rectangle::xform_op": {"background_color": 0x0},
# text remove
"Button::remove": {"background_color": FIELD_BACKGROUND, "margin": 0},
"Button::remove:hovered": {"background_color": FIELD_BACKGROUND},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898},
"Button.Image::options:hovered": {"color": 0xFFC2C2C2},
"IconButton": {"margin": 0, "padding": 0, "background_color": 0x0},
"IconButton:hovered": {"background_color": 0x0},
"IconButton:checked": {"background_color": 0x0},
"IconButton:pressed": {"background_color": 0x0},
"IconButton.Image": {"color": 0xFFA8A8A8},
"IconButton.Image:hovered": {"color": 0xFF929292},
"IconButton.Image:pressed": {"color": 0xFFA4A4A4},
"IconButton.Image:checked": {"color": 0xFFFFFFFF},
"IconButton.Tooltip": {"color": 0xFF9E9E9E},
"IconButton.Image::OpenFolder": {
"image_url": f"{icons_path}/open-folder.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenConfig": {
"image_url": f"{icons_path}/open-config.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenLink": {
"image_url": "resources/glyphs/link.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenDocs": {
"image_url": "resources/glyphs/docs.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::CopyToClipboard": {
"image_url": "resources/glyphs/copy.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Export": {
"image_url": f"{icons_path}/export.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Sync": {
"image_url": "resources/glyphs/sync.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Upload": {
"image_url": "resources/glyphs/upload.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::FolderPicker": {
"image_url": "resources/glyphs/folder.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4},
"ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B},
"ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6},
"ItemButton:hovered": {"background_color": 0xFF333333},
"ItemButton:pressed": {"background_color": 0xFF222222},
"Tooltip": TOOLTIP_STYLE,
}
else:
LABEL_COLOR = 0xFF8F8E86
FIELD_BACKGROUND = 0xFF23211F
FIELD_TEXT_COLOR = 0xFFD5D5D5
FIELD_TEXT_COLOR_READ_ONLY = 0xFF5C5C5C
FIELD_TEXT_COLOR_HIDDEN = 0x01000000
FRAME_TEXT_COLOR = 0xFFCCCCCC
WINDOW_BACKGROUND_COLOR = 0xFF444444
BUTTON_BACKGROUND_COLOR = 0xFF292929
BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E
BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778
BUTTON_LABEL_DISABLED_COLOR = 0xFF606060
LABEL_LABEL_COLOR = 0xFF9E9E9E
LABEL_TITLE_COLOR = 0xFFAAAAAA
LABEL_MIXED_COLOR = 0xFFE6B067
LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD
COLORWIDGET_BORDER_COLOR = 0xFF1E1E1E
COMBOBOX_HOVERED_BACKGROUND_COLOR = 0xFF33312F
COLLAPSABLEFRAME_BORDER_COLOR = 0x0
COLLAPSABLEFRAME_BACKGROUND_COLOR = 0xFF343432
COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFF23211F
COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFF343432
COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFF2E2E2B
COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B
style = {
"Window": {"background_color": WINDOW_BACKGROUND_COLOR},
"Button": {"background_color": BUTTON_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 2},
"Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR},
"Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR},
"Button.Label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Field::models": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
},
"Field::models_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
},
"Field::models_readonly": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_READ_ONLY,
"border_radius": BORDER_RADIUS,
},
"Field::models_readonly_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
},
"Label": {"font_size": FONT_SIZE, "color": LABEL_COLOR},
"Label::label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR},
"Label::label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Label::title": {"font_size": FONT_SIZE, "color": LABEL_TITLE_COLOR},
"Label::mixed_overlay": {"font_size": FONT_SIZE, "color": LABEL_MIXED_COLOR},
"Label::mixed_overlay_normal": {"font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR},
"Label::path_label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR},
"Label::stage_label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR},
"ComboBox::choices": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"secondary_selected_color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
},
"ComboBox::choices_mixed": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"secondary_selected_color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
},
"ComboBox:hovered:choices": {
"background_color": COMBOBOX_HOVERED_BACKGROUND_COLOR,
"secondary_color": COMBOBOX_HOVERED_BACKGROUND_COLOR,
},
"Slider": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.FILLED,
},
"Slider::value": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
},
"Slider::value_mixed": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
},
"Slider::multivalue": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::multivalue_mixed": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"CheckBox::greenCheck": {
"font_size": 12,
"background_color": KIT_GREEN_CHECKBOX,
"color": FIELD_BACKGROUND,
"border_radius": BORDER_RADIUS,
},
"CheckBox::greenCheck_mixed": {
"font_size": 12,
"background_color": KIT_GREEN_CHECKBOX,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
},
"CollapsableFrame": {
"background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"border_color": COLLAPSABLEFRAME_BORDER_COLOR,
"border_width": 1,
"padding": 6,
},
"CollapsableFrame::groupFrame": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"padding": 6,
},
"CollapsableFrame::groupFrame:hovered": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::groupFrame:pressed": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:hovered": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:pressed": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR,
},
"CollapsableFrame.Header": {
"font_size": FONT_SIZE,
"background_color": FRAME_TEXT_COLOR,
"color": FRAME_TEXT_COLOR,
},
"CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR},
"CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR},
"ScrollingFrame": {"margin": 0, "padding": 3, "border_radius": BORDER_RADIUS},
"TreeView": {
"background_color": 0xFF23211F,
"background_selected_color": 0x664F4D43,
"secondary_color": 0xFF403B3B,
},
"TreeView.ScrollingFrame": {"background_color": 0xFF23211F},
"TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 12},
"TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF},
"TreeView.Image:disabled": {"color": 0x60FFFFFF},
"TreeView.Item": {"color": 0xFF8A8777},
"TreeView.Item:disabled": {"color": 0x608A8777},
"TreeView.Item::object_name_grey": {"color": 0xFF4D4B42},
"TreeView.Item::object_name_missing": {"color": 0xFF6F72FF},
"TreeView.Item:selected": {"color": 0xFF23211F},
"TreeView:selected": {"background_color": 0xFF8A8777},
"ColorWidget": {
"border_radius": BORDER_RADIUS,
"border_color": COLORWIDGET_BORDER_COLOR,
"border_width": 0.5,
},
"Label::vector_label": {"font_size": 16, "color": LABEL_VECTORLABEL_COLOR},
"PlotLabel::X": {"color": 0xFF1515EA, "background_color": 0x0},
"PlotLabel::Y": {"color": 0xFF5FC054, "background_color": 0x0},
"PlotLabel::Z": {"color": 0xFFC5822A, "background_color": 0x0},
"PlotLabel::W": {"color": 0xFFAA5555, "background_color": 0x0},
"Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT},
"Rectangle::mixed_overlay": {
"border_radius": BORDER_RADIUS,
"background_color": LABEL_MIXED_COLOR,
"border_width": 3,
},
"Rectangle": {
"border_radius": BORDER_RADIUS,
"background_color": FIELD_TEXT_COLOR_READ_ONLY,
}, # FIELD_BACKGROUND},
"Rectangle::xform_op:hovered": {"background_color": 0xFF444444},
"Rectangle::xform_op": {"background_color": 0xFF333333},
# text remove
"Button::remove": {"background_color": FIELD_BACKGROUND, "margin": 0},
"Button::remove:hovered": {"background_color": FIELD_BACKGROUND},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898},
"Button.Image::options:hovered": {"color": 0xFFC2C2C2},
"IconButton": {"margin": 0, "padding": 0, "background_color": 0x0},
"IconButton:hovered": {"background_color": 0x0},
"IconButton:checked": {"background_color": 0x0},
"IconButton:pressed": {"background_color": 0x0},
"IconButton.Image": {"color": 0xFFA8A8A8},
"IconButton.Image:hovered": {"color": 0xFFC2C2C2},
"IconButton.Image:pressed": {"color": 0xFFA4A4A4},
"IconButton.Image:checked": {"color": 0xFFFFFFFF},
"IconButton.Tooltip": {"color": 0xFF9E9E9E},
"IconButton.Image::OpenFolder": {
"image_url": f"{icons_path}/open-folder.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenConfig": {
"tooltip": TOOLTIP_STYLE,
"image_url": f"{icons_path}/open-config.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::OpenLink": {
"image_url": "resources/glyphs/link.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenDocs": {
"image_url": "resources/glyphs/docs.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::CopyToClipboard": {
"image_url": "resources/glyphs/copy.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Export": {
"image_url": f"{icons_path}/export.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Sync": {
"image_url": "resources/glyphs/sync.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Upload": {
"image_url": "resources/glyphs/upload.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::FolderPicker": {
"image_url": "resources/glyphs/folder.svg",
"background_color": 0x0,
"color": 0xFF929292,
},
"ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4},
"ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B},
"ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6},
"ItemButton:hovered": {"background_color": 0xFF333333},
"ItemButton:pressed": {"background_color": 0xFF222222},
"Tooltip": TOOLTIP_STYLE,
}
return style
| 31,271 | Python | 45.884558 | 116 | 0.53903 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/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.mjcf import _mjcf
from pxr import Usd
class MJCFCreateImportConfig(omni.kit.commands.Command):
"""
Returns an ImportConfig object that can be used while parsing and importing.
Should be used with the `MJCFCreateAsset` command
Returns:
:obj:`omni.importer.mjcf._mjcf.ImportConfig`: Parsed MJCF stored in an internal structure.
"""
def __init__(self) -> None:
pass
def do(self) -> _mjcf.ImportConfig:
return _mjcf.ImportConfig()
def undo(self) -> None:
pass
class MJCFCreateAsset(omni.kit.commands.Command):
"""
This command parses and imports a given mjcf file.
Args:
arg0 (:obj:`str`): The absolute path the mjcf file
arg1 (:obj:`omni.importer.mjcf._mjcf.ImportConfig`): Import configuration
arg2 (:obj:`str`): Path to the robot on the USD stage
arg3 (:obj:`str`): destination path for robot usd. Default is "" which will load the robot in-memory on the open stage.
"""
def __init__(
self, mjcf_path: str = "", import_config=_mjcf.ImportConfig(), prim_path: str = "", dest_path: str = ""
) -> None:
self.prim_path = prim_path
self.dest_path = dest_path
self._mjcf_path = mjcf_path
self._root_path, self._filename = os.path.split(os.path.abspath(self._mjcf_path))
self._import_config = import_config
self._mjcf_interface = _mjcf.acquire_mjcf_interface()
pass
def do(self) -> str:
# if self.prim_path:
# self.prim_path = self.prim_path.replace(
# "\\", "/"
# ) # Omni client works with both slashes cross platform, making it standard to make it easier later on
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._mjcf_interface.create_asset_mjcf(
self._mjcf_path, self.prim_path, self._import_config, self.dest_path
)
def undo(self) -> None:
pass
omni.kit.commands.register_all_commands_in_module(__name__)
| 3,194 | Python | 31.938144 | 127 | 0.649656 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/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.client._omniclient import Result
from omni.importer.mjcf import _mjcf
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from omni.kit.window.filepicker import FilePickerDialog
from pxr import Sdf, Usd, UsdGeom, UsdPhysics
# from omni.isaac.ui.menu import make_menu_item_description
from .ui_utils import (
btn_builder,
cb_builder,
dropdown_builder,
float_builder,
str_builder,
)
EXTENSION_NAME = "MJCF Importer"
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)
def is_mjcf_file(path: str):
_, ext = os.path.splitext(path.lower())
return ext == ".xml"
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_mjcf_file(item.path)
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._mjcf_interface = _mjcf.acquire_mjcf_interface()
self._usd_context = omni.usd.get_context()
self._window = omni.ui.Window(
EXTENSION_NAME, width=600, height=400, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.deferred_dock_in("Console", omni.ui.DockPolicy.DO_NOTHING)
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._models = {}
result, self._config = omni.kit.commands.execute("MJCFCreateImportConfig")
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_convex_decomp(False)
self._config.set_fix_base(False)
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_make_default_prim(True)
self._config.set_create_physics_scene(True)
self._config.set_import_sites(True)
self._config.set_visualize_collision_geoms(True)
def build_ui(self):
with self._window.frame:
with ui.VStack(spacing=20, height=0):
with ui.HStack(spacing=10):
with ui.VStack(spacing=2, height=0):
# cb_builder(
# label="Merge Fixed Joints",
# tooltip="Check this box to skip adding articulation on fixed joints",
# on_clicked_fn=lambda m, config=self._config: config.set_merge_fixed_joints(m),
# )
cb_builder(
"Fix Base Link",
tooltip="If true, enables the fix base property on the root of the articulation.",
default_val=False,
on_clicked_fn=lambda m, config=self._config: config.set_fix_base(m),
)
cb_builder(
"Import Inertia Tensor",
tooltip="If True, inertia will be loaded from mjcf, if the mjcf does not specify inertia tensor, identity will be used and scaled by the scaling factor. If false physx will compute automatically",
on_clicked_fn=lambda m, config=self._config: config.set_import_inertia_tensor(m),
)
cb_builder(
"Import Sites",
tooltip="If True, sites will be imported from mjcf.",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_import_sites(m),
)
cb_builder(
"Visualize Collision Geoms",
tooltip="If True, collision geoms will also be imported as visual geoms",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_visualize_collision_geoms(m),
)
self._models["scale"] = float_builder(
"Stage Units Per Meter",
default_val=1.0,
tooltip="[1.0 / stage_units] Set the distance units the robot is imported as, default is 1.0 corresponding to m",
)
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="[kg/stage_units^3] If a link doesn't have mass, use this density as backup, A density of 0.0 results in the physics engine automatically computing a default 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: i,
# #config.set_default_drive_type(0 if i == "None" else (1 if i == "Position" else 2)
# tooltip="Set the default drive configuration, None: stiffness and damping are zero, Position/Velocity: use default specified below.",
# )
# self._models["drive_strength"] = float_builder(
# "Joint Drive Strength",
# default_val=1e7,
# tooltip="Corresponds to stiffness for position or damping for velocity, set to -1 to prevent this value from getting used",
# )
# self._models["drive_strength"].add_value_changed_fn(
# lambda m, config=self._config: m
# # config.set_default_drive_strength(m.get_value_as_float())
# )
# self._models["position_drive_damping"] = float_builder(
# "Joint Position Drive Damping",
# default_val=1e5,
# tooltip="If the drive type is set to position, this will be used as a default damping for the drive, set to -1 to prevent this from getting used",
# )
# self._models["position_drive_damping"].add_value_changed_fn(
# lambda m, config=self._config: m
# #config.set_default_position_drive_damping(m.get_value_as_float()
# )
with ui.VStack(spacing=2, height=0):
self._models["clean_stage"] = cb_builder(
label="Clean Stage", tooltip="Check this box to load MJCF on a clean stage"
)
# cb_builder(
# "Convex Decomposition",
# tooltip="If true, non-convex meshes will be decomposed into convex collision shapes, if false a convex hull will be used.",
# on_clicked_fn=lambda m, config=self._config: config.set_convex_decomp(m),
# )
cb_builder(
"Self Collision",
tooltip="If true, allows self intersection between links in the robot, can cause instability if collision meshes between links are self intersecting",
on_clicked_fn=lambda m, config=self._config: config.set_self_collision(m),
)
cb_builder(
"Create Physics Scene",
tooltip="If true, creates a default physics scene if one does not already exist in the stage",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_create_physics_scene(m),
),
cb_builder(
"Make Default Prim",
tooltip="If true, makes imported robot the default prim for the stage",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_make_default_prim(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())
)
with ui.VStack(height=0):
with ui.HStack(spacing=20):
btn_builder("Import MJCF", text="Select and Import", on_clicked_fn=self._parse_mjcf)
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()
else:
self._events = None
self._stage_event_sub = None
def _refresh_filebrowser(self):
parent = None
selection_name = None
if len(self._filebrowser.get_selections()):
parent = self._filebrowser.get_selections()[0].parent
selection_name = self._filebrowser.get_selections()[0].name
self._filebrowser.refresh_ui(parent)
if selection_name:
selection = [child for child in parent.children.values() if child.name == selection_name]
if len(selection):
self._filebrowser.select_and_center(selection[0])
def _parse_mjcf(self):
self._filepicker = FilePickerDialog(
"Import MJCF",
allow_multi_selection=False,
apply_button_label="Import",
click_apply_handler=lambda filename, path, c=weakref.proxy(self): c._select_picked_file_callback(
self._filepicker, filename, path
),
click_cancel_handler=lambda a, b, c=weakref.proxy(self): c._filepicker.hide(),
item_filter_fn=on_filter_item,
enable_versioning_pane=True,
)
if self._last_folder:
self._filepicker.set_current_directory(self._last_folder)
self._filepicker.navigate_to(self._last_folder)
self._filepicker.refresh_current_directory()
self._filepicker.toggle_bookmark_from_path("Built In MJCF Files", (self._extension_path + "/data/mjcf"), True)
self._filepicker.show()
def _load_robot(self, path=None):
if path:
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]
# sanitize basename
if basename[0].isdigit():
basename = "_" + basename
full_path = os.path.abspath(os.path.join(self.root_path, self.filename))
dest_path = "{}/{}/{}.usd".format(base_path, basename, basename)
current_stage = omni.usd.get_context().get_stage()
prim_path = omni.usd.get_stage_next_free_path(current_stage, "/" + basename, False)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=full_path,
import_config=self._config,
prim_path=prim_path,
dest_path=dest_path,
)
stage = Usd.Stage.Open(dest_path)
prim_name = str(stage.GetDefaultPrim().GetName())
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()
current_stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(current_stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 1)
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:
upAxis = UsdGeom.GetStageUpAxis(current_stage)
if upAxis == "Y":
carb.log_error("The stage Up-Axis must be Z to use the MJCF importer")
add_reference_to_stage()
def _select_picked_file_callback(self, dialog: FilePickerDialog, filename=None, path=None):
if not path.startswith("omniverse://"):
self.root_path = path
self.filename = filename
if path and filename:
self._last_folder = path
self._load_robot(path + "/" + filename)
else:
carb.log_error("path and filename not specified")
else:
carb.log_error("Only Local Paths supported")
dialog.hide()
def on_shutdown(self):
_mjcf.release_mjcf_interface(self._mjcf_interface)
if self._filepicker:
self._filepicker.toggle_bookmark_from_path(
"Built In MJCF Files", (self._extension_path + "/data/mjcf"), False
)
self._filepicker.destroy()
self._filepicker = None
remove_menu_items(self._menu_items, "Isaac Utils")
if self._window:
self._window = None
gc.collect()
| 18,382 | Python | 48.549865 | 224 | 0.543194 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/scripts/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.
# str_builder
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 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 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 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 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 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 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 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 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
| 10,551 | Python | 35.512111 | 120 | 0.619278 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/tests/test_mjcf.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 filecmp
import os
import carb
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 TestMJCF(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.mjcf")
self._extension_path = ext_manager.get_extension_path(ext_id)
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
# After running each test
async def tearDown(self):
while omni.usd.get_context().get_stage_loading_status()[2] > 0:
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await omni.kit.app.get_app().next_update_async()
await omni.usd.get_context().new_stage_async()
async def test_mjcf_ant(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
await omni.kit.app.get_app().next_update_async()
# check if object is there
prim = stage.GetPrimAtPath("/ant")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints and links exist
front_left_leg_joint = stage.GetPrimAtPath("/ant/torso/joints/hip_1")
self.assertNotEqual(front_left_leg_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(front_left_leg_joint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertAlmostEqual(front_left_leg_joint.GetAttribute("physics:upperLimit").Get(), 40)
self.assertAlmostEqual(front_left_leg_joint.GetAttribute("physics:lowerLimit").Get(), -40)
front_left_leg = stage.GetPrimAtPath("/ant/torso/front_left_leg")
self.assertAlmostEqual(front_left_leg.GetAttribute("physics:diagonalInertia").Get()[0], 0.0)
self.assertAlmostEqual(front_left_leg.GetAttribute("physics:mass").Get(), 0.0)
front_left_foot_joint = stage.GetPrimAtPath("/ant/torso/joints/ankle_1")
self.assertNotEqual(front_left_foot_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(front_left_foot_joint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertAlmostEqual(front_left_foot_joint.GetAttribute("physics:upperLimit").Get(), 100)
self.assertAlmostEqual(front_left_foot_joint.GetAttribute("physics:lowerLimit").Get(), 30)
front_left_foot = stage.GetPrimAtPath("/ant/torso/front_left_foot")
self.assertAlmostEqual(front_left_foot.GetAttribute("physics:diagonalInertia").Get()[0], 0.0)
self.assertAlmostEqual(front_left_foot.GetAttribute("physics:mass").Get(), 0.0)
# 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)
async def test_mjcf_humanoid(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_humanoid.xml",
import_config=import_config,
prim_path="/humanoid",
)
await omni.kit.app.get_app().next_update_async()
# check if object is there
prim = stage.GetPrimAtPath("/humanoid")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints and link exist
root_joint = stage.GetPrimAtPath("/humanoid/torso/joints/rootJoint_torso")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
pelvis_joint = stage.GetPrimAtPath("/humanoid/torso/joints/abdomen_x")
self.assertNotEqual(pelvis_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(pelvis_joint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertAlmostEqual(pelvis_joint.GetAttribute("physics:upperLimit").Get(), 35)
self.assertAlmostEqual(pelvis_joint.GetAttribute("physics:lowerLimit").Get(), -35)
lower_waist_joint = stage.GetPrimAtPath("/humanoid/torso/joints/lower_waist")
self.assertNotEqual(lower_waist_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(lower_waist_joint.GetTypeName(), "PhysicsJoint")
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotX:physics:high").Get(), 45)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotX:physics:low").Get(), -45)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotY:physics:high").Get(), 30)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotY:physics:low").Get(), -75)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotZ:physics:high").Get(), -1)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotZ:physics:low").Get(), 1)
left_foot = stage.GetPrimAtPath("/humanoid/torso/left_foot")
self.assertAlmostEqual(left_foot.GetAttribute("physics:diagonalInertia").Get()[0], 0.0)
self.assertAlmostEqual(left_foot.GetAttribute("physics:mass").Get(), 0.0)
# 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)
# 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, PhysicsSchemaTools, Sdf, UsdLux, UsdPhysics
# setting up import configuration:
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
# 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.mjcf")
extension_path = ext_manager.get_extension_path(ext_id)
# import MJCF
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
# 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 lighting
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
async def test_mjcf_scale(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_distance_scale(100.0)
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
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), 0.01)
async def test_mjcf_self_collision(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(True)
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/ant/torso")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(prim.GetAttribute("physxArticulation:enabledSelfCollisions").Get(), True)
# 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()
async def test_mjcf_default_prim(self):
stage = omni.usd.get_context().get_stage()
mjcf_path = os.path.abspath(self._extension_path + "/data/mjcf/nv_ant.xml")
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
import_config.set_make_default_prim(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant_1",
)
await omni.kit.app.get_app().next_update_async()
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant_2",
)
await omni.kit.app.get_app().next_update_async()
default_prim = stage.GetDefaultPrim()
self.assertNotEqual(default_prim.GetPath(), Sdf.Path.emptyPath)
prim_2 = stage.GetPrimAtPath("/ant_2")
self.assertNotEqual(prim_2.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(default_prim.GetPath(), prim_2.GetPath())
async def test_mjcf_visualize_collision_geom(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(True)
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
import_config.set_visualize_collision_geoms(False)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/open_ai_assets/hand/manipulate_block.xml",
import_config=import_config,
prim_path="/shadow_hand",
)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/shadow_hand/robot0_hand_mount/robot0_forearm/visuals/robot0_C_forearm")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
imageable = UsdGeom.Imageable(prim)
visibility_attr = imageable.GetVisibilityAttr().Get()
self.assertEqual(visibility_attr, "invisible")
# 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()
async def test_mjcf_import_shadow_hand_egg(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/open_ai_assets/hand/manipulate_egg_touch_sensors.xml",
import_config=import_config,
prim_path="/shadow_hand",
)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/shadow_hand/robot0_hand_mount")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
prim = stage.GetPrimAtPath("/shadow_hand/object")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
prim = stage.GetPrimAtPath("/shadow_hand/worldBody")
self.assertNotEqual(prim.GetPath(), 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()
async def test_mjcf_import_humanoid_100(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(False)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/mujoco_sim_assets/humanoid100.xml",
import_config=import_config,
prim_path="/humanoid_100",
)
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()
| 15,081 | Python | 43.753709 | 142 | 0.660898 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.