file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_09_02/scripts/what_is_cl.py
|
# SPDX-License-Identifier: Apache-2.0
import omni.ui as ui
from omni.ui import color as cl
# import omni.ui.color as color
my_window = ui.Window("Example Window", width=300, height=300)
with my_window.frame:
with ui.VStack():
ui.Label("Hello World!", style={"color": cl(0.0, 1.0, 0.0)})
| 303 |
Python
| 22.384614 | 68 | 0.673267 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_09_02/config/extension.toml
|
[package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "2022-09-02: Dev Office Hours"
description="Sample code from the Dev Office Hour held on 2022-09-02"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import maticodes.doh_2022_09_02".
[[python.module]]
name = "maticodes.doh_2022_09_02"
| 784 |
TOML
| 26.068965 | 113 | 0.732143 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_09_02/docs/README.md
|
# Developer Office Hour - 09/02/2022
This is the sample code from the Developer Office Hour held on 09/02/2022, Mati answered some developer questions from the NVIDIA Omniverse forums regarding Kit, Omniverse Code, Python, and USD.
## Questions
- What's the difference between a shape and a mesh?
- How do I import cl?
- How do I import sc?
- How do I define UI colors?
- How do I add an item to a menu?
| 405 |
Markdown
| 39.599996 | 194 | 0.748148 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_11_18/maticodes/doh_2022_11_18/extension.py
|
# SPDX-License-Identifier: Apache-2.0
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
import omni.ui as ui
class MyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
carb.log_info("[maticodes.doh_2022_11_18] Dev Office Hours Extension (2022-11-18) startup")
self.custom_frame = None
viewport_window = get_active_viewport_window()
if viewport_window is not None:
self.custom_frame: ui.Frame = viewport_window.get_frame(ext_id)
with self.custom_frame:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Button("Hello", width=0, height=0)
def on_shutdown(self):
carb.log_info("[maticodes.doh_2022_11_18] Dev Office Hours Extension (2022-11-18) shutdown")
self.custom_frame.destroy()
self.custom_frame = None
| 990 |
Python
| 32.033332 | 100 | 0.59596 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_11_18/maticodes/doh_2022_11_18/__init__.py
|
# SPDX-License-Identifier: Apache-2.0
from .extension import *
| 64 |
Python
| 15.249996 | 37 | 0.75 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_11_18/scripts/placer_model.py
|
# SPDX-License-Identifier: Apache-2.0
import omni.ui as ui
my_window = ui.Window("Example Window", width=300, height=300)
model = ui.SimpleFloatModel()
sub = None
with my_window.frame:
with ui.VStack():
ui.FloatSlider(model=model)
def body_moved(body, model):
if body.offset_x.value > 100:
body.offset_x.value = 100
elif body.offset_x.value < 0:
body.offset_x.value = 0
model.set_value(body.offset_x.value / 100.0)
body = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=0)
with body:
rect = ui.Rectangle(width=25, height=25, style={"background_color": ui.color.red})
body.set_offset_x_changed_fn(lambda _, b=body, m=model: body_moved(b, m))
def slider_moved(model, body):
body.offset_x.value = model.as_float * 100
sub = model.subscribe_value_changed_fn(lambda m=model, b=body: slider_moved(m, b))
| 996 |
Python
| 34.607142 | 94 | 0.589357 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_11_18/config/extension.toml
|
[package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "2022-11-18: Dev Office Hours"
description="Sample code from the Dev Office Hour held on 2022-11-18"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import maticodes.doh_2022_11_18".
[[python.module]]
name = "maticodes.doh_2022_11_18"
| 784 |
TOML
| 26.068965 | 113 | 0.732143 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_11_18/docs/README.md
|
# Developer Office Hour - 11/18/2022
This is the sample code from the Developer Office Hour held on 11/18/2022, Mati answered some developer questions
from the NVIDIA Omniverse forums regarding Kit, Omniverse Code, Python, and USD.
## Questions
- How do I add widgets on top of the viewport? (ViewportWindow.get_frame)
- How do I use value model with ui.Placer?
- How do I see all of the code from the UI documentation examples?
| 431 |
Markdown
| 46.999995 | 114 | 0.770302 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_10_07/maticodes/doh_2022_10_07/extension.py
|
# SPDX-License-Identifier: Apache-2.0
import carb
import omni.ext
import omni.ui as ui
class MyWindow(ui.Window):
def __init__(self, title: str = None, **kwargs):
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_window)
def _build_window(self):
with ui.ScrollingFrame():
with ui.VStack(height=0):
ui.Label("My Label")
def clicked():
carb.log_info("Button Clicked!")
ui.Button("Click Me", clicked_fn=clicked)
class MyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
carb.log_info("[maticodes.doh_2022_10_07] Dev Office Hours Extension (2022-10-07) startup")
self._window = MyWindow("MyWindow", width=300, height=300)
def on_shutdown(self):
carb.log_info("[maticodes.doh_2022_10_07] Dev Office Hours Extension (2022-10-07) shutdown")
if self._window:
self._window.destroy()
self._window = None
| 1,005 |
Python
| 28.588234 | 100 | 0.595025 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_10_07/maticodes/doh_2022_10_07/__init__.py
|
# SPDX-License-Identifier: Apache-2.0
from .extension import *
| 64 |
Python
| 15.249996 | 37 | 0.75 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_10_07/scripts/usd_update_stream.py
|
# SPDX-License-Identifier: Apache-2.0
import omni.usd
from pxr import UsdGeom, Gf
stage = omni.usd.get_context().get_stage()
cube = stage.GetPrimAtPath("/World/Cube")
def print_pos(changed_path):
print(changed_path)
if changed_path.IsPrimPath():
prim_path = changed_path
else:
prim_path = changed_path.GetPrimPath()
prim = stage.GetPrimAtPath(prim_path)
world_transform = omni.usd.get_world_transform_matrix(prim)
translation: Gf.Vec3d = world_transform.ExtractTranslation()
rotation: Gf.Rotation = world_transform.ExtractRotation()
scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix()))
print(translation, rotation, scale)
cube_move_sub = omni.usd.get_watcher().subscribe_to_change_info_path(cube.GetPath(), print_pos)
| 813 |
Python
| 37.761903 | 97 | 0.719557 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_10_07/scripts/create_viewport.py
|
# SPDX-License-Identifier: Apache-2.0
import carb
import omni.kit.viewport.utility as vp_utils
from omni.kit.widget.viewport.api import ViewportAPI
vp_window = vp_utils.create_viewport_window("My Viewport")
vp_window.viewport_api.fill_frame = True
vp_api: ViewportAPI = vp_window.viewport_api
carb.settings.get_settings().set('/rtx/rendermode', "PathTracing")
vp_api.set_hd_engine("rtx")
| 392 |
Python
| 27.071427 | 66 | 0.770408 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_10_07/config/extension.toml
|
[package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "2022-10-07: Dev Office Hours"
description="Sample code from the Dev Office Hour held on 2022-10-07"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import maticodes.doh_2022_10_07".
[[python.module]]
name = "maticodes.doh_2022_10_07"
| 784 |
TOML
| 26.068965 | 113 | 0.732143 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_10_07/docs/README.md
|
# Developer Office Hour - 10/07/2022
This is the sample code from the Developer Office Hour held on 10/07/2022, Mati answered some developer questions
from the NVIDIA Omniverse forums regarding Kit, Omniverse Code, Python, and USD.
## Questions
- How do I create another viewport?
- How do I use the Script Node?
| 315 |
Markdown
| 38.499995 | 114 | 0.771429 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_12_02/maticodes/doh_2022_12_02/extension.py
|
# SPDX-License-Identifier: Apache-2.0
import carb
import omni.ext
import omni.ui as ui
class MyWindow(ui.Window):
def __init__(self, title: str = None, **kwargs):
super().__init__(title, **kwargs)
self.frame.set_build_fn(self._build_window)
def _build_window(self):
with ui.ScrollingFrame():
with ui.VStack(height=0):
with ui.HStack(height=0):
ui.Label("My Label")
MyCoolComponent()
def clicked():
carb.log_info("Button Clicked!")
ui.Button("Click Me", clicked_fn=clicked)
class MyCoolComponent:
def __init__(self):
with ui.VStack():
ui.Label("Moar labels- asdfasdfasdf")
ui.Label("Even moar labels")
with ui.HStack():
ui.Button("Ok")
ui.Button("Cancel")
class MyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
"""_summary_
Args:
ext_id (_type_): _description_
"""
carb.log_info("[maticodes.doh_2022_12_02] Dev Office Hours Extension (2022-12-02) startup")
self._window = MyWindow("MyWindow", width=300, height=300)
def on_shutdown(self):
carb.log_info("[maticodes.doh_2022_12_02] Dev Office Hours Extension (2022-12-02) shutdown")
if self._window:
self._window.destroy()
self._window = None
| 1,442 |
Python
| 28.448979 | 100 | 0.549237 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_12_02/maticodes/doh_2022_12_02/__init__.py
|
# SPDX-License-Identifier: Apache-2.0
from .extension import *
| 64 |
Python
| 15.249996 | 37 | 0.75 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_12_02/scripts/spawn_objects.py
|
# SPDX-License-Identifier: Apache-2.0
import carb.events
import omni.kit.app
import omni.kit.commands
import logging
time_since_last_create = 0
update_stream = omni.kit.app.get_app().get_update_event_stream()
def on_update(e: carb.events.IEvent):
global time_since_last_create
carb.log_info(f"Update: {e.payload['dt']}")
time_since_last_create += e.payload['dt']
carb.log_info(f"time since: {time_since_last_create}")
if time_since_last_create > 2:
carb.log_info("Creating cube")
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube')
time_since_last_create = 0
sub = update_stream.create_subscription_to_pop(on_update, name="My Subscription Name")
sub = None
| 745 |
Python
| 27.692307 | 86 | 0.69396 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_12_02/config/extension.toml
|
[package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "2022-12-02: Dev Office Hours"
description="Sample code from the Dev Office Hour held on 2022-12-02"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import maticodes.doh_2022_12_02".
[[python.module]]
name = "maticodes.doh_2022_12_02"
| 784 |
TOML
| 26.068965 | 113 | 0.732143 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_12_02/docs/README.md
|
# Developer Office Hour - 12/02/2022
This is the sample code from the Developer Office Hour held on 12/02/2022, Mati answered some developer questions
from the NVIDIA Omniverse forums regarding Kit, Omniverse Code, Python, and USD.
## Questions
- How do I uninstall an extension?
- How do I export USDZ?
- Where is the extension I was working on?
- How do I create complex UI without so much indented Python code?
| 416 |
Markdown
| 40.699996 | 114 | 0.769231 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/maticodes/doh_2022_08_12/extension.py
|
# SPDX-License-Identifier: Apache-2.0
import carb
import omni.ext
from omni.kit.viewport.utility import get_active_viewport_window
import omni.ui as ui
from .viewport_scene import ViewportScene
from .object_info_model import ObjectInfoModel
class MyWindow(ui.Window):
def __init__(self, title: str = None, delegate=None, **kwargs):
super().__init__(title, **kwargs)
self._viewport_scene = None
self.obj_info_model = kwargs["obj_info_model"]
self.frame.set_build_fn(self._build_window)
def _build_window(self):
with ui.ScrollingFrame():
with ui.VStack(height=0):
ui.Label("My Label 2")
ui.StringField()
ui.StringField(password_mode=True)
def clicked():
self.obj_info_model.populate()
ui.Button("Reload Object Info", clicked_fn=clicked)
def destroy(self) -> None:
return super().destroy()
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):
# 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
model = ObjectInfoModel()
self._viewport_scene = ViewportScene(viewport_window, ext_id, model)
self._window = MyWindow("MyWindow", obj_info_model=model, width=300, height=300)
def on_shutdown(self):
if self._window:
self._window.destroy()
self._window = None
if self._viewport_scene:
self._viewport_scene.destroy()
self._viewport_scene = None
| 1,997 |
Python
| 31.754098 | 119 | 0.618928 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/maticodes/doh_2022_08_12/viewport_scene.py
|
# SPDX-License-Identifier: Apache-2.0
# 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__ = ["ViewportScene"]
from omni.ui import scene as sc
import omni.ui as ui
from .object_info_manipulator import ObjectInfoManipulator
class ViewportScene():
"""The Object Info Manipulator, placed into a Viewport"""
def __init__(self, viewport_window: ui.Window, ext_id: str, model) -> None:
self._scene_view = None
self._viewport_window = viewport_window
# Create a unique frame for our SceneView
with self._viewport_window.get_frame(ext_id):
# Create a default SceneView (it has a default camera-model)
self._scene_view = sc.SceneView()
# Add the manipulator into the SceneView's scene
with self._scene_view.scene:
ObjectInfoManipulator(model=model)
# Register the SceneView with the Viewport to get projection and view updates
self._viewport_window.viewport_api.add_scene_view(self._scene_view)
def __del__(self):
self.destroy()
def destroy(self):
if self._scene_view:
# Empty the SceneView of any elements it may have
self._scene_view.scene.clear()
# Be a good citizen, and un-register the SceneView from Viewport updates
if self._viewport_window:
self._viewport_window.viewport_api.remove_scene_view(self._scene_view)
# Remove our references to these objects
self._viewport_window = None
self._scene_view = None
| 1,938 |
Python
| 37.779999 | 89 | 0.676987 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/maticodes/doh_2022_08_12/__init__.py
|
# SPDX-License-Identifier: Apache-2.0
from .extension import *
| 64 |
Python
| 15.249996 | 37 | 0.75 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/maticodes/doh_2022_08_12/object_info_model.py
|
# SPDX-License-Identifier: Apache-2.0
# 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__ = ["ObjectInfoModel"]
from pxr import Tf
from pxr import Usd
from pxr import UsdGeom
from omni.ui import scene as sc
import omni.usd
# The distance to raise above the top of the object's bounding box
TOP_OFFSET = 5
class ObjectInfoModel(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):
super().__init__()
self.value = [0, 0, 0]
def __init__(self):
super().__init__()
# Current selected prim and material
self._current_paths = []
self.positions = []
self._stage_listener = None
self.populate()
if not self._stage_listener:
# This handles camera movement
usd_context = self._get_context()
stage = usd_context.get_stage()
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage)
def populate(self):
self._current_paths = []
self.positions = []
usd_context = self._get_context()
stage = usd_context.get_stage()
prim = stage.GetPrimAtPath("/World/Labeled")
if not prim.IsValid():
return
for child in prim.GetChildren():
if child.IsA(UsdGeom.Imageable):
self._current_paths.append(child.GetPath())
self.positions.append(ObjectInfoModel.PositionItem())
# Position is changed because new selected object has a different position
self._item_changed(self.positions[-1])
def _get_context(self):
# Get the UsdContext we are attached to
return omni.usd.get_context()
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():
for i, watched_path in enumerate(self._current_paths):
if str(watched_path) in str(p.GetPrimPath()):
self._item_changed(self.positions[i])
def get_name(self, index):
return self._current_paths[index]
def get_num_prims(self):
return len(self._current_paths)
def get_position(self, index):
"""Returns position of currently selected object"""
stage = self._get_context().get_stage()
if not stage or not self._current_paths[index]:
return [0, 0, 0]
# Get position directly from USD
prim = stage.GetPrimAtPath(self._current_paths[index])
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.
position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + TOP_OFFSET, (bboxMin[2] + bboxMax[2]) * 0.5]
return position
| 3,774 |
Python
| 36.376237 | 110 | 0.63646 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/maticodes/doh_2022_08_12/object_info_manipulator.py
|
# SPDX-License-Identifier: Apache-2.0
# 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
for i in range(self.model.get_num_prims()):
position = self.model.get_position(i)
# 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_name(i)}",
alignment=ui.Alignment.LEFT_BOTTOM)
def on_model_updated(self, item):
# Regenerate the manipulator
self.invalidate()
| 2,870 |
Python
| 43.859374 | 112 | 0.617073 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/scripts/viewport_popup_notification.py
|
# SPDX-License-Identifier: Apache-2.0
# https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.kit.notification_manager/docs/index.html?highlight=omni%20kit%20notification_manager#
import carb
def clicked_ok():
carb.log_info("User clicked ok")
def clicked_cancel():
carb.log_info("User clicked cancel")
import omni.kit.notification_manager as nm
ok_button = nm.NotificationButtonInfo("OK", on_complete=clicked_ok)
cancel_button = nm.NotificationButtonInfo("CANCEL", on_complete=clicked_cancel)
notification_info = nm.post_notification(
"Notification Example",
hide_after_timeout=False,
duration=0,
status=nm.NotificationStatus.WARNING,
button_infos=[ok_button, cancel_button],
)
| 723 |
Python
| 27.959999 | 151 | 0.755187 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/scripts/create_many_prims.py
|
# SPDX-License-Identifier: Apache-2.0
from pxr import UsdGeom
import omni.kit.commands
import omni.usd
stage = omni.usd.get_context().get_stage()
cube_paths = []
for i in range(10):
cube_path = omni.usd.get_stage_next_free_path(stage, "/World/Cube", prepend_default_prim=False)
cube_paths.append(cube_path)
omni.kit.commands.execute("CreatePrim", prim_type="Cube", prim_path=cube_path)
# UsdGeom.Cube.Define(stage, cube_path)
| 445 |
Python
| 28.733331 | 99 | 0.719101 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/scripts/refer_to_child_prim.py
|
# SPDX-License-Identifier: Apache-2.0
# https://docs.omniverse.nvidia.com/prod_usd/prod_usd/quick-start/hierarchy.html
import omni.usd
stage = omni.usd.get_context().get_stage()
starting_prim = stage.GetPrimAtPath("/World/New")
for shape in starting_prim.GetChildren():
print(shape)
for shape_child in shape.GetChildren():
print(shape_child)
for prim in stage.Traverse():
print(prim)
| 408 |
Python
| 24.562498 | 80 | 0.720588 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/scripts/create_group_anywhere.py
|
# SPDX-License-Identifier: Apache-2.0
from pxr import Sdf
import omni.kit.commands
import omni.usd
stage = omni.usd.get_context().get_stage()
children = []
for i in range(3):
child = omni.usd.get_stage_next_free_path(stage, "/World/Cube", prepend_default_prim=False)
children.append(child)
omni.kit.commands.execute("CreatePrim", prim_type="Cube", prim_path=child)
group_path = Sdf.Path("/World/New/Hello")
omni.kit.commands.execute("CreatePrimWithDefaultXformCommand", prim_type="Scope", prim_path=str(group_path))
for child in children:
prim = stage.GetPrimAtPath(child)
name = prim.GetName()
omni.kit.commands.execute("MovePrim", path_from=child, path_to=group_path.AppendPath(name))
| 715 |
Python
| 33.095237 | 108 | 0.731469 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/scripts/does_prim_exist.py
|
# SPDX-License-Identifier: Apache-2.0
from pxr import Usd, UsdGeom
import omni.usd
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/World/New/Hello")
print(prim)
print(prim.IsValid())
prim = stage.GetPrimAtPath("/World/New/Fake")
print(prim)
print(prim.IsValid())
| 290 |
Python
| 19.785713 | 46 | 0.737931 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/config/extension.toml
|
[package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "2022-08-12: Dev Office Hours"
description="Sample code from the Dev Office Hour held on 2022-08-12"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import maticodes.doh_2022_08_12".
[[python.module]]
name = "maticodes.doh_2022_08_12"
| 784 |
TOML
| 26.068965 | 113 | 0.732143 |
mati-nvidia/developer-office-hours/exts/maticodes.doh_2022_08_12/docs/README.md
|
# Developer Office Hour - 08/12/2022
This is the sample code from the Developer Office Hour held on 08/12/2022, Mati answered some developer questions
from the NVIDIA Omniverse forums regarding Kit, Omniverse Code, Python, and USD.
## Questions
- How do I create many prims at available prim paths?
- How do I create a group at a specific prim path?
- Is there a way to check if a prim exists?
- How do I refer to the child of a prim without giving the prim path?
- How can I create a notification popup in the viewport with a log message?
- How do I show labels in the viewport for multiple prims?
...
| 605 |
Markdown
| 45.615381 | 114 | 0.758678 |
omniverse-code/kit/gsl/README.packman.md
|
* Package: gsl
* Version: 3.1.0.1
* From: ssh://[email protected]:12051/omniverse/externals/gsl.git
* Branch: master
* Commit: 5e0543eb9d231a0d3ccd7f5789aa51d1c896f6ae
* Time: Fri Nov 06 14:03:26 2020
* Computername: KPICOTT-LT
* Packman: 5.13.2
| 257 |
Markdown
| 27.666664 | 76 | 0.750973 |
omniverse-code/kit/gsl/appveyor.yml
|
shallow_clone: true
platform:
- x86
- x64
configuration:
- Debug
- Release
image:
- Visual Studio 2017
- Visual Studio 2019
environment:
NINJA_TAG: v1.8.2
NINJA_SHA512: 9B9CE248240665FCD6404B989F3B3C27ED9682838225E6DC9B67B551774F251E4FF8A207504F941E7C811E7A8BE1945E7BCB94472A335EF15E23A0200A32E6D5
NINJA_PATH: C:\Tools\ninja\ninja-%NINJA_TAG%
VCVAR2017: 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat'
VCVAR2019: 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat'
matrix:
- GSL_CXX_STANDARD: 14
USE_TOOLSET: MSVC
USE_GENERATOR: MSBuild
- GSL_CXX_STANDARD: 17
USE_TOOLSET: MSVC
USE_GENERATOR: MSBuild
- GSL_CXX_STANDARD: 14
USE_TOOLSET: LLVM
USE_GENERATOR: Ninja
- GSL_CXX_STANDARD: 17
USE_TOOLSET: LLVM
USE_GENERATOR: Ninja
cache:
- C:\cmake-3.14.4-win32-x86
- C:\Tools\ninja
install:
- ps: |
if (![IO.File]::Exists("$env:NINJA_PATH\ninja.exe")) {
Start-FileDownload `
"https://github.com/ninja-build/ninja/releases/download/$env:NINJA_TAG/ninja-win.zip"
$hash = (Get-FileHash ninja-win.zip -Algorithm SHA512).Hash
if ($env:NINJA_SHA512 -eq $hash) {
7z e -y -bso0 ninja-win.zip -o"$env:NINJA_PATH"
} else { Write-Warning "Ninja download hash changed!"; Write-Output "$hash" }
}
if ([IO.File]::Exists("$env:NINJA_PATH\ninja.exe")) {
$env:PATH = "$env:NINJA_PATH;$env:PATH"
} else { Write-Warning "Failed to find ninja.exe in expected location." }
if ($env:USE_TOOLSET -ne "LLVM") {
if (![IO.File]::Exists("C:\cmake-3.14.0-win32-x86\bin\cmake.exe")) {
Start-FileDownload 'https://cmake.org/files/v3.14/cmake-3.14.4-win32-x86.zip'
7z x -y -bso0 cmake-3.14.4-win32-x86.zip -oC:\
}
$env:PATH="C:\cmake-3.14.4-win32-x86\bin;$env:PATH"
}
before_build:
- ps: |
if ("$env:USE_GENERATOR" -eq "Ninja") {
$GeneratorFlags = '-k 10'
$Architecture = $env:PLATFORM
if ("$env:APPVEYOR_BUILD_WORKER_IMAGE" -eq "Visual Studio 2017") {
$env:VCVARSALL = "`"$env:VCVAR2017`" $Architecture"
} else {
$env:VCVARSALL = "`"$env:VCVAR2019`" $Architecture"
}
$env:CMakeGenFlags = "-G Ninja -DGSL_CXX_STANDARD=$env:GSL_CXX_STANDARD"
} else {
$GeneratorFlags = '/m /v:minimal'
if ("$env:APPVEYOR_BUILD_WORKER_IMAGE" -eq "Visual Studio 2017") {
$Generator = 'Visual Studio 15 2017'
} else {
$Generator = 'Visual Studio 16 2019'
}
if ("$env:PLATFORM" -eq "x86") {
$Architecture = "Win32"
} else {
$Architecture = "x64"
}
if ("$env:USE_TOOLSET" -eq "LLVM") {
$env:CMakeGenFlags = "-G `"$Generator`" -A $Architecture -T llvm -DGSL_CXX_STANDARD=$env:GSL_CXX_STANDARD"
} else {
$env:CMakeGenFlags = "-G `"$Generator`" -A $Architecture -DGSL_CXX_STANDARD=$env:GSL_CXX_STANDARD"
}
}
if ("$env:USE_TOOLSET" -eq "LLVM") {
$env:CC = "clang-cl"
$env:CXX = "clang-cl"
if ("$env:PLATFORM" -eq "x86") {
$env:CFLAGS = "-m32";
$env:CXXFLAGS = "-m32";
} else {
$env:CFLAGS = "-m64";
$env:CXXFLAGS = "-m64";
}
}
$env:CMakeBuildFlags = "--config $env:CONFIGURATION -- $GeneratorFlags"
- mkdir build
- cd build
- if %USE_GENERATOR%==Ninja (call %VCVARSALL%)
- echo %CMakeGenFlags%
- cmake .. %CMakeGenFlags%
build_script:
- echo %CMakeBuildFlags%
- cmake --build . %CMakeBuildFlags%
test_script:
- ctest -j2
deploy: off
| 3,759 |
YAML
| 31.695652 | 144 | 0.592445 |
omniverse-code/kit/gsl/README.md
|
# GSL: Guidelines Support Library
[](https://travis-ci.org/Microsoft/GSL) [](https://ci.appveyor.com/project/neilmacintosh/GSL)
The Guidelines Support Library (GSL) contains functions and types that are suggested for use by the
[C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines) maintained by the [Standard C++ Foundation](https://isocpp.org).
This repo contains Microsoft's implementation of GSL.
The library includes types like `span<T>`, `string_span`, `owner<>` and others.
The entire implementation is provided inline in the headers under the [gsl](./include/gsl) directory. The implementation generally assumes a platform that implements C++14 support.
While some types have been broken out into their own headers (e.g. [gsl/span](./include/gsl/span)),
it is simplest to just include [gsl/gsl](./include/gsl/gsl) and gain access to the entire library.
> NOTE: We encourage contributions that improve or refine any of the types in this library as well as ports to
other platforms. Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for more information about contributing.
# Project Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
# Usage of Third Party Libraries
This project makes use of the [Google Test](https://github.com/google/googletest) testing library. Please see the [ThirdPartyNotices.txt](./ThirdPartyNotices.txt) file for details regarding the licensing of Google Test.
# Quick Start
## Supported Compilers
The GSL officially supports the current and previous major release of MSVC, GCC, Clang, and XCode's Apple-Clang.
See our latest test results for the most up-to-date list of supported configurations.
Compiler |Toolset Versions Currently Tested| Build Status
:------- |:--|------------:
XCode |11.4 & 10.3 | [](https://travis-ci.org/Microsoft/GSL)
GCC |9 & 8| [](https://travis-ci.org/Microsoft/GSL)
Clang |11 & 10| [](https://travis-ci.org/Microsoft/GSL)
Visual Studio with MSVC | VS2017 (15.9) & VS2019 (16.4) | [](https://ci.appveyor.com/project/neilmacintosh/GSL)
Visual Studio with LLVM | VS2017 (Clang 9) & VS2019 (Clang 10) | [](https://ci.appveyor.com/project/neilmacintosh/GSL)
Note: For `gsl::byte` to work correctly with Clang and GCC you might have to use the ` -fno-strict-aliasing` compiler option.
---
If you successfully port GSL to another platform, we would love to hear from you!
- Submit an issue specifying the platform and target.
- Consider contributing your changes by filing a pull request with any necessary changes.
- If at all possible, add a CI/CD step and add the button to the table below!
Target | CI/CD Status
:------- | -----------:
iOS | 
Android | 
Note: These CI/CD steps are run with each pull request, however failures in them are non-blocking.
## Building the tests
To build the tests, you will require the following:
* [CMake](http://cmake.org), version 3.1.3 (3.2.3 for AppleClang) or later to be installed and in your PATH.
These steps assume the source code of this repository has been cloned into a directory named `c:\GSL`.
1. Create a directory to contain the build outputs for a particular architecture (we name it c:\GSL\build-x86 in this example).
cd GSL
md build-x86
cd build-x86
2. Configure CMake to use the compiler of your choice (you can see a list by running `cmake --help`).
cmake -G "Visual Studio 15 2017" c:\GSL
3. Build the test suite (in this case, in the Debug configuration, Release is another good choice).
cmake --build . --config Debug
4. Run the test suite.
ctest -C Debug
All tests should pass - indicating your platform is fully supported and you are ready to use the GSL types!
## Building GSL - Using vcpkg
You can download and install GSL using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install ms-gsl
The GSL port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
## Using the libraries
As the types are entirely implemented inline in headers, there are no linking requirements.
You can copy the [gsl](./include/gsl) directory into your source tree so it is available
to your compiler, then include the appropriate headers in your program.
Alternatively set your compiler's *include path* flag to point to the GSL development folder (`c:\GSL\include` in the example above) or installation folder (after running the install). Eg.
MSVC++
/I c:\GSL\include
GCC/clang
-I$HOME/dev/GSL/include
Include the library using:
#include <gsl/gsl>
## Usage in CMake
The library provides a Config file for CMake, once installed it can be found via
find_package(Microsoft.GSL CONFIG)
Which, when successful, will add library target called `Microsoft.GSL::GSL` which you can use via the usual
`target_link_libraries` mechanism.
## Debugging visualization support
For Visual Studio users, the file [GSL.natvis](./GSL.natvis) in the root directory of the repository can be added to your project if you would like more helpful visualization of GSL types in the Visual Studio debugger than would be offered by default.
| 6,291 |
Markdown
| 50.154471 | 332 | 0.750437 |
omniverse-code/kit/gsl/PACKAGE-LICENSES/gsl-LICENSE.md
|
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
This code is licensed under the MIT License (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.
| 1,156 |
Markdown
| 51.590907 | 81 | 0.792388 |
omniverse-code/kit/exts/omni.kit.material.library/docs/index.rst
|
omni.kit.material.library
###########################
Material Library
.. toctree::
:maxdepth: 1
CHANGELOG
Python API Reference
*********************
.. automodule:: omni.kit.material.library
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:imported-members:
:exclude-members: chain
:noindex: omni.usd._impl.utils.PrimCaching
| 383 |
reStructuredText
| 14.359999 | 46 | 0.597911 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/PACKAGE-LICENSES/omni.kit.window.imageviewer-LICENSE.md
|
Copyright (c) 2020, 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.
| 412 |
Markdown
| 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/config/extension.toml
|
[package]
version = "1.0.6"
category = "Internal"
feature = true
title = "Image Viewer"
description="Adds context menu in the Content Browser that allows to view images."
authors = ["NVIDIA"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
readme = "docs/README.md"
[dependencies]
"omni.ui" = {}
"omni.kit.widget.imageview" = {}
"omni.kit.window.content_browser" = { optional=true }
"omni.kit.test" = {}
"omni.usd.libs" = {}
[[python.module]]
name = "omni.kit.window.imageviewer"
# Additional python module with tests, to make them discoverable by test system.
[[python.module]]
name = "omni.kit.window.imageviewer.tests"
[[test]]
args = ["--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false"]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.renderer.capture",
]
pythonTests.unreliable = [
"*test_general" # OM-49017
]
| 902 |
TOML
| 23.405405 | 83 | 0.695122 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer.py
|
# Copyright (c) 2018-2020, 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.widget.imageview as imageview
import omni.ui as ui
from .singleton import singleton
@singleton
class ViewerWindows:
"""This object keeps all the Image Viewper windows"""
def __init__(self):
self.__windows = {}
def open_window(self, filepath: str) -> ui.Window:
"""Open ImageViewer window with the image file opened in it"""
if filepath in self.__windows:
window = self.__windows[filepath]
window.visible = True
else:
window = ImageViewer(filepath)
# When window is closed, remove it from the list
window.set_visibility_changed_fn(lambda _, f=filepath: self.close(f))
self.__windows[filepath] = window
return window
def close(self, filepath):
"""Close and remove spacific window"""
del self.__windows[filepath]
def close_all(self):
"""Close and remove all windows"""
self.__windows = {}
class ImageViewer(ui.Window):
"""The window with Image Viewer"""
def __init__(self, filename: str, **kwargs):
if "width" not in kwargs:
kwargs["width"] = 640
if "height" not in kwargs:
kwargs["height"] = 480
super().__init__(filename, **kwargs)
self.frame.set_style({"Window": {"background_color": 0xFF000000, "border_width": 0}})
self.frame.set_build_fn(self.__build_window)
self.__filename = filename
def __build_window(self):
"""Called to build the widgets of the window"""
# For now it's only one single widget
imageview.ImageView(self.__filename, smooth_zoom=True, style={"ImageView": {"background_color": 0xFF000000}})
def destroy(self):
pass
| 2,181 |
Python
| 33.093749 | 117 | 0.644658 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/__init__.py
|
# Copyright (c) 2018-2020, 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 .imageviewer import ImageViewer
from .imageviewer_extension import ImageViewerExtension
| 526 |
Python
| 46.909087 | 76 | 0.821293 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer_utils.py
|
# Copyright (c) 2018-2020, 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.app
def is_extension_loaded(extansion_name: str) -> bool:
"""
Returns True if the extension with the given name is loaded.
"""
def is_ext(ext_id: str, extension_name: str) -> bool:
id_name = omni.ext.get_extension_name(ext_id)
return id_name == extension_name
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
extensions = ext_manager.get_extensions()
loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None)
return bool(loaded)
| 1,015 |
Python
| 35.285713 | 108 | 0.721182 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/content_menu.py
|
# Copyright (c) 2018-2020, 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 .imageviewer import ViewerWindows
from .imageviewer_utils import is_extension_loaded
def content_available():
"""
Returns True if the extension "omni.kit.window.content_browser" is loaded.
"""
return is_extension_loaded("omni.kit.window.content_browser")
class ContentMenu:
"""
When this object is alive, Content Browser has the additional context menu
with the items that allow to view image files.
"""
def __init__(self, version: int = 2):
if version != 2:
raise RuntimeError("Only version 2 is supported")
content_window = self._get_content_window()
if content_window:
view_menu_name = "Show Image"
self.__view_menu_subscription = content_window.add_file_open_handler(
view_menu_name,
lambda file_path: self._on_show_triggered(view_menu_name, file_path),
self._is_show_visible,
)
else:
self.__view_menu_subscription = None
def _get_content_window(self):
try:
import omni.kit.window.content_browser as content
except ImportError:
return None
return content.get_content_window()
def _is_show_visible(self, content_url):
"""True if we can show the menu item View Image"""
# List of available formats: carb/source/plugins/carb.imaging/Imaging.cpp
return any(
content_url.endswith(f".{ext}")
for ext in ["bmp", "dds", "exr", "gif", "hdr", "jpeg", "jpg", "png", "psd", "svg", "tga"]
)
def _on_show_triggered(self, menu, value):
"""Start watching for the layer and run the editor"""
ViewerWindows().open_window(value)
def destroy(self):
"""Stop all watchers and remove the menu from the content browser"""
if self.__view_menu_subscription:
content_window = self._get_content_window()
if content_window:
content_window.delete_file_open_handler(self.__view_menu_subscription)
self.__view_menu_subscription = None
ViewerWindows().close_all()
| 2,572 |
Python
| 36.289855 | 101 | 0.640747 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer_extension.py
|
# Copyright (c) 2018-2020, 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 .content_menu import content_available
from .content_menu import ContentMenu
class ImageViewerExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
self.__imageviewer = None
self.__extensions_subscription = None # noqa: PLW0238
self.__content_menu = None
def on_startup(self, ext_id):
# Setup a callback when any extension is loaded/unloaded
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
self.__extensions_subscription = ( # noqa: PLW0238
ext_manager.get_change_event_stream().create_subscription_to_pop(
self._on_event, name="omni.kit.window.imageviewer"
)
)
self.__content_menu = None
self._on_event(None)
def _on_event(self, event):
"""Called when any extension is loaded/unloaded"""
if self.__content_menu:
if not content_available():
self.__content_menu.destroy()
self.__content_menu = None
else:
if content_available():
self.__content_menu = ContentMenu()
def on_shutdown(self):
if self.__imageviewer:
self.__imageviewer.destroy()
self.__imageviewer = None
self.__extensions_subscription = None # noqa: PLW0238
if self.__content_menu:
self.__content_menu.destroy()
self.__content_menu = None
| 1,922 |
Python
| 33.963636 | 77 | 0.632154 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/singleton.py
|
# Copyright (c) 2018-2020, 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.
#
def singleton(class_):
"""A singleton decorator"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
| 697 |
Python
| 32.238094 | 76 | 0.725968 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/tests/__init__.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 .imageviewer_test import TestImageViewer
| 474 |
Python
| 46.499995 | 76 | 0.814346 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/tests/imageviewer_test.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 pathlib import Path
from omni.ui.tests.test_base import OmniUiTest
import omni.kit
import omni.ui as ui
from ..imageviewer import ViewerWindows
class TestImageViewer(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute()
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_general(self):
window = await self.create_test_window() # noqa: PLW0612, F841
await omni.kit.app.get_app().next_update_async()
viewer = ViewerWindows().open_window(f"{self._golden_img_dir.joinpath('lenna.png')}")
viewer.flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE
viewer.position_x = 0
viewer.position_y = 0
viewer.width = 256
viewer.height = 256
# One frame to show the window and another to build the frame
# And a dozen frames more to let the asset load
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 1,817 |
Python
| 36.10204 | 110 | 0.693451 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/docs/CHANGELOG.md
|
# Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-06-17
### Changed
- Properly linted
## [1.0.5] - 2021-09-20
### Changed
- Fixed unittest path to golden image.
## [1.0.4] - 2021-08-18
### Changed
- Fixed console_browser leak
## [1.0.3] - 2020-12-08
### Added
- Description, preview image and icon
### Changed
- Fixed crash on exit
## [1.0.2] - 2020-11-25
### Changed
- Pasting an image URL into the content window's browser bar or double clicking opens the file.
## [1.0.1] - 2020-11-12
### Changed
- Fixed exception in Create
## [1.0.0] - 2020-07-19
### Added
- Adds context menu in the Content Browser
| 674 |
Markdown
| 18.852941 | 95 | 0.655786 |
omniverse-code/kit/exts/omni.kit.window.imageviewer/docs/README.md
|
# Image Viewer [omni.kit.window.imageviewer]
It's The extension that can display stored graphical images in a new window.
It can handle various graphics file formats.
| 168 |
Markdown
| 32.799993 | 76 | 0.797619 |
omniverse-code/kit/exts/omni.kit.window.audiorecorder/PACKAGE-LICENSES/omni.kit.window.audiorecorder-LICENSE.md
|
Copyright (c) 2020, 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.
| 412 |
Markdown
| 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.audiorecorder/config/extension.toml
|
[package]
title = "Kit Audio Recorder Window"
category = "Audio"
version = "1.0.1"
description = "A simple audio recorder window"
detailedDescription = """This adds a window for recording audio to file from an audio
capture device.
"""
preview_image = "data/preview.png"
authors = ["NVIDIA"]
keywords = ["audio", "capture", "recording"]
[dependencies]
"omni.kit.audiodeviceenum" = {}
"omni.audiorecorder" = {}
"omni.ui" = {}
"omni.kit.window.content_browser" = { optional=true }
"omni.kit.window.filepicker" = {}
"omni.kit.pip_archive" = {}
"omni.usd" = {}
"omni.kit.menu.utils" = {}
[python.pipapi]
requirements = ["numpy"]
[[python.module]]
name = "omni.kit.window.audiorecorder"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window",
# Use the null device backend.
# We need this to ensure the captured data is consistent.
# We could use the capture test patterns mode, but there's no way to
# synchronize the image capture with the audio capture right now, so we'll
# have to just capture silence.
"--/audio/deviceBackend=null",
# needed for the UI test stuff
"--/app/menu/legacy_mode=false",
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"carb.audio",
]
stdoutFailPatterns.exclude = [
"*" # I don't want these but OmniUiTest forces me to use them
]
| 1,690 |
TOML
| 25.841269 | 94 | 0.666864 |
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/__init__.py
|
from .audio_recorder_window import *
| 37 |
Python
| 17.999991 | 36 | 0.783784 |
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/audio_recorder_window.py
|
# Copyright (c) 2020, 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 carb.audio
import omni.audiorecorder
import omni.kit.ui
import omni.ui
import threading
import time
import re
import asyncio
from typing import Callable
from omni.kit.window.filepicker import FilePickerDialog
class AudioRecorderWindowExtension(omni.ext.IExt):
"""Audio Recorder Window Extension"""
class ComboModel(omni.ui.AbstractItemModel):
class ComboItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
def __init__(self):
super().__init__()
self._options = [
["16 bit PCM", carb.audio.SampleFormat.PCM16],
["24 bit PCM", carb.audio.SampleFormat.PCM24],
["32 bit PCM", carb.audio.SampleFormat.PCM32],
["float PCM", carb.audio.SampleFormat.PCM_FLOAT],
["Vorbis", carb.audio.SampleFormat.VORBIS],
["FLAC", carb.audio.SampleFormat.FLAC],
["Opus", carb.audio.SampleFormat.OPUS],
]
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._items = [AudioRecorderWindowExtension.ComboModel.ComboItem(text) for (text, value) in self._options]
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def set_value(self, value):
for i in range(0, len(self._options)):
if self._options[i][1] == value:
self._current_index.as_int = i
break
def get_value(self):
return self._options[self._current_index.as_int][1]
class FieldModel(omni.ui.AbstractValueModel):
def __init__(self):
super(AudioRecorderWindowExtension.FieldModel, self).__init__()
self._value = ""
def get_value_as_string(self):
return self._value
def begin_edit(self):
pass
def set_value(self, value):
self._value = value
self._value_changed()
def end_edit(self):
pass
def get_value(self):
return self._value
def _choose_file_clicked(self): # pragma: no cover
dialog = FilePickerDialog(
"Select File",
apply_button_label="Select",
click_apply_handler=lambda filename, dirname: self._on_file_pick(dialog, filename, dirname),
)
dialog.show()
def _on_file_pick(self, dialog: FilePickerDialog, filename: str, dirname: str): # pragma: no cover
path = ""
if dirname:
path = f"{dirname}/{filename}"
elif filename:
path = filename
dialog.hide()
self._file_field.model.set_value(path)
def _menu_callback(self, a, b):
self._window.visible = not self._window.visible
def _read_callback(self, data): # pragma: no cover
self._display_buffer[self._display_buffer_index] = data
self._display_buffer_index = (self._display_buffer_index + 1) % self._display_len
buf = []
for i in range(self._display_len):
buf += self._display_buffer[(self._display_buffer_index + i) % self._display_len]
width = 512
height = 128
img = omni.audiorecorder.draw_waveform_from_blob_int16(
input=buf,
channels=1,
width=width,
height=height,
fg_color=[0.89, 0.54, 0.14, 1.0],
bg_color=[0.0, 0.0, 0.0, 0.0],
)
self._waveform_image_provider.set_bytes_data(img, [width, height])
def _close_error_window(self):
self._error_window.visible = False
def _record_clicked(self):
if self._recording:
self._record_button.set_style({"image_url": "resources/glyphs/audio_record.svg"})
self._recorder.stop_recording()
self._recording = False
else:
result = self._recorder.begin_recording_int16(
filename=self._file_field_model.get_value(),
callback=self._read_callback,
output_format=self._format_model.get_value(),
buffer_length=200,
period=25,
length_type=carb.audio.UnitType.MILLISECONDS,
)
if result:
self._record_button.set_style({"image_url": "resources/glyphs/timeline_stop.svg"})
self._recording = True
else: # pragma: no cover
self._error_window = omni.ui.Window(
"Audio Recorder Error", width=400, height=0, flags=omni.ui.WINDOW_FLAGS_NO_DOCKING
)
with self._error_window.frame:
with omni.ui.VStack():
with omni.ui.HStack():
omni.ui.Spacer()
self._error_window_label = omni.ui.Label(
"Failed to start recording. The file path may be incorrect or the device may be inaccessible.",
word_wrap=True,
width=380,
alignment=omni.ui.Alignment.CENTER,
)
omni.ui.Spacer()
with omni.ui.HStack():
omni.ui.Spacer()
self._error_window_ok_button = omni.ui.Button(
width=64, height=32, clicked_fn=self._close_error_window, text="ok"
)
omni.ui.Spacer()
def _stop_clicked(self):
pass
def _create_tooltip(self, text):
"""Create a tooltip in a fixed style"""
with omni.ui.VStack(width=400):
omni.ui.Label(text, word_wrap=True)
def on_startup(self):
self._display_len = 8
self._display_buffer = [[0] for i in range(self._display_len)]
self._display_buffer_index = 0
# self._ticker_pos = 0;
self._recording = False
self._recorder = omni.audiorecorder.create_audio_recorder()
self._window = omni.ui.Window("Audio Recorder", width=600, height=240)
with self._window.frame:
with omni.ui.VStack(height=0, spacing=8):
# file dialogue
with omni.ui.HStack():
omni.ui.Button(
width=32,
height=32,
clicked_fn=self._choose_file_clicked,
style={"image_url": "resources/glyphs/folder.svg"},
)
self._file_field_model = AudioRecorderWindowExtension.FieldModel()
self._file_field = omni.ui.StringField(self._file_field_model, height=32)
# waveform
with omni.ui.HStack(height=128):
omni.ui.Spacer()
self._waveform_image_provider = omni.ui.ByteImageProvider()
self._waveform_image = omni.ui.ImageWithProvider(
self._waveform_image_provider,
width=omni.ui.Percent(95),
height=omni.ui.Percent(100),
fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH,
)
omni.ui.Spacer()
# buttons
with omni.ui.HStack():
with omni.ui.ZStack():
omni.ui.Spacer()
self._anim_label = omni.ui.Label("", alignment=omni.ui.Alignment.CENTER)
with omni.ui.VStack():
omni.ui.Spacer()
self._format_model = AudioRecorderWindowExtension.ComboModel()
self._format = omni.ui.ComboBox(
self._format_model,
height=0,
tooltip_fn=lambda: self._create_tooltip(
"The format for the output file."
+ "The PCM formats will output as a WAVE file (.wav)."
+ "FLAC will output as a FLAC file (.flac)."
+ "Vorbis and Opus will output as an Ogg file (.ogg/.oga)."
),
)
omni.ui.Spacer()
self._record_button = omni.ui.Button(
width=32,
height=32,
clicked_fn=self._record_clicked,
style={"image_url": "resources/glyphs/audio_record.svg"},
)
omni.ui.Spacer()
# add a callback to open the window
self._menuEntry = omni.kit.ui.get_editor_menu().add_item("Window/Audio Recorder", self._menu_callback)
self._window.visible = False
def on_shutdown(self): # pragma: no cover
self._recorder = None
self._window = None
self._menuEntry = None
| 9,750 |
Python
| 38.477733 | 127 | 0.521436 |
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/tests/__init__.py
|
from .test_audiorecorder_window import * # pragma: no cover
| 61 |
Python
| 29.999985 | 60 | 0.754098 |
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/tests/test_audiorecorder_window.py
|
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.test
import omni.ui as ui
import omni.usd
import omni.timeline
import carb.tokens
import carb.audio
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
#from omni.ui_query import OmniUIQuery
import pathlib
import asyncio
import tempfile
import os
import platform
class TestAudioRecorderWindow(OmniUiTest): # pragma: no cover
async def _dock_window(self, win):
await self.docked_test_window(
window=win._window,
width=600,
height=240)
#def _dump_ui_tree(self, root):
# print("DUMP UI TREE START")
# #windows = omni.ui.Workspace.get_windows()
# #children = [windows[0].frame]
# children = [root.frame]
# print(str(dir(root.frame)))
# def recurse(children, path=""):
# for c in children:
# name = path + "/" + type(c).__name__
# print(name)
# if isinstance(c, omni.ui.ComboBox):
# print(str(dir(c)))
# recurse(omni.ui.Inspector.get_children(c), name)
# recurse(children)
# print("DUMP UI TREE END")
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.audiorecorder}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._golden_img_dir = self._test_path.joinpath("golden")
# open the dropdown
window_menu = omni.kit.ui_test.get_menubar().find_menu("Window")
self.assertIsNotNone(window_menu)
await window_menu.click()
# click the Audio Recorder entry to open it
rec_menu = omni.kit.ui_test.get_menubar().find_menu("Audio Recorder")
self.assertIsNotNone(rec_menu)
await rec_menu.click()
#self._dump_ui_tree(omni.kit.ui_test.find("Audio Recorder").window)
# After running each test
async def tearDown(self):
await super().tearDown()
self._rec = None
async def _test_just_opened(self):
win = omni.kit.ui_test.find("Audio Recorder")
self.assertIsNotNone(win)
await self._dock_window(win)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_just_opened.png")
async def _test_recording(self):
# wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt
await ui_test.human_delay(50)
iface = carb.audio.acquire_data_interface()
self.assertIsNotNone(iface)
win = omni.kit.ui_test.find("Audio Recorder")
self.assertIsNotNone(win)
file_name_textbox = win.find("**/StringField[*]")
self.assertIsNotNone(file_name_textbox)
record_button = win.find("**/HStack[2]/Button[0]")
self.assertIsNotNone(record_button)
with tempfile.TemporaryDirectory() as temp_dir:
path = os.path.join(temp_dir, "test.wav")
# type our file path into the textbox
await file_name_textbox.click()
await file_name_textbox.input(str(path))
# the user hit the record button
await record_button.click()
await asyncio.sleep(1.0)
# change the text in the textbox so we'll have something constant
# for the image comparison
await file_name_textbox.input("soundstorm_song.wav")
await self._dock_window(win)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_recording.png")
# wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt
await ui_test.human_delay(50)
# grab these again just in case window docking broke it
win = omni.kit.ui_test.find("Audio Recorder")
self.assertIsNotNone(win)
record_button = win.find("**/HStack[2]/Button[0]")
self.assertIsNotNone(record_button)
# the user hit the stop button
await record_button.click()
await self._dock_window(win)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_stopped.png")
# wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt
await ui_test.human_delay(50)
# grab these again just in case window docking broke it
win = omni.kit.ui_test.find("Audio Recorder")
self.assertIsNotNone(win)
file_name_textbox = win.find("**/StringField[*]")
self.assertIsNotNone(file_name_textbox)
record_button = win.find("**/HStack[2]/Button[0]")
self.assertIsNotNone(record_button)
format_combobox = win.find("**/ComboBox[*]")
self.assertIsNotNone(format_combobox)
# analyze the data
sound = iface.create_sound_from_file(path, streaming=True)
self.assertIsNotNone(sound)
fmt = sound.get_format()
self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM16)
pcm = sound.get_buffer_as_int16()
for i in range(len(pcm)):
self.assertEqual(pcm[i], 0);
sound = None # close it
# try again with a different format
# FIXME: We should not be manipulating the model directly, but ui_test
# doesn't have a way to find any of the box item to click on,
# and ComboBoxes don't respond to keyboard input either.
format_combobox.model.set_value(carb.audio.SampleFormat.VORBIS)
path2 = os.path.join(temp_dir, "test.oga")
await file_name_textbox.input(str(path2))
# the user hit the record button
await record_button.click()
await asyncio.sleep(1.0)
# the user hit the stop button
await record_button.click()
# analyze the data
sound = iface.create_sound_from_file(str(path2), streaming=True)
self.assertIsNotNone(sound)
fmt = sound.get_format()
self.assertEqual(fmt.format, carb.audio.SampleFormat.VORBIS)
pcm = sound.get_buffer_as_int16()
for i in range(len(pcm)):
self.assertEqual(pcm[i], 0);
sound = None # close it
async def test_all(self):
await self._test_just_opened()
await self._test_recording()
| 7,060 |
Python
| 34.129353 | 111 | 0.616856 |
omniverse-code/kit/exts/omni.command.usd/PACKAGE-LICENSES/omni.command.usd-LICENSE.md
|
Copyright (c) 2020, 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.
| 412 |
Markdown
| 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.command.usd/config/extension.toml
|
[package]
title = "Command USD"
description = "Usefull command for USD."
category = "Internal"
version = "1.0.2"
readme = "docs/README.md"
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[[python.module]]
name = "omni.command.usd"
[dependencies]
"omni.kit.commands" = {}
"omni.usd" = {}
| 329 |
TOML
| 18.411764 | 40 | 0.68693 |
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/__init__.py
|
from .commands.usd_commands import *
| 37 |
Python
| 17.999991 | 36 | 0.783784 |
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/__init__.py
|
from .usd_commands import *
from .parenting_commands import *
| 62 |
Python
| 19.999993 | 33 | 0.774194 |
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/parenting_commands.py
|
import omni.kit.commands
import omni.usd
from typing import List
from pxr import Sdf
class ParentPrimsCommand(omni.kit.commands.Command):
def __init__(
self,
parent_path: str,
child_paths: List[str],
on_move_fn: callable = None,
keep_world_transform: bool = True
):
"""
Move prims into children of "parent" primitives undoable **Command**.
Args:
parent_path: prim path to become parent of child_paths
child_paths: prim paths to become children of parent_prim
keep_world_transform: If it needs to keep the world transform after parenting.
"""
self._parent_path = parent_path
self._child_paths = child_paths.copy()
self._on_move_fn = on_move_fn
self._keep_world_transform = keep_world_transform
def do(self):
with omni.kit.undo.group():
for path in self._child_paths:
path_to = self._parent_path + "/" + Sdf.Path(path).name
omni.kit.commands.execute(
"MovePrim",
path_from=path,
path_to=path_to,
on_move_fn=self._on_move_fn,
destructive=False,
keep_world_transform=self._keep_world_transform
)
def undo(self):
pass
class UnparentPrimsCommand(omni.kit.commands.Command):
def __init__(
self,
paths: List[str],
on_move_fn: callable = None,
keep_world_transform: bool = True
):
"""
Move prims into "/" primitives undoable **Command**.
Args:
paths: prim path to become parent of child_paths
keep_world_transform: If it needs to keep the world transform after parenting.
"""
self._paths = paths.copy()
self._on_move_fn = on_move_fn
self._keep_world_transform = keep_world_transform
def do(self):
with omni.kit.undo.group():
for path in self._paths:
path_to = "/" + Sdf.Path(path).name
omni.kit.commands.execute(
"MovePrim",
path_from=path,
path_to=path_to,
on_move_fn=self._on_move_fn,
destructive=False,
keep_world_transform=self._keep_world_transform
)
def undo(self):
pass
omni.kit.commands.register_all_commands_in_module(__name__)
| 2,518 |
Python
| 29.349397 | 90 | 0.53892 |
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/usd_commands.py
|
import omni.kit.commands
import omni.usd
from typing import List
from pxr import Sdf
class TogglePayLoadLoadSelectedPrimsCommand(omni.kit.commands.Command):
def __init__(self, selected_paths: List[str]):
"""
Toggles the load/unload payload of the selected primitives undoable **Command**.
Args:
selected_paths: Old selected prim paths.
"""
self._stage = omni.usd.get_context().get_stage()
self._selected_paths = selected_paths.copy()
def _toggle_load(self):
for selected_path in self._selected_paths:
selected_prim = self._stage.GetPrimAtPath(selected_path)
if selected_prim.IsLoaded():
selected_prim.Unload()
else:
selected_prim.Load()
def do(self):
self._toggle_load()
def undo(self):
self._toggle_load()
class SetPayLoadLoadSelectedPrimsCommand(omni.kit.commands.Command):
def __init__(self, selected_paths: List[str], value: bool):
"""
Set the load/unload payload of the selected primitives undoable **Command**.
Args:
selected_paths: Old selected prim paths.
value: True = load, False = unload
"""
self._stage = omni.usd.get_context().get_stage()
self._selected_paths = selected_paths.copy()
self._processed_path = set()
self._value = value
self._is_undo = False
def _set_load(self):
if self._is_undo:
paths = self._processed_path
else:
paths = self._selected_paths
for selected_path in paths:
selected_prim = self._stage.GetPrimAtPath(selected_path)
if (selected_prim.IsLoaded() and self._value) or (not selected_prim.IsLoaded() and not self._value):
if selected_path in self._processed_path:
self._processed_path.remove(selected_path)
continue
if self._value:
selected_prim.Load()
else:
selected_prim.Unload()
self._processed_path.add(selected_path)
def do(self):
self._set_load()
def undo(self):
self._is_undo = True
self._value = not self._value
self._set_load()
self._value = not self._value
self._processed_path = set()
self._is_undo = False
omni.kit.commands.register_all_commands_in_module(__name__)
| 2,457 |
Python
| 29.725 | 112 | 0.582825 |
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/tests/__init__.py
|
from .test_command_usd import *
| 32 |
Python
| 15.499992 | 31 | 0.75 |
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/tests/test_command_usd.py
|
import carb
import omni.kit.test
import omni.kit.undo
import omni.kit.commands
import omni.usd
from pxr import Sdf, Usd
def get_stage_default_prim_path(stage):
if stage.HasDefaultPrim():
return stage.GetDefaultPrim().GetPath()
else:
return Sdf.Path.absoluteRootPath
class TestCommandUsd(omni.kit.test.AsyncTestCase):
async def test_toggle_payload_selected(self):
carb.log_info("Test TogglePayLoadLoadSelectedPrimsCommand")
await omni.usd.get_context().new_stage_async()
usd_context = omni.usd.get_context()
selection = usd_context.get_selection()
stage = usd_context.get_stage()
default_prim_path = get_stage_default_prim_path(stage)
payload1 = Usd.Stage.CreateInMemory("payload1.usd")
payload1.DefinePrim("/payload1/scope1", "Xform")
payload1.DefinePrim("/payload1/scope1/xform", "Cube")
payload2 = Usd.Stage.CreateInMemory("payload2.usd")
payload2.DefinePrim("/payload2/scope2", "Xform")
payload2.DefinePrim("/payload2/scope2/xform", "Cube")
payload3 = Usd.Stage.CreateInMemory("payload3.usd")
payload3.DefinePrim("/payload3/scope3", "Xform")
payload3.DefinePrim("/payload3/scope3/xform", "Cube")
payload4 = Usd.Stage.CreateInMemory("payload4.usd")
payload4.DefinePrim("/payload4/scope4", "Xform")
payload4.DefinePrim("/payload4/scope4/xform", "Cube")
ps1 = stage.DefinePrim(default_prim_path.AppendChild("payload1"), "Xform")
ps1.GetPayloads().AddPayload(
Sdf.Payload(payload1.GetRootLayer().identifier, "/payload1"))
ps2 = stage.DefinePrim(default_prim_path.AppendChild("payload2"), "Xform")
ps2.GetPayloads().AddPayload(
Sdf.Payload(payload2.GetRootLayer().identifier, "/payload2"))
ps3 = stage.DefinePrim(default_prim_path.AppendChild("payload3"), "Xform")
ps3.GetPayloads().AddPayload(
Sdf.Payload(payload3.GetRootLayer().identifier, "/payload3"))
ps4 = stage.DefinePrim(ps3.GetPath().AppendChild("payload4"), "Xform")
ps4.GetPayloads().AddPayload(
Sdf.Payload(payload4.GetRootLayer().identifier, "/payload4"))
# unload everything
stage.Unload()
self.assertTrue(not ps1.IsLoaded())
self.assertTrue(not ps2.IsLoaded())
self.assertTrue(not ps3.IsLoaded())
self.assertTrue(not ps4.IsLoaded())
# if nothing selected, payload state should not change.
selection.clear_selected_prim_paths()
paths = selection.get_selected_prim_paths()
omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths)
self.assertTrue(not ps1.IsLoaded())
self.assertTrue(not ps2.IsLoaded())
self.assertTrue(not ps3.IsLoaded())
self.assertTrue(not ps4.IsLoaded())
# load payload1
selection.set_selected_prim_paths(
[
ps1.GetPath().pathString
],
False,
)
paths = selection.get_selected_prim_paths()
omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths)
self.assertTrue(ps1.IsLoaded())
# unload payload1
omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths)
self.assertTrue(not ps1.IsLoaded())
# load payload1, 2 and 3. 4 will load
selection.set_selected_prim_paths(
[
ps1.GetPath().pathString,
ps2.GetPath().pathString,
ps3.GetPath().pathString,
],
False,
)
paths = selection.get_selected_prim_paths()
omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths)
self.assertTrue(ps1.IsLoaded())
self.assertTrue(ps2.IsLoaded())
self.assertTrue(ps3.IsLoaded())
self.assertTrue(ps4.IsLoaded())
# unload 4
selection.set_selected_prim_paths(
[
ps4.GetPath().pathString
],
False,
)
paths = selection.get_selected_prim_paths()
omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths)
self.assertTrue(not ps4.IsLoaded())
# undo
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded())
# redo
omni.kit.undo.redo()
self.assertTrue(not ps4.IsLoaded())
async def test_set_payload_selected(self):
carb.log_info("Test SetPayLoadLoadSelectedPrimsCommand")
await omni.usd.get_context().new_stage_async()
usd_context = omni.usd.get_context()
selection = usd_context.get_selection()
stage = usd_context.get_stage()
default_prim_path = get_stage_default_prim_path(stage)
payload1 = Usd.Stage.CreateInMemory("payload1.usd")
payload1.DefinePrim("/payload1/scope1", "Xform")
payload1.DefinePrim("/payload1/scope1/xform", "Cube")
payload2 = Usd.Stage.CreateInMemory("payload2.usd")
payload2.DefinePrim("/payload2/scope2", "Xform")
payload2.DefinePrim("/payload2/scope2/xform", "Cube")
payload3 = Usd.Stage.CreateInMemory("payload3.usd")
payload3.DefinePrim("/payload3/scope3", "Xform")
payload3.DefinePrim("/payload3/scope3/xform", "Cube")
payload4 = Usd.Stage.CreateInMemory("payload4.usd")
payload4.DefinePrim("/payload4/scope4", "Xform")
payload4.DefinePrim("/payload4/scope4/xform", "Cube")
ps1 = stage.DefinePrim(default_prim_path.AppendChild("payload1"), "Xform")
ps1.GetPayloads().AddPayload(
Sdf.Payload(payload1.GetRootLayer().identifier, "/payload1"))
ps2 = stage.DefinePrim(default_prim_path.AppendChild("payload2"), "Xform")
ps2.GetPayloads().AddPayload(
Sdf.Payload(payload2.GetRootLayer().identifier, "/payload2"))
ps3 = stage.DefinePrim(default_prim_path.AppendChild("payload3"), "Xform")
ps3.GetPayloads().AddPayload(
Sdf.Payload(payload3.GetRootLayer().identifier, "/payload3"))
ps4 = stage.DefinePrim(ps3.GetPath().AppendChild("payload4"), "Xform")
ps4.GetPayloads().AddPayload(
Sdf.Payload(payload4.GetRootLayer().identifier, "/payload4"))
# unload everything
stage.Unload()
self.assertTrue(not ps1.IsLoaded())
self.assertTrue(not ps2.IsLoaded())
self.assertTrue(not ps3.IsLoaded())
self.assertTrue(not ps4.IsLoaded())
# if nothing selected, payload state should not change.
selection.clear_selected_prim_paths()
paths = selection.get_selected_prim_paths()
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True)
self.assertTrue(not ps1.IsLoaded())
self.assertTrue(not ps2.IsLoaded())
self.assertTrue(not ps3.IsLoaded())
self.assertTrue(not ps4.IsLoaded())
# load payload1
selection.set_selected_prim_paths(
[
ps1.GetPath().pathString
],
False,
)
paths = selection.get_selected_prim_paths()
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True)
self.assertTrue(ps1.IsLoaded())
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True)
self.assertTrue(ps1.IsLoaded())
# unload payload1
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False)
self.assertTrue(not ps1.IsLoaded())
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False)
self.assertTrue(not ps1.IsLoaded())
# load payload1, 2 and 3. 4 will load
selection.set_selected_prim_paths(
[
ps1.GetPath().pathString,
ps2.GetPath().pathString,
ps3.GetPath().pathString,
],
False,
)
paths = selection.get_selected_prim_paths()
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True)
self.assertTrue(ps1.IsLoaded())
self.assertTrue(ps2.IsLoaded())
self.assertTrue(ps3.IsLoaded())
self.assertTrue(ps4.IsLoaded())
selection.set_selected_prim_paths(
[
ps4.GetPath().pathString
],
False,
)
paths = selection.get_selected_prim_paths()
# reload 4
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True)
self.assertTrue(ps4.IsLoaded())
# unload 4
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False)
self.assertTrue(not ps4.IsLoaded())
# undo
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded())
# redo
omni.kit.undo.redo()
self.assertTrue(not ps4.IsLoaded())
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False)
self.assertTrue(not ps4.IsLoaded())
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False)
self.assertTrue(not ps4.IsLoaded())
omni.kit.undo.undo()
self.assertTrue(not ps4.IsLoaded())
omni.kit.undo.redo()
self.assertTrue(not ps4.IsLoaded())
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # -1
self.assertTrue(ps4.IsLoaded())
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 0
self.assertTrue(ps4.IsLoaded())
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded())
omni.kit.undo.redo()
self.assertTrue(ps4.IsLoaded())
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) # 1
self.assertTrue(not ps4.IsLoaded()) # 1
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded()) # 0
omni.kit.undo.redo()
self.assertTrue(not ps4.IsLoaded()) # 1
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded()) # 0
# triple undo
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 2
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 3
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) # 4
omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 5
self.assertTrue(ps4.IsLoaded()) # 5
omni.kit.undo.undo()
self.assertTrue(not ps4.IsLoaded()) # 4
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded()) # 3
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded()) # 2
# more undo
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded()) # 0
omni.kit.undo.undo()
self.assertTrue(ps4.IsLoaded()) # -1
| 11,219 |
Python
| 39.215054 | 104 | 0.635618 |
omniverse-code/kit/exts/omni.command.usd/docs/CHANGELOG.md
|
## [1.0.2] - 2022-11-10
### Removed
- Removed dependency on omni.kit.test
## [1.0.1] - 2021-03-15
### Changed
- Added "ParentPrimsCommand" and "UnparentPrimsCommand"
## [0.1.0] - 2021-02-17
### Changed
- Add "TogglePayLoadLoadSelectedPrimsCommand" and "SetPayLoadLoadSelectedPrimsCommand"
| 292 |
Markdown
| 21.53846 | 86 | 0.708904 |
omniverse-code/kit/exts/omni.command.usd/docs/README.md
|
# Command USD [omni.command.usd]
Usefull command for USD.
| 58 |
Markdown
| 18.66666 | 32 | 0.758621 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/style.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.
#
__all__ = ["welcome_widget_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.welcome_widget_attribute_bg = cl("#1f2124")
cl.welcome_widget_attribute_fg = cl("#0f1115")
cl.welcome_widget_hovered = cl("#FFFFFF")
cl.welcome_widget_text = cl("#CCCCCC")
fl.welcome_widget_attr_hspacing = 10
fl.welcome_widget_attr_spacing = 1
fl.welcome_widget_group_spacing = 2
url.welcome_widget_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg"
url.welcome_widget_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg"
# The main style dict
welcome_widget_style = {
"Label::attribute_name": {
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl.welcome_widget_attr_spacing,
"margin_width": fl.welcome_widget_attr_hspacing,
},
"Label::title": {"alignment": ui.Alignment.CENTER, "color": cl.welcome_widget_text, "font_size": 30},
"Label::attribute_name:hovered": {"color": cl.welcome_widget_hovered},
"Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER},
"Slider::attribute_int:hovered": {"color": cl.welcome_widget_hovered},
"Slider": {
"background_color": cl.welcome_widget_attribute_bg,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::attribute_float": {
"draw_mode": ui.SliderDrawMode.FILLED,
"secondary_color": cl.welcome_widget_attribute_fg,
},
"Slider::attribute_float:hovered": {"color": cl.welcome_widget_hovered},
"Slider::attribute_vector:hovered": {"color": cl.welcome_widget_hovered},
"Slider::attribute_color:hovered": {"color": cl.welcome_widget_hovered},
"CollapsableFrame::group": {"margin_height": fl.welcome_widget_group_spacing},
"Image::collapsable_opened": {"color": cl.welcome_widget_text, "image_url": url.welcome_widget_icon_opened},
"Image::collapsable_closed": {"color": cl.welcome_widget_text, "image_url": url.welcome_widget_icon_closed},
}
| 2,636 |
Python
| 43.694915 | 112 | 0.715478 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/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.
#
__all__ = ["WelcomeWindowExtension"]
import asyncio
import carb
import omni.ext
import omni.ui as ui
from typing import Optional
class WelcomeWindowExtension(omni.ext.IExt):
"""The entry point for Welcome Window"""
WINDOW_NAME = "Welcome Window"
# MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self):
self.__window: Optional["WelcomeWindow"] = None
self.__widget: Optional["WelcomeWidget"] = None
self.__render_loading: Optional["ViewportReady"] = None
self.show_welcome(True)
def on_shutdown(self):
self._menu = None
if self.__window:
self.__window.destroy()
self.__window = None
if self.__widget:
self.__widget.destroy()
self.__widget = None
def show_welcome(self, visible: bool):
in_viewport = carb.settings.get_settings().get("/exts/omni.kit.window.welcome/embedInViewport")
if in_viewport and not self.__window:
self.__show_widget(visible)
else:
self.__show_window(visible)
if not visible and self.__render_loading:
self.__render_loading = None
def __get_buttons(self) -> dict:
return {
"Create Empty Scene": self.__create_empty_scene,
"Open Last Saved Scene": None,
"Browse Scenes": None
}
def __destroy_object(self, object):
# Hide it immediately
object.visible = False
# And destroy it in the future
async def destroy_object(object):
await omni.kit.app.get_app().next_update_async()
object.destroy()
asyncio.ensure_future(destroy_object(object))
def __show_window(self, visible: bool):
if visible and self.__window is None:
from .window import WelcomeWindow
self.__window = WelcomeWindow(WelcomeWindowExtension.WINDOW_NAME, width=500, height=300, buttons=self.__get_buttons())
elif self.__window and not visible:
self.__destroy_object(self.__window)
self.__window = None
elif self.__window:
self.__window.visible = True
def __show_widget(self, visible: bool):
if visible and self.__widget is None:
async def add_to_viewport():
try:
from omni.kit.viewport.utility import get_active_viewport_window
from .widget import WelcomeWidget
viewport_window = get_active_viewport_window()
with viewport_window.get_frame("omni.kit.window.welcome"):
self.__widget = WelcomeWidget(self.__get_buttons(), add_background=True)
except (ImportError, AttributeError):
# Fallback to Welcome window
self.__show_window(visible)
asyncio.ensure_future(add_to_viewport())
elif self.__widget and not visible:
self.__destroy_object(self.__widget)
self.__widget = None
elif self.__widget:
self.__widget.visible = True
def __button_clicked(self):
self.show_welcome(False)
def __create_empty_scene(self, renderer: Optional[str] = None):
self.__button_clicked()
settings = carb.settings.get_settings()
ext_manager = omni.kit.app.get_app().get_extension_manager()
if renderer is None:
renderer = settings.get("/exts/omni.app.setup/backgroundRendererLoad/renderer")
if not renderer:
return
ext_manager.set_extension_enabled_immediate("omni.kit.viewport.bundle", True)
if renderer == "iray":
ext_manager.set_extension_enabled_immediate(f"omni.hydra.rtx", True)
ext_manager.set_extension_enabled_immediate(f"omni.hydra.{renderer}", True)
else:
ext_manager.set_extension_enabled_immediate(f"omni.kit.viewport.{renderer}", True)
async def _new_stage_async():
if settings.get("/exts/omni.kit.window.welcome/showRenderLoading"):
from .render_loading import start_render_loading_ui
self.__render_loading = start_render_loading_ui(ext_manager, renderer)
await omni.kit.app.get_app().next_update_async()
import omni.kit.stage_templates as stage_templates
stage_templates.new_stage(template=None)
await omni.kit.app.get_app().next_update_async()
from omni.kit.viewport.utility import get_active_viewport
get_active_viewport().set_hd_engine(renderer)
asyncio.ensure_future(_new_stage_async())
| 5,066 |
Python
| 37.097744 | 130 | 0.617055 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/__init__.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.
#
__all__ = ["WelcomeWindowExtension"]
from .extension import WelcomeWindowExtension
| 512 |
Python
| 41.749997 | 76 | 0.804687 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/render_loading.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.
#
__all__ = ["start_render_loading_ui"]
def start_render_loading_ui(ext_manager, renderer: str):
import carb
import time
time_begin = time.time()
carb.settings.get_settings().set("/exts/omni.kit.viewport.ready/startup/enabled", False)
ext_manager.set_extension_enabled_immediate("omni.kit.viewport.ready", True)
from omni.kit.viewport.ready.viewport_ready import ViewportReady, ViewportReadyDelegate
class TimerDelegate(ViewportReadyDelegate):
def __init__(self, time_begin):
super().__init__()
self.__timer_start = time.time()
self.__vp_ready_cost = self.__timer_start - time_begin
@property
def font_size(self) -> float:
return 48
@property
def message(self) -> str:
rtx_mode = {
"RaytracedLighting": "Real-Time",
"PathTracing": "Interactive (Path Tracing)",
"LightspeedAperture": "Aperture (Game Path Tracer)"
}.get(carb.settings.get_settings().get("/rtx/rendermode"), "Real-Time")
renderer_label = {
"rtx": f"RTX - {rtx_mode}",
"iray": "RTX - Accurate (Iray)",
"pxr": "Pixar Storm",
"index": "RTX - Scientific (IndeX)"
}.get(renderer, renderer)
return f"Waiting for {renderer_label} to start"
def on_complete(self):
rtx_load_time = time.time() - self.__timer_start
super().on_complete()
print(f"Time until pixel: {rtx_load_time}")
print(f"ViewportReady cost: {self.__vp_ready_cost}")
return ViewportReady(TimerDelegate(time_begin))
| 2,121 |
Python
| 37.581817 | 92 | 0.619991 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/widget.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.
#
__all__ = ["WelcomeWidget"]
import carb
import omni.kit.app
import omni.ui as ui
from typing import Callable, Optional
class WelcomeWidget():
"""The class that represents the window"""
def __init__(self, buttons: dict, style: Optional[dict] = None, button_size: Optional[tuple] = None, add_background: bool = False):
if style is None:
from .style import welcome_widget_style
style = welcome_widget_style
if button_size is None:
button_size = (150, 100)
self.__add_background = add_background
# Save the button_size for later use
self.__buttons = buttons
self.__button_size = button_size
# Create the top-level ui.Frame
self.__frame: ui.Frame = ui.Frame()
# Apply the style to all the widgets of this window
self.__frame.style = style
# Set the function that is called to build widgets when the window is visible
self.__frame.set_build_fn(self.create_ui)
def destroy(self):
# It will destroy all the children
if self.__frame:
self.__frame.destroy()
self.__frame = None
def create_label(self):
ui.Label("Select Stage", name="title")
def create_button(self, label: str, width: float, height: float, clicked_fn: Callable):
ui.Button(label, width=width, height=height, clicked_fn=clicked_fn)
def create_buttons(self, width: float, height: float):
for label, clicked_fn in self.__buttons.items():
self.create_button(label, width=width, height=height, clicked_fn=clicked_fn)
def create_background(self):
bg_color = carb.settings.get_settings().get('/exts/omni.kit.viewport.ready/background_color')
if bg_color:
omni.ui.Rectangle(style={"background_color": bg_color})
def create_ui(self):
with ui.ZStack():
if self.__add_background:
self.create_background()
with ui.HStack():
ui.Spacer(width=20)
with ui.VStack():
ui.Spacer()
self.create_label()
ui.Spacer(height=20)
with ui.HStack(height=100):
ui.Spacer()
self.create_buttons(self.__button_size[0], self.__button_size[1])
ui.Spacer()
ui.Spacer()
ui.Spacer(width=20)
@property
def visible(self):
return self.__frame.visible if self.__frame else None
@visible.setter
def visible(self, visible: bool):
if self.__frame:
self.__frame.visible = visible
elif visible:
import carb
carb.log_error("Cannot make WelcomeWidget visible after it was destroyed")
| 3,244 |
Python
| 36.29885 | 135 | 0.608508 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/window.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.
#
__all__ = ["WelcomeWindow"]
from .widget import WelcomeWidget
from typing import Optional
import omni.ui as ui
class WelcomeWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, buttons: dict, *args, **kwargs):
super().__init__(title, *args, **kwargs)
self.__buttons = buttons
self.__widget: Optional[WelcomeWidget] = None
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self.__build_fn)
def __destroy_widget(self):
if self.__widget:
self.__widget.destroy()
self.__widget = None
def __build_fn(self):
# Destroy any existing WelcomeWidget
self.__destroy_widget()
# Add the Welcomwidget
self.__widget = WelcomeWidget(self.__buttons)
def destroy(self):
# It will destroy all the children
self.__destroy_widget()
super().destroy()
@property
def wlcome_widget(self):
return self.__widget
| 1,477 |
Python
| 31.130434 | 85 | 0.668246 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/test_widget.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.
#
__all__ = ["TestWidget"]
from omni.kit.window.welcome.widget import WelcomeWidget
import omni.kit.app
import omni.kit.test
import omni.ui as ui
class TestWidget(omni.kit.test.AsyncTestCase):
async def test_general(self):
"""Create a widget and make sure there are no errors"""
window = ui.Window("Test")
with window.frame:
WelcomeWidget(buttons={})
await omni.kit.app.get_app().next_update_async()
| 879 |
Python
| 32.846153 | 76 | 0.737201 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/__init__.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.
#
from .test_widget import TestWidget
from .test_window import TestWindow
| 500 |
Python
| 44.54545 | 76 | 0.812 |
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/test_window.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.
#
__all__ = ["TestWindow"]
from omni.kit.window.welcome.window import WelcomeWindow
import omni.kit.app
import omni.kit.test
class TestWindow(omni.kit.test.AsyncTestCase):
async def test_general(self):
"""Create a window and make sure there are no errors"""
window = WelcomeWindow("Welcome Window Test", buttons={})
await omni.kit.app.get_app().next_update_async()
| 823 |
Python
| 36.454544 | 76 | 0.755772 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/delegate.py
|
# Copyright (c) 2018-2020, 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 abc
class SearchDelegate:
def __init__(self):
self._search_dir = None
@property
def visible(self):
return True # pragma: no cover
@property
def enabled(self):
"""Enable/disable Widget"""
return True # pragma: no cover
@property
def search_dir(self):
return self._search_dir # pragma: no cover
@search_dir.setter
def search_dir(self, search_dir: str):
self._search_dir = search_dir # pragma: no cover
@abc.abstractmethod
def build_ui(self):
pass # pragma: no cover
@abc.abstractmethod
def destroy(self):
pass # pragma: no cover
| 1,098 |
Python
| 26.474999 | 76 | 0.678506 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/style.py
|
# Copyright (c) 2018-2020, 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 carb
import omni.ui as ui
from pathlib import Path
try:
THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle")
except Exception:
THEME = None
finally:
THEME = THEME or "NvidiaDark"
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"icons/{THEME}")
THUMBNAIL_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("thumbnails")
def get_style():
if THEME == "NvidiaLight":
BACKGROUND_COLOR = 0xFF535354
BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E
BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E
BACKGROUND_DISABLED_COLOR = 0xFF666666
TEXT_COLOR = 0xFF8D760D
TEXT_HINT_COLOR = 0xFFD6D6D6
SEARCH_BORDER_COLOR = 0xFFC9974C
SEARCH_HOVER_COLOR = 0xFFB8B8B8
SEARCH_CLOSE_COLOR = 0xFF858585
SEARCH_TEXT_BACKGROUND_COLOR = 0xFFD9D4BC
else:
BACKGROUND_COLOR = 0xFF23211F
BACKGROUND_SELECTED_COLOR = 0xFF8A8777
BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A
BACKGROUND_DISABLED_COLOR = 0xFF666666
TEXT_COLOR = 0xFF9E9E9E
TEXT_HINT_COLOR = 0xFF4A4A4A
SEARCH_BORDER_COLOR = 0xFFC9974C
SEARCH_HOVER_COLOR = 0xFF3A3A3A
SEARCH_CLOSE_COLOR = 0xFF858585
SEARCH_TEXT_BACKGROUND_COLOR = 0xFFD9D4BC
style = {
"Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin": 0,
"padding": 0
},
"Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"Button.Label": {"color": TEXT_COLOR},
"Field": {"background_color": 0x0, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"Label": {"background_color": 0x0, "color": TEXT_COLOR},
"Rectangle": {"background_color": 0x0},
"SearchField": {
"background_color": 0,
"border_radius": 0,
"border_width": 0,
"background_selected_color": BACKGROUND_COLOR,
"margin": 0,
"padding": 4,
"alignment": ui.Alignment.LEFT_CENTER,
},
"SearchField.Frame": {
"background_color": BACKGROUND_COLOR,
"border_radius": 0.0,
"border_color": 0,
"border_width": 2,
},
"SearchField.Frame:selected": {
"background_color": BACKGROUND_COLOR,
"border_radius": 0,
"border_color": SEARCH_BORDER_COLOR,
"border_width": 2,
},
"SearchField.Frame:disabled": {
"background_color": BACKGROUND_DISABLED_COLOR,
},
"SearchField.Hint": {"color": TEXT_HINT_COLOR},
"SearchField.Button": {"background_color": 0x0, "margin_width": 2, "padding": 4},
"SearchField.Button.Image": {"color": TEXT_HINT_COLOR},
"SearchField.Clear": {"background_color": 0x0, "padding": 4},
"SearchField.Clear:hovered": {"background_color": SEARCH_HOVER_COLOR},
"SearchField.Clear.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": SEARCH_CLOSE_COLOR},
"SearchField.Word": {"background_color": SEARCH_TEXT_BACKGROUND_COLOR},
"SearchField.Word.Label": {"color": TEXT_COLOR},
"SearchField.Word.Button": {"background_color": 0, "padding": 2},
"SearchField.Word.Button.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": TEXT_COLOR},
}
return style
| 4,013 |
Python
| 39.959183 | 148 | 0.62771 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/__init__.py
|
# Copyright (c) 2018-2020, 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.
#
"""
A UI widget to search for files in a filesystem.
"""
from .widget import SearchField
from .delegate import SearchDelegate
from .model import SearchResultsModel, SearchResultsItem
| 617 |
Python
| 37.624998 | 76 | 0.805511 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/model.py
|
# Copyright (c) 2018-2020, 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.ui as ui
import omni.client
from typing import Dict
from datetime import datetime
from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem, find_thumbnails_for_files_async
from omni.kit.widget.filebrowser.model import FileBrowserItemFields
from omni.kit.search_core import AbstractSearchModel, AbstractSearchItem
class SearchResultsItem(FileBrowserItem):
_thumbnail_dict: Dict = {}
def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = False):
super().__init__(path, fields, is_folder=is_folder)
class _RedirectModel(ui.AbstractValueModel):
def __init__(self, search_model, field):
super().__init__()
self._search_model = search_model
self._field = field
def get_value_as_string(self):
return str(self._search_model[self._field])
def set_value(self, value):
pass
async def get_custom_thumbnails_for_folder_async(self) -> Dict:
"""
Returns the thumbnail dictionary for this (folder) item.
Returns:
Dict: With children url's as keys, and url's to thumbnail files as values.
"""
if not self.is_folder:
return {}
# Files in the root folder only
file_urls = []
for _, item in self.children.items():
if item.is_folder or item.path in self._thumbnail_dict:
# Skip if folder or thumbnail previously found
pass
else:
file_urls.append(item.path)
thumbnail_dict = await find_thumbnails_for_files_async(file_urls)
for url, thumbnail_url in thumbnail_dict.items():
if url and thumbnail_url:
self._thumbnail_dict[url] = thumbnail_url
return self._thumbnail_dict
class SearchResultsItemFactory:
@staticmethod
def create_item(search_item: AbstractSearchItem) -> SearchResultsItem:
if not search_item:
return None
access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE
fields = FileBrowserItemFields(search_item.name, search_item.date, search_item.size, access)
item = SearchResultsItem(search_item.path, fields, is_folder=search_item.is_folder)
item._models = (
SearchResultsItem._RedirectModel(search_item, "name"),
SearchResultsItem._RedirectModel(search_item, "date"),
SearchResultsItem._RedirectModel(search_item, "size"),
)
return item
@staticmethod
def create_group_item(name: str, path: str) -> SearchResultsItem:
access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE
fields = FileBrowserItemFields(name, datetime.now(), 0, access)
item = SearchResultsItem(path, fields, is_folder=True)
return item
class SearchResultsModel(FileBrowserModel):
def __init__(self, search_model: AbstractSearchModel, **kwargs):
super().__init__(**kwargs)
self._root = SearchResultsItemFactory.create_group_item("Search Results", "search_results://")
self._search_model = search_model
# Circular dependency
self._dirty_item_subscription = self._search_model.subscribe_item_changed(self.__on_item_changed)
def destroy(self):
# Remove circular dependency
self._dirty_item_subscription = None
if self._search_model:
self._search_model.destroy()
self._search_model = None
def get_item_children(self, item: SearchResultsItem) -> [SearchResultsItem]:
if self._search_model is None or item is not None:
return []
# OM-92499: Skip populate for empty search model items
if not self._root.populated and self._search_model.items:
for search_item in self._search_model.items:
self._root.add_child(SearchResultsItemFactory.create_item(search_item))
self._root.populated = True
children = list(self._root.children.values())
if self._filter_fn:
return list(filter(self._filter_fn, children))
else:
return children
def __on_item_changed(self, item):
self._item_changed(item)
| 4,673 |
Python
| 37.95 | 106 | 0.657822 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/widget.py
|
# Copyright (c) 2018-2020, 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 import ui
from carb import log_warn
from typing import Callable, List
from omni.kit.search_core import SearchEngineRegistry
from .delegate import SearchDelegate
from .model import SearchResultsModel
from .style import get_style, ICON_PATH
class SearchWordButton:
"""
Represents a search word widget, combined with a label to show the word and a close button to remove it.
Args:
word (str): String of word.
Keyword args:
on_close_fn (callable): Function called when close button clicked. Function signure:
void on_close_fn(widget: SearchWordButton)
"""
def __init__(self, word: str, on_close_fn: callable = None):
self._container = ui.ZStack(width=0)
with self._container:
with ui.VStack():
ui.Spacer(height=5)
ui.Rectangle(style_type_name_override="SearchField.Word")
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer(width=3)
ui.Label(word, width=0, style_type_name_override="SearchField.Word.Label")
ui.Spacer(width=3)
ui.Button(
image_width=8,
style_type_name_override="SearchField.Word.Button",
clicked_fn=lambda: on_close_fn(self) if on_close_fn is not None else None,
identifier="search_word_button",
)
@property
def visible(self) -> None:
"""Widget visibility"""
return self._container.visible
@visible.setter
def visible(self, value: bool) -> None:
self._container.visible = value
class SearchField(SearchDelegate):
"""
A search field to input search words
Args:
callback (callable): Function called after search done. Function signature: void callback(model: SearchResultsModel)
Keyword Args:
width (Optional[ui.Length]): Widget widthl. Default None, means auto.
height (Optional[ui.Length]): Widget height. Default ui.Pixel(26). Use None for auto.
subscribe_edit_changed (bool): True to retreive on_search_fn called when input changed. Default False only retreive on_search_fn called when input ended.
show_tokens (bool): Default True to show tokens if end edit. Do nothing if False.
Properties:
visible (bool): Widget visibility.
enabled (bool): Enable/Disable widget.
"""
SEARCH_IMAGE_SIZE = 16
CLOSE_IMAGE_SIZE = 12
def __init__(self, callback: Callable, **kwargs):
super().__init__(**kwargs)
self._callback = callback
self._container_args = {"style": get_style()}
if kwargs.get("width") is not None:
self._container_args["width"] = kwargs.get("width")
self._container_args["height"] = kwargs.get("height", ui.Pixel(26))
self._subscribe_edit_changed = kwargs.get("subscribe_edit_changed", False)
self._show_tokens = kwargs.get("show_tokens", True)
self._search_field: ui.StringField = None
self._search_engine = None
self._search_engine_menu = None
self._search_words: List[str] = []
self._in_searching = False
self._search_label = None
# OM-76011:subscribe to engine changed
self.__search_engine_changed_sub = SearchEngineRegistry().subscribe_engines_changed(self._on_search_engines_changed)
@property
def visible(self):
"""
Widget visibility
"""
return self._container.visible
@visible.setter
def visible(self, value):
self._container.visible = value
@property
def enabled(self):
"""
Enable/disable Widget
"""
return self._container.enabled
@enabled.setter
def enabled(self, value):
self._container.enabled = value
if value:
self._search_label.text = "Search"
else:
self._search_label.text = "Search disabled. Please install a search extension."
@property
def search_dir(self):
return self._search_dir
@search_dir.setter
def search_dir(self, search_dir: str):
dir_changed = search_dir != self._search_dir
self._search_dir = search_dir
if self._in_searching and dir_changed:
self.search(self._search_words)
def build_ui(self):
self._container = ui.ZStack(**self._container_args)
with self._container:
# background
self._background = ui.Rectangle(style_type_name_override="SearchField.Frame")
with ui.HStack():
with ui.VStack(width=0):
# Search "magnifying glass" button
search_button = ui.Button(
image_url=f"{ICON_PATH}/search.svg",
image_width=SearchField.SEARCH_IMAGE_SIZE,
image_height=SearchField.SEARCH_IMAGE_SIZE,
style_type_name_override="SearchField.Button",
identifier="show_engine_menu",
)
search_button.set_clicked_fn(
lambda b=search_button: self._show_engine_menu(
b.screen_position_x, b.screen_position_y + b.computed_height
)
)
with ui.HStack():
with ui.ZStack():
with ui.HStack():
# Individual word widgets
if self._show_tokens:
self._words_container = ui.HStack()
self._build_search_words()
# String field to accept user input, here ui.Spacer for border of SearchField.Frame
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
self._search_field = ui.StringField(
ui.SimpleStringModel(),
mouse_double_clicked_fn=lambda x, y, btn, m: self._convert_words_to_string(),
style_type_name_override="SearchField",
)
ui.Spacer()
self._hint_container = ui.HStack(spacing=4)
with self._hint_container:
# Hint label
self._search_label = ui.Label("Search", width=275,
style_type_name_override="SearchField.Hint")
# Close icon
with ui.VStack(width=20):
ui.Spacer(height=2)
self._clear_button = ui.Button(
image_width=SearchField.CLOSE_IMAGE_SIZE,
style_type_name_override="SearchField.Clear",
clicked_fn=self._on_clear_clicked,
)
ui.Spacer(height=2)
ui.Spacer(width=2)
self._clear_button.visible = False
self._sub_begin_edit = self._search_field.model.subscribe_begin_edit_fn(self._on_begin_edit)
self._sub_end_edit = self._search_field.model.subscribe_end_edit_fn(self._on_end_edit)
if self._subscribe_edit_changed:
self._sub_text_edit = self._search_field.model.subscribe_value_changed_fn(self._on_text_edit)
else:
self._sub_text_edit = None
# check on init for if we have available search engines
self._on_search_engines_changed()
def destroy(self):
self._callback = None
self._search_field = None
self._sub_begin_edit = None
self._sub_end_edit = None
self._sub_text_edit = None
self._background = None
self._hint_container = None
self._clear_button = None
self._search_label = None
self._container = None
self.__search_engine_changed_sub = None
def _show_engine_menu(self, x, y):
self._search_engine_menu = ui.Menu("Engines")
search_names = SearchEngineRegistry().get_available_search_names(self._search_dir)
if not search_names:
return
# TODO: We need to have predefined default search
if self._search_engine is None or self._search_engine not in search_names:
self._search_engine = search_names[0]
def set_current_engine(engine_name):
self._search_engine = engine_name
with self._search_engine_menu:
for name in search_names:
ui.MenuItem(
name,
checkable=True,
checked=self._search_engine == name,
triggered_fn=lambda n=name: set_current_engine(n),
)
self._search_engine_menu.show_at(x, y)
def _get_search_words(self) -> List[str]:
# Split the input string to words and filter invalid
search_string = self._search_field.model.get_value_as_string()
search_words = [word for word in search_string.split(" ") if word]
if len(search_words) == 0:
return None
elif len(search_words) == 1 and search_words[0] == "":
# If empty input, regard as clear
return None
else:
return search_words
def _on_begin_edit(self, model):
self._set_in_searching(True)
def _on_end_edit(self, model: ui.AbstractValueModel) -> None:
search_words = self._get_search_words()
if search_words is None:
# Filter empty(hidden) word
filter_words = [word for word in self._search_words if word]
if len(filter_words) == 0:
self._set_in_searching(False)
else:
if self._show_tokens:
self._search_words.extend(search_words)
self._build_search_words()
self._search_field.model.set_value("")
else:
self._search_words = search_words
self.search(self._search_words)
def _on_text_edit(self, model: ui.AbstractValueModel) -> None:
new_search_words = self._get_search_words()
if new_search_words is not None:
# Add current input to search words
search_words = []
search_words.extend(self._search_words)
search_words.extend(new_search_words)
self._search_words = search_words
self.search(self._search_words)
def _convert_words_to_string(self) -> None:
if self._show_tokens:
# convert existing search words back to string
filter_words = [word for word in self._search_words if word]
seperator = " "
self._search_words = []
self._build_search_words()
original_string = seperator.join(filter_words)
# Append current input
input_string = self._search_field.model.get_value_as_string()
if input_string:
original_string = original_string + seperator + input_string
self._search_field.model.set_value(original_string)
def _on_clear_clicked(self) -> None:
# Update UI
self._set_in_searching(False)
self._search_field.model.set_value("")
self._search_words.clear()
self._build_search_words()
# Notification
self.search(None)
def _set_in_searching(self, in_searching: bool) -> None:
self._in_searching = in_searching
# Background outline
self._background.selected = in_searching
# Show/Hide hint frame (search icon and hint lable)
self._hint_container.visible = not in_searching
# Show/Hide close image
self._clear_button.visible = in_searching
def _build_search_words(self):
if self._show_tokens:
self._words_container.clear()
if len(self._search_words) == 0:
return
with self._words_container:
ui.Spacer(width=4)
for index, word in enumerate(self._search_words):
if word:
SearchWordButton(word, on_close_fn=lambda widget, idx=index: self._hide_search_word(idx, widget))
def _hide_search_word(self, index: int, widget: SearchWordButton) -> None:
# Here cannot remove the widget since this function is called by the widget
# So just set invisible and change to empty word
# It will be removed later if clear or edit end.
widget.visible = False
if index >= 0 and index < len(self._search_words):
self._search_words[index] = ""
self.search(self._search_words)
def search(self, search_words: List[str]):
"""
Search using selected search engine.
Args:
search_words (List[str]): List of search terms.
"""
# TODO: We need to have predefined default search
if self._search_engine is None:
search_names = SearchEngineRegistry().get_search_names()
self._search_engine = search_names[0] if search_names else None
if self._search_engine:
SearchModel = SearchEngineRegistry().get_search_model(self._search_engine)
else:
log_warn("No search engines registered! Please import a search extension.")
return
if not SearchModel:
log_warn(f"Search engine '{self._search_engine}' not found.")
return
search_words = [word for word in search_words or [] if word] # Filter empty(hidden) word
if len(search_words) > 0:
search_results = SearchModel(search_text=" ".join(search_words), current_dir=self._search_dir)
model = SearchResultsModel(search_results)
else:
model = None
if self._callback:
self._callback(model)
def _on_search_engines_changed(self):
search_names = SearchEngineRegistry().get_search_names()
self.enabled = bool(search_names)
| 14,675 |
Python
| 38.772358 | 161 | 0.567564 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/tests/__init__.py
|
## Copyright (c) 2018-2020, 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 .test_search_field import *
| 474 |
Python
| 46.499995 | 77 | 0.791139 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/tests/test_search_field.py
|
## Copyright (c) 2018-2019, 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 unittest.mock import patch, MagicMock
import omni.kit.ui_test as ui_test
from omni.kit.ui_test.query import MenuRef
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.search_core import AbstractSearchModel, AbstractSearchItem, SearchEngineRegistry
from ..widget import SearchField
from ..model import SearchResultsModel
class MockSearchEngineRegistry(MagicMock):
def get_search_names():
return "test_search"
def get_search_model(_: str):
return MockSearchModel
class MockSearchItem(AbstractSearchItem):
def __init__(self, name: str, path: str):
super().__init__()
self._name = name
self._path = path
@property
def name(self):
return self._name
@property
def path(self):
return self._path
class MockSearchModel(AbstractSearchModel):
def __init__(self, search_text: str, current_dir: str):
super().__init__()
self._items = []
search_words = search_text.split(" ")
# Return mock results from input search text
for search_word in search_words:
name = f"{search_word}.usd"
self._items.append(MockSearchItem(name, f"{current_dir}/{name}"))
@property
def items(self):
return self._items
class TestSearchField(OmniUiTest):
async def setUp(self):
self._search_results = None
async def tearDown(self):
if self._search_results:
self._search_results.destroy()
self._search_results = None
def _on_search(self, search_results: SearchResultsModel):
self._search_results = search_results
async def test_search_succeeds(self):
"""Testing search function successfully returns search results"""
window = await self.create_test_window()
with window.frame:
under_test = SearchField(self._on_search)
under_test.build_ui()
search_words = ["foo", "bar"]
with patch("omni.kit.widget.search_delegate.widget.SearchEngineRegistry", return_value=MockSearchEngineRegistry):
under_test.search_dir = "C:/my_search_dir"
under_test.search(search_words)
# Assert the the search generated the expected results
results = self._search_results.get_item_children(None)
self.assertEqual(
[f"{under_test.search_dir}/{w}.usd" for w in search_words],
[result.path for result in results]
)
for result in results:
thumbnail = await result.get_custom_thumbnails_for_folder_async()
self.assertEqual(thumbnail, {})
self.assertTrue(under_test.visible)
under_test.destroy()
async def test_setting_search_dir_triggers_search(self):
"""Testing that when done editing the search field, executes the search"""
window = await self.create_test_window()
mock_search = MagicMock()
with window.frame:
with patch.object(SearchField, "search") as mock_search:
under_test = SearchField(None)
under_test.build_ui()
# Procedurally set search directory and search field
search_words = ["foo", "bar"]
under_test.search_dir = "C:/my_search_dir"
under_test._on_begin_edit(None)
under_test._search_field.model.set_value(" ".join(search_words))
under_test._on_end_edit(None)
# Assert that the search is executed
mock_search.assert_called_once_with(search_words)
under_test.destroy()
async def test_engine_menu(self):
window = await self.create_test_window(block_devices=False)
with window.frame:
under_test = SearchField(None)
under_test.build_ui()
self._subscription = SearchEngineRegistry().register_search_model("TEST_SEARCH", MockSearchModel)
window_ref = ui_test.WindowRef(window, "")
button_ref = window_ref.find_all("**/Button[*].identifier=='show_engine_menu'")[0]
await button_ref.click()
self.assertTrue(under_test.enabled)
self.assertIsNotNone(under_test._search_engine_menu)
self.assertTrue(under_test._search_engine_menu.shown)
menu_ref = MenuRef(under_test._search_engine_menu, "")
menu_items = menu_ref.find_all("**/")
self.assertEqual(len(menu_items), 1)
self.assertEqual(menu_items[0].widget.text, "TEST_SEARCH")
under_test.destroy()
self._subscription = None
async def test_edit_search(self):
window = await self.create_test_window(block_devices=False)
with window.frame:
under_test = SearchField(self._on_search)
under_test.build_ui()
self._subscription = SearchEngineRegistry().register_search_model("TEST_SEARCH", MockSearchModel)
search_words = ["foo", "bar"]
under_test.search_dir = "C:/my_search_dir"
under_test._on_begin_edit(None)
under_test._search_field.model.set_value(" ".join(search_words))
under_test._on_end_edit(None)
results = self._search_results.get_item_children(None)
self.assertEqual(len(results), 2)
# Remove first search
window_ref = ui_test.WindowRef(window, "")
close_ref = window_ref.find_all(f"**/Button[*].identifier=='search_word_button'")[0]
await close_ref.click()
results = self._search_results.get_item_children(None)
self.assertEqual(len(results), 1)
# Clear search
await self.wait_n_updates()
clear_ref = ui_test.WidgetRef(under_test._clear_button, "", window=window)
await clear_ref.click()
self.assertIsNone(self._search_results)
self._subscription = None
under_test.destroy()
| 6,247 |
Python
| 36.190476 | 121 | 0.639187 |
omniverse-code/kit/exts/omni.kit.widget.search_delegate/docs/index.rst
|
omni.kit.widget.search_delegate
###############################
Base module that provides a search widget for searching the file system
.. toctree::
:maxdepth: 1
CHANGELOG
.. automodule:: omni.kit.widget.search_delegate
:platform: Windows-x86_64, Linux-x86_64
:members:
:show-inheritance:
:undoc-members:
.. autoclass:: SearchField
:members:
| 382 |
reStructuredText
| 18.149999 | 71 | 0.628272 |
omniverse-code/kit/exts/omni.graph/PACKAGE-LICENSES/omni.graph-LICENSE.md
|
Copyright (c) 2020, 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.
| 412 |
Markdown
| 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.graph/config/extension.toml
|
[package]
title = "OmniGraph Python"
version = "1.50.2"
category = "Graph"
readme = "docs/README.md"
description = "Contains the implementation of the OmniGraph core (Python Support)."
preview_image = "data/preview.png"
repository = ""
keywords = ["kit", "omnigraph", "core"]
# Main Python module, available as "import omni.graph.core"
[[python.module]]
name = "omni.graph.core"
# Other extensions on which this one relies
[dependencies]
"omni.graph.core" = {}
"omni.graph.tools" = {}
"omni.kit.test" = {}
"omni.kit.commands" = {}
"omni.kit.usd_undo" = {}
"omni.usd" = {}
"omni.client" = {}
"omni.kit.async_engine" = {}
"omni.kit.stage_templates" = {}
"omni.kit.pip_archive" = {}
[python.pipapi]
requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231
[[test]]
stdoutFailPatterns.exclude = [
"*Ignore this error/warning*",
]
pyCoverageFilter = ["omni.graph"] # Restrict coverage to omni.graph only
[documentation]
deps = [
["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph.core refs until that workflow is moved
]
pages = [
"docs/Overview.md",
"docs/commands.rst",
"docs/omni.graph.core.bindings.rst",
"docs/autonode.rst",
"docs/controller.rst",
"docs/running_one_script.rst",
"docs/runtimeInitialize.rst",
"docs/testing.rst",
"docs/CHANGELOG.md",
]
| 1,335 |
TOML
| 24.207547 | 113 | 0.669663 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_omni_graph_core.pyi
|
"""pybind11 omni.graph.core bindings"""
from __future__ import annotations
import omni.graph.core._omni_graph_core
import typing
import carb.events._events
import numpy
import omni.core._core
import omni.graph.core._omni_graph_core._internal
import omni.graph.core._omni_graph_core._og_unstable
import omni.inspect._omni_inspect
_Shape = typing.Tuple[int, ...]
__all__ = [
"ACCORDING_TO_CONTEXT_GRAPH_INDEX",
"APPLIED_SCHEMA",
"ASSET",
"AUTHORING_GRAPH_INDEX",
"Attribute",
"AttributeData",
"AttributePortType",
"AttributeRole",
"AttributeType",
"BOOL",
"BUNDLE",
"BaseDataType",
"BucketId",
"BundleChangeType",
"COLOR",
"CONNECTION",
"ComputeGraph",
"ConnectionInfo",
"ConnectionType",
"DOUBLE",
"ERROR",
"EXECUTION",
"ExecutionAttributeState",
"ExtendedAttributeType",
"FLOAT",
"FRAME",
"FileFormatVersion",
"Graph",
"GraphBackingType",
"GraphContext",
"GraphEvaluationMode",
"GraphEvent",
"GraphPipelineStage",
"GraphRegistry",
"GraphRegistryEvent",
"HALF",
"IBundle2",
"IBundleChanges",
"IBundleFactory",
"IBundleFactory2",
"IConstBundle2",
"INFO",
"INSTANCING_GRAPH_TARGET_PATH",
"INT",
"INT64",
"INodeCategories",
"ISchedulingHints",
"ISchedulingHints2",
"IVariable",
"MATRIX",
"MemoryType",
"NONE",
"NORMAL",
"Node",
"NodeEvent",
"NodeType",
"OBJECT_ID",
"OmniGraphBindingError",
"PATH",
"POSITION",
"PRIM",
"PRIM_TYPE_NAME",
"PtrToPtrKind",
"QUATERNION",
"RELATIONSHIP",
"Severity",
"TAG",
"TARGET",
"TEXCOORD",
"TEXT",
"TIMECODE",
"TOKEN",
"TRANSFORM",
"Type",
"UCHAR",
"UINT",
"UINT64",
"UNKNOWN",
"VECTOR",
"WARNING",
"acquire_interface",
"attach",
"deregister_node_type",
"deregister_post_load_file_format_upgrade_callback",
"deregister_pre_load_file_format_upgrade_callback",
"detach",
"eAccessLocation",
"eAccessType",
"eComputeRule",
"ePurityStatus",
"eThreadSafety",
"eVariableScope",
"get_all_graphs",
"get_all_graphs_and_subgraphs",
"get_bundle_tree_factory_interface",
"get_compute_graph_contexts",
"get_global_orchestration_graphs",
"get_global_orchestration_graphs_in_pipeline_stage",
"get_graph_by_path",
"get_graphs_in_pipeline_stage",
"get_node_by_path",
"get_node_categories_interface",
"get_node_type",
"get_registered_nodes",
"is_global_graph_prim",
"on_shutdown",
"register_node_type",
"register_post_load_file_format_upgrade_callback",
"register_pre_load_file_format_upgrade_callback",
"register_python_node",
"release_interface",
"set_test_failure",
"shutdown_compute_graph",
"test_failure_count",
"update"
]
class Attribute():
"""
An attribute, defining a data type and value that belongs to a node
"""
def __bool__(self) -> bool: ...
def __eq__(self, arg0: Attribute) -> bool: ...
def __hash__(self) -> int: ...
def __repr__(self) -> str: ...
def connect(self, path: Attribute, modify_usd: bool) -> bool:
"""
Connects this attribute with another attribute. Assumes regular connection type.
Args:
path (omni.graph.core.Attribute): The destination attr
modify_usd (bool): Whether to create USD.
Returns:
bool: True for success, False for fail
"""
@staticmethod
def connectEx(*args, **kwargs) -> typing.Any:
"""
Connects this attribute with another attribute. Allows for different connection types.
Args:
info (omni.graph.core.ConnectionInfo): The ConnectionInfo object that contains both the attribute and the connection type
modify_usd (bool): Whether to modify the underlying USD with this connection
Returns:
bool: True for success, False for fail
"""
def connectPrim(self, path: str, modify_usd: bool, write: bool) -> bool:
"""
Connects this attribute to a prim that can represent a bundle connection or just a plain prim relationship
Args:
path (str): The path to the prim
modify_usd (bool): Whether to modify USD.
write (bool): Whether this connection represents a bundle
Returns:
bool: True for success, False for fail
"""
def deprecation_message(self) -> str:
"""
Gets the deprecation message on an attribute, if it is deprecated.
Typically this message gives guidance as to what the user should do instead of using the deprecated attribute.
Returns:
str: The message associated with a deprecated attribute
"""
def disconnect(self, attribute: Attribute, modify_usd: bool) -> bool:
"""
Disconnects this attribute from another attribute.
Args:
attribute (omni.graph.core.Attribute): The destination attribute of the connection to remove
modify_usd (bool): Whether to modify USD
Returns:
bool: True for success, False for fail
"""
def disconnectPrim(self, path: str, modify_usd: bool, write: bool) -> bool:
"""
Disconnects this attribute to a prim that can represent a bundle connection or just a plain prim relationship
Args:
path (str): The path to the prim
modify_usd (bool): Whether to modify USD.
write (bool): Whether this connection represents a bundle
Returns:
bool: True for success, False for fail
"""
@staticmethod
def ensure_port_type_in_name(name: str, port_type: AttributePortType, is_bundle: bool) -> str:
"""
Return the attribute name with the port type namespace prepended if it isn't already present.
Args:
name (str): The attribute name, with or without the port prefix
port_type (omni.graph.core.AttributePortType): The port type of the attribute
is_bundle (bool): true if the attribute name is to be used in a bundle. Note that colon is an illegal character
in bundled attributes so an underscore is used instead.
Returns:
str: The name with the proper prefix for the given port type
"""
def get(self, on_gpu: bool = False, instance: int = 18446744073709551614) -> object:
"""
Get the value of the attribute
Args:
on_gpu (bool): Is the data to be retrieved from the GPU?
instance (int): an instance index when getting value on an instantiated graph
Returns:
Any: Value of the attribute's data
"""
def get_all_metadata(self) -> dict:
"""
Gets the attribute's metadata
Returns:
dict[str,str]: A dictionary of name:value metadata on the attribute
"""
@staticmethod
def get_array(*args, **kwargs) -> typing.Any:
"""
Gets the value of an array attribute
Args:
on_gpu (bool): Is the data to be retrieved from the GPU?
get_for_write (bool): Should the data be retrieved for writing?
reserved_element_count (int): If the data is to be retrieved for writing, preallocate this many elements
instance (int): an instance index when getting value on an instantiated graph
Returns:
list[Any]: Value of the array attribute's data
"""
@staticmethod
def get_attribute_data(*args, **kwargs) -> typing.Any:
"""
Get the AttributeData object that can access the attribute's data
Args:
instance (int): an instance index when getting value on an instantiated graph
Returns:
omni.graph.core.AttributeData: The underlying attribute data accessor object for this attribute
"""
def get_disable_dynamic_downstream_work(self) -> bool:
"""
Where we have dynamic scheduling, downstream nodes can have their execution disabled by turning on the flag
in the upstream attribute. Note you also have to call setDynamicDownstreamControl on the node to enable
this feature. See setDynamicDownstreamControl on INode for further information.
Returns:
bool: True if downstream nodes are disabled in dynamic scheduling, False otherwise
"""
def get_downstream_connection_count(self) -> int:
"""
Gets the number of downstream connections to this attribute
Returns:
int: the number of downstream connections on this attribute.
"""
def get_downstream_connections(self) -> typing.List[Attribute]:
"""
Gets the list of downstream connections to this attribute
Returns:
list[omni.graph.core.Attribute]: The list of downstream connections for this attribute.
"""
@staticmethod
def get_downstream_connections_info(*args, **kwargs) -> typing.Any:
"""
Returns the list of downstream connections for this attribute, with detailed connection information
such as the connection type.
Returns:
list[omni.graph.core.ConnectionInfo]: A list of the downstream ConnectionInfo objects
"""
def get_extended_type(self) -> ExtendedAttributeType:
"""
Get the extended type of the attribute
Returns:
omni.graph.core.ExtendedAttributeType: Extended type of the attribute data object
"""
def get_handle(self) -> int:
"""
Get a handle to the attribute
Returns:
int: An opaque handle to the attribute
"""
def get_metadata(self, key: str) -> str:
"""
Returns the metadata value for the given key.
Args:
key: (str) The metadata keyword
Returns:
str: Metadata value for the given keyword, or None if it is not defined
"""
def get_metadata_count(self) -> int:
"""
Gets the number of metadata values on the attribute
Returns:
int: the number of metadata values currently defined on the attribute.
"""
def get_name(self) -> str:
"""
Get the attribute's name
Returns:
str: The name of the current attribute.
"""
@staticmethod
def get_node(*args, **kwargs) -> typing.Any:
"""
Gets the node to which this attribute belongs
Returns:
omni.graph.core.Node: The node associated with the attribute
"""
def get_path(self) -> str:
"""
Get the path to the attribute
Returns:
str: The full path to the attribute, including the node path.
"""
def get_port_type(self) -> AttributePortType:
"""
Gets the attribute's port type (input, output, or state)
Returns:
omni.graph.core.AttributePortType: The port type of the attribute.
"""
@staticmethod
def get_port_type_from_name(name: str) -> AttributePortType:
"""
Parse the port type from the given attribute name if present. The port type is indicated by a prefix seperated by
a colon or underscore in the case of bundled attributes.
Args:
name The attribute name
Returns:
omni.graph.core.AttributePortType: The port type indicated by the attribute prefix if present.
AttributePortType.UNKNOWN if there is no recognized prefix.
"""
@staticmethod
def get_resolved_type(*args, **kwargs) -> typing.Any:
"""
Get the resolved type of the attribute
Returns:
omni.graph.core.Type: Resolved type of the attribute data object, or the hardcoded type for regular attributes
"""
def get_type_name(self) -> str:
"""
Get the name of the attribute's type
Returns:
str: The type name of the current attribute.
"""
def get_union_types(self) -> object:
"""
Get the list of types accepted by a union attribute
Returns:
list[str]: The list of accepted types for the attribute if it is an extended union type, else None
"""
def get_upstream_connection_count(self) -> int:
"""
Gets the number of upstream connections to this attribute
Returns:
int: the number of upstream connections on this attribute.
"""
def get_upstream_connections(self) -> typing.List[Attribute]:
"""
Gets the list of upstream connections to this attribute
Returns:
list[omni.graph.core.Attribute]: The list of upstream connections for this attribute.
"""
@staticmethod
def get_upstream_connections_info(*args, **kwargs) -> typing.Any:
"""
Returns the list of upstream connections for this attribute, with detailed connection information
such as the connection type.
Returns:
list[omni.graph.core.ConnectionInfo]: A list of the upstream ConnectionInfo objects
"""
def is_array(self) -> bool:
"""
Checks if the attribute is an array type.
Returns:
bool: True if the attribute data type is an array
"""
def is_compatible(self, attribute: Attribute) -> bool:
"""
Checks to see if this attribute is compatible with another one, in particular the data types they use
Args:
attribute (omni.graph.core.Attribute): Attribute for which compatibility is to be checked
Returns:
bool: True if this attribute is compatible with "attribute"
"""
def is_connected(self, attribute: Attribute) -> bool:
"""
Checks to see if this attribute has a connection to another attribute
Args:
attribute (Attribute): Attribute for which the connection is to be checked
Returns:
bool: True if this attribute is connected to another, either as source or destination
"""
def is_deprecated(self) -> bool:
"""
Checks whether an attribute is deprecated. Deprecated attributes should not be used as
they will be removed in a future version.
Returns:
bool: True if the attribute is deprecated
"""
def is_dynamic(self) -> bool:
"""
Checks to see if an attribute is dynamic
Returns:
bool: True if the current attribute is a dynamic attribute (not in the node type definition).
"""
def is_runtime_constant(self) -> bool:
"""
Checks is this attribute is a runtime constant.
Runtime constants will keep the same value every frame, for every instance.
This property can be taken advantage of in vectorized compute.
Returns:
bool: True if the attribute is a runtime constant
"""
def is_valid(self) -> bool:
"""
Checks if the current attribute is valid.
Returns:
bool: True if the attribute reference points to a valid attribute object
"""
def register_value_changed_callback(self, func: object) -> None:
"""
Registers a function that will be invoked when the value of the given attribute changes.
Note that an attribute can have one and only one callback. Subsequent calls will replace
previously set callbacks. Passing None for the function argument will clear the existing
callback.
Args:
func (callable): A function with one argument representing the attribute that changed.
"""
@staticmethod
def remove_port_type_from_name(name: str, is_bundle: bool) -> str:
"""
Find the attribute name with the port type removed if it is present. For example "inputs:attr" becomes "attr"
Args:
name (str): The attribute name, with or without the port prefix
is_bundle (bool): True if the attribute name is to be used in a bundle. Note that colon is an illegal character
in bundled attributes so an underscore is used instead.
Returns:
str: The name with the port type prefix removed
"""
def set(self, value: object, on_gpu: bool = False, instance: int = 18446744073709551614) -> bool:
"""
Sets the value of the attribute's data
Args:
value (Any): New value of the attribute's data
on_gpu (bool): Is the data to be set on the GPU?
instance (int): an instance index when setting value on an instantiated graph
Returns:
bool: True if the value was successfully set
"""
def set_default(self, value: object, on_gpu: bool = False) -> bool:
"""
Sets the default value of the attribute's data (value when not connected)
Args:
value (Any): New value of the default attribute's data
on_gpu (bool): Is the data to be set on the GPU?
Returns:
bool: True if the value was successfully set
"""
def set_disable_dynamic_downstream_work(self, disable: bool) -> None:
"""
Where we have dynamic scheduling, downstream nodes can have their execution disabled by turning on the flag
in the upstream attribute. Note you also have to call setDynamicDownstreamControl on the node to enable
this feature. This function allows you to set the flag on the attribute that will disable the downstream
node. See setDynamicDownstreamControl on INode for further information.
Args:
disable (bool): Whether to disable downstream connected nodes in dynamic scheduling.
"""
def set_metadata(self, key: str, value: str) -> bool:
"""
Sets the metadata value for the given key
Args:
key (str): The metadata keyword
value (str): The value of the metadata
"""
@staticmethod
def set_resolved_type(*args, **kwargs) -> typing.Any:
"""
Sets the resolved type for the extended attribute.
Only valid for attributes with union/any extended types, who's
type has not yet been resolved. Should only be called from on_connection_type_resolve() callback. This operation
is async and may fail if the type cannot be resolved as requested.
Args:
resolved_type (omni.graph.core.Type): The type to resolve the attribute to
"""
def update_attribute_value(self, update_immediately: bool) -> bool:
"""
Requests the value of an attribute. In the cases of lazy evaluation systems, this
generates the "pull" that causes the attribute to update its value.
Args:
update_immediately (bool): Whether to update the attribute value immediately. If True, the function
will block until the attribute is update and then return. If False, the
attribute will be updated in the next update loop.
Returns:
Any: The value of the attribute
"""
@staticmethod
def write_complete(attributes: typing.Sequence) -> None:
"""
Warn the framework that writing to the provided attributes is done, so it can trigger callbacks attached to them
Args:
attributes (list[omni.graph.core.Attribute]): List of attributes that are done writing
"""
@property
def gpu_ptr_kind(self) -> omni::fabric::PtrToPtrKind:
"""
Defines the memory space that GPU array data pointers live in
:type: omni::fabric::PtrToPtrKind
"""
@gpu_ptr_kind.setter
def gpu_ptr_kind(self, arg1: omni::fabric::PtrToPtrKind) -> None:
"""
Defines the memory space that GPU array data pointers live in
"""
@property
def is_optional_for_compute(self) -> bool:
"""
Flag that is set when an attribute need not be valid for compute() to happen. bool:
:type: bool
"""
@is_optional_for_compute.setter
def is_optional_for_compute(self, arg1: bool) -> None:
"""
Flag that is set when an attribute need not be valid for compute() to happen. bool:
"""
resolved_prefix = '__resolved_'
pass
class AttributeData():
"""
Reference to data defining an attribute's value
"""
def __bool__(self) -> bool: ...
def __eq__(self, arg0: AttributeData) -> bool: ...
def __hash__(self) -> int: ...
def as_read_only(self) -> AttributeData:
"""
Returns read-only variant of the attribute data.
Returns:
AttributeData: Read-only variant of the attribute data.
"""
def copy_data(self, rhs: AttributeData) -> bool:
"""
Copies the AttributeData data into this object's data.
Args:
rhs (omni.graph.core.AttributeData): Attribute data to be copied - must be the same type as the current object to work
Returns:
bool: True if the data was successfully copied, else False.
"""
def cpu_valid(self) -> bool:
"""
Returns whether this attribute data object is currently valid on the cpu.
Returns:
bool: True if the data represented by this object currently has a valid value in CPU memory
"""
def get(self, on_gpu: bool = False) -> object:
"""
Gets the current value of the attribute data
Args:
on_gpu (bool): Is the data to be retrieved from the GPU?
Returns:
Any: Value of the attribute data
"""
@staticmethod
def get_array(*args, **kwargs) -> typing.Any:
"""
Gets the current value of the attribute data.
Args:
on_gpu (bool): Is the data to be retrieved from the GPU?
get_for_write (bool): Should the data be retrieved for writing?
reserved_element_count (int): If the data is to be retrieved for writing, preallocate this many elements
Returns:
Any: Value of the array attribute data
"""
def get_extended_type(self) -> ExtendedAttributeType:
"""
Returns the extended type of the current attribute data.
Returns:
omni.graph.core.ExtendedAttributeType: Extended type of the attribute data object
"""
def get_name(self) -> str:
"""
Returns the name of the current attribute data.
Returns:
str: Name of the attribute data object
"""
def get_resolved_type(self) -> Type:
"""
Returns the resolved type of the extended attribute data. Only valid for attributes with union/any extended types.
Returns:
omni.graph.core.Type: Resolved type of the attribute data object
"""
def get_type(self) -> Type:
"""
Returns the type of the current attribute data.
Returns:
omni.graph.core.Type: Type of the attribute data object
"""
def gpu_valid(self) -> bool:
"""
Returns whether this attribute data object is currently valid on the gpu.
Returns:
bool: True if the data represented by this object currently has a valid value in GPU memory
"""
def is_read_only(self) -> bool:
"""
Returns whether this attribute data object is read-only or not.
Returns:
bool: True if the data represented by this object is read-only
"""
def is_valid(self) -> bool:
"""
Returns whether this attribute data object is valid or not.
Returns:
bool: True if the data represented by this object is valid
"""
def resize(self, element_count: int) -> bool:
"""
Sets the number of elements in the array represented by this object.
Args:
element_count (int): Number of elements to reserve in the array
Returns:
bool: True if the array was resized, False if not (e.g. if the attribute data was not an array type)
"""
def set(self, value: object, on_gpu: bool = False) -> bool:
"""
Sets the value of the attribute data
Args:
value (Any): New value of the attribute data
on_gpu (bool): Is the data to be set on the GPU?
Returns:
bool: True if the value was successfully set
"""
def size(self) -> int:
"""
Returns the size of the data represented by this object (1 if it's not an array).
Returns:
int: Number of elements in the data
"""
@property
def gpu_ptr_kind(self) -> PtrToPtrKind:
"""
Defines the memory space that GPU array data pointers live in
:type: PtrToPtrKind
"""
@gpu_ptr_kind.setter
def gpu_ptr_kind(self, arg1: PtrToPtrKind) -> None:
"""
Defines the memory space that GPU array data pointers live in
"""
pass
class AttributePortType():
"""
Port side of the attribute on its node
Members:
ATTRIBUTE_PORT_TYPE_INPUT : Deprecated: use og.AttributePortType.INPUT
ATTRIBUTE_PORT_TYPE_OUTPUT : Deprecated: use og.AttributePortType.OUTPUT
ATTRIBUTE_PORT_TYPE_STATE : Deprecated: use og.AttributePortType.STATE
ATTRIBUTE_PORT_TYPE_UNKNOWN : Deprecated: use og.AttributePortType.UNKNOWN
INPUT : Attribute is an input
OUTPUT : Attribute is an output
STATE : Attribute is state
UNKNOWN : Attribute port type is unknown
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
ATTRIBUTE_PORT_TYPE_INPUT: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: 0>
ATTRIBUTE_PORT_TYPE_OUTPUT: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: 1>
ATTRIBUTE_PORT_TYPE_STATE: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: 2>
ATTRIBUTE_PORT_TYPE_UNKNOWN: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_UNKNOWN: 3>
INPUT: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: 0>
OUTPUT: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: 1>
STATE: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: 2>
UNKNOWN: omni.graph.core._omni_graph_core.AttributePortType # value = <AttributePortType.ATTRIBUTE_PORT_TYPE_UNKNOWN: 3>
__members__: dict # value = {'ATTRIBUTE_PORT_TYPE_INPUT': <AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: 0>, 'ATTRIBUTE_PORT_TYPE_OUTPUT': <AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: 1>, 'ATTRIBUTE_PORT_TYPE_STATE': <AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: 2>, 'ATTRIBUTE_PORT_TYPE_UNKNOWN': <AttributePortType.ATTRIBUTE_PORT_TYPE_UNKNOWN: 3>, 'INPUT': <AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: 0>, 'OUTPUT': <AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: 1>, 'STATE': <AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: 2>, 'UNKNOWN': <AttributePortType.ATTRIBUTE_PORT_TYPE_UNKNOWN: 3>}
pass
class AttributeRole():
"""
Interpretation applied to the attribute data
Members:
APPLIED_SCHEMA : Data is to be interpreted as an applied schema
BUNDLE : Data is to be interpreted as an OmniGraph Bundle
COLOR : Data is to be interpreted as RGB or RGBA color
EXECUTION : Data is to be interpreted as an Action Graph execution pin
FRAME : Data is to be interpreted as a 4x4 matrix representing a reference frame
MATRIX : Data is to be interpreted as a square matrix of values
NONE : Data has no special role
NORMAL : Data is to be interpreted as a normal vector
OBJECT_ID : Data is to be interpreted as a unique object identifier
PATH : Data is to be interpreted as a path to a USD element
POSITION : Data is to be interpreted as a position or point vector
PRIM_TYPE_NAME : Data is to be interpreted as the name of a prim type
QUATERNION : Data is to be interpreted as a rotational quaternion
TARGET : Data is to be interpreted as a relationship target path
TEXCOORD : Data is to be interpreted as texture coordinates
TEXT : Data is to be interpreted as a text string
TIMECODE : Data is to be interpreted as a time code
TRANSFORM : Deprecated
VECTOR : Data is to be interpreted as a simple vector
UNKNOWN : Data role is currently unknown
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
APPLIED_SCHEMA: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.APPLIED_SCHEMA: 11>
BUNDLE: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.BUNDLE: 16>
COLOR: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.COLOR: 4>
EXECUTION: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.EXECUTION: 13>
FRAME: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.FRAME: 8>
MATRIX: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.MATRIX: 14>
NONE: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.NONE: 0>
NORMAL: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.NORMAL: 2>
OBJECT_ID: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.OBJECT_ID: 15>
PATH: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.PATH: 17>
POSITION: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.POSITION: 3>
PRIM_TYPE_NAME: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.PRIM_TYPE_NAME: 12>
QUATERNION: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.QUATERNION: 6>
TARGET: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TARGET: 20>
TEXCOORD: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TEXCOORD: 5>
TEXT: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TEXT: 10>
TIMECODE: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TIMECODE: 9>
TRANSFORM: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TRANSFORM: 7>
UNKNOWN: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.UNKNOWN: 21>
VECTOR: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.VECTOR: 1>
__members__: dict # value = {'APPLIED_SCHEMA': <AttributeRole.APPLIED_SCHEMA: 11>, 'BUNDLE': <AttributeRole.BUNDLE: 16>, 'COLOR': <AttributeRole.COLOR: 4>, 'EXECUTION': <AttributeRole.EXECUTION: 13>, 'FRAME': <AttributeRole.FRAME: 8>, 'MATRIX': <AttributeRole.MATRIX: 14>, 'NONE': <AttributeRole.NONE: 0>, 'NORMAL': <AttributeRole.NORMAL: 2>, 'OBJECT_ID': <AttributeRole.OBJECT_ID: 15>, 'PATH': <AttributeRole.PATH: 17>, 'POSITION': <AttributeRole.POSITION: 3>, 'PRIM_TYPE_NAME': <AttributeRole.PRIM_TYPE_NAME: 12>, 'QUATERNION': <AttributeRole.QUATERNION: 6>, 'TARGET': <AttributeRole.TARGET: 20>, 'TEXCOORD': <AttributeRole.TEXCOORD: 5>, 'TEXT': <AttributeRole.TEXT: 10>, 'TIMECODE': <AttributeRole.TIMECODE: 9>, 'TRANSFORM': <AttributeRole.TRANSFORM: 7>, 'VECTOR': <AttributeRole.VECTOR: 1>, 'UNKNOWN': <AttributeRole.UNKNOWN: 21>}
pass
class AttributeType():
"""
Utilities for operating with the attribute data type class omni.graph.core.Type and related types
"""
@staticmethod
def base_data_size(type: Type) -> int:
"""
Figure out how much space a base data type occupies in memory inside Fabric.
This will not necessarily be the same as the space occupied by the Python data, which is only transient.
Multiply by the tuple count and the array element count to get the full size of any given piece of data.
Args:
type (omni.graph.core.Type): The type object whose base data type size is to be found
Returns:
int: Number of bytes one instance of the base data type occupies in Fabric
"""
@staticmethod
def get_unions() -> dict:
"""
Returns a dictionary containing the names and contents of the ogn attribute union types.
Returns:
dict[str, list[str]]: Dictionary that maps the attribute union names to list of associated ogn types
"""
@staticmethod
def is_legal_ogn_type(type: Type) -> bool:
"""
Check to see if the type combination has a legal representation in OGN.
Args:
type (omni.graph.core.Type): The type object to be checked
Returns:
bool: True if the type represents a legal OGN type, otherwise False
"""
@staticmethod
def sdf_type_name_from_type(type: Type) -> object:
"""
Given an attribute type find the corresponding SDF type name for it, None if there is none, e.g. a 'bundle'
Args:
type (omni.graph.core.Type): The type to be converted
Returns:
str: The SDF type name of the type, or None if there is no corresponding SDF type
"""
@staticmethod
def type_from_ogn_type_name(ogn_type_name: str) -> Type:
"""
Parse an OGN attribute type name into the corresponding omni.graph.core.Type description.
Args:
ogn_type_name (str): The OGN-style attribute type name to be converted
Returns:
omni.graph.core.Type: Type corresponding to the attribute type name in OGN format.
Type object will be the unknown type if the type name could be be parsed.
"""
@staticmethod
def type_from_sdf_type_name(sdf_type_name: str) -> Type:
"""
Parse an SDF attribute type name into the corresponding omni.graph.core.Type description.
Note that SDF types are not capable of representing some of the valid types - use typeFromOgnTypeName()
for a more comprehensive type name description.
Args:
sdf_type_name (str): The SDF-style attribute type name to be converted
Returns:
omni.graph.core.Type: Type corresponding to the attribute type name in SDF format.
Type object will be the unknown type if the type name could be be parsed.
"""
pass
class BaseDataType():
"""
Basic data type for attribute data
Members:
ASSET : Data represents an Asset
BOOL : Data is a boolean
CONNECTION : Data is a special value representing a connection
DOUBLE : Data is a double precision floating point value
FLOAT : Data is a single precision floating point value
HALF : Data is a half precision floating point value
INT : Data is a 32-bit integer
INT64 : Data is a 64-bit integer
PRIM : Data is a reference to a USD prim
RELATIONSHIP : Data is a relationship to a USD prim
TAG : Data is a special Fabric tag
TOKEN : Data is a reference to a unique shared string
UCHAR : Data is an 8-bit unsigned character
UINT : Data is a 32-bit unsigned integer
UINT64 : Data is a 64-bit unsigned integer
UNKNOWN : Data type is currently unknown
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
ASSET: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.ASSET: 12>
BOOL: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.BOOL: 1>
CONNECTION: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.CONNECTION: 14>
DOUBLE: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.DOUBLE: 9>
FLOAT: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.FLOAT: 8>
HALF: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.HALF: 7>
INT: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.INT: 3>
INT64: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.INT64: 5>
PRIM: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.PRIM: 13>
RELATIONSHIP: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.RELATIONSHIP: 11>
TAG: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.TAG: 15>
TOKEN: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.TOKEN: 10>
UCHAR: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.UCHAR: 2>
UINT: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.UINT: 4>
UINT64: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.UINT64: 6>
UNKNOWN: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.UNKNOWN: 0>
__members__: dict # value = {'ASSET': <BaseDataType.ASSET: 12>, 'BOOL': <BaseDataType.BOOL: 1>, 'CONNECTION': <BaseDataType.CONNECTION: 14>, 'DOUBLE': <BaseDataType.DOUBLE: 9>, 'FLOAT': <BaseDataType.FLOAT: 8>, 'HALF': <BaseDataType.HALF: 7>, 'INT': <BaseDataType.INT: 3>, 'INT64': <BaseDataType.INT64: 5>, 'PRIM': <BaseDataType.PRIM: 13>, 'RELATIONSHIP': <BaseDataType.RELATIONSHIP: 11>, 'TAG': <BaseDataType.TAG: 15>, 'TOKEN': <BaseDataType.TOKEN: 10>, 'UCHAR': <BaseDataType.UCHAR: 2>, 'UINT': <BaseDataType.UINT: 4>, 'UINT64': <BaseDataType.UINT64: 6>, 'UNKNOWN': <BaseDataType.UNKNOWN: 0>}
pass
class BucketId():
"""
Internal Use - Unique identifier of the bucket of Fabric data
"""
def __init__(self, id: int) -> None:
"""
Set up the initial value of the bucket id
Args:
id (int): Unique identifier of a bucket of Fabric data
"""
@property
def id(self) -> int:
"""
Internal Use - Unique identifier of a bucket of Fabric data
:type: int
"""
@id.setter
def id(self, arg0: int) -> None:
"""
Internal Use - Unique identifier of a bucket of Fabric data
"""
pass
class BundleChangeType():
"""
Enumeration representing the type of change that occurred in a bundle.
This enumeration is used to identify the kind of modification that has taken place in a bundle or attribute.
It's used as the return type for functions that check bundles and attributes, signaling whether those have been
modified or not.
Members:
NONE : Indicates that no change has occurred in the bundle.
MODIFIED : Indicates that the bundle has been modified.
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
MODIFIED: omni.graph.core._omni_graph_core.BundleChangeType # value = <BundleChangeType.MODIFIED: 1>
NONE: omni.graph.core._omni_graph_core.BundleChangeType # value = <BundleChangeType.NONE: 0>
__members__: dict # value = {'NONE': <BundleChangeType.NONE: 0>, 'MODIFIED': <BundleChangeType.MODIFIED: 1>}
pass
class ComputeGraph():
"""
Main OmniGraph interface registered with the extension system
"""
pass
class ConnectionInfo():
"""
Attribute and connection type in a given graph connection
"""
def __init__(self, attr: Attribute, connection_type: ConnectionType) -> None:
"""
Set up the connection info data
Args:
attr (omni.graph.core.Attribute): Attribute in the connection
connection_type (omni.graph.core.ConnectionType): Type of connection
"""
@property
def attr(self) -> Attribute:
"""
Attribute being connected
:type: Attribute
"""
@attr.setter
def attr(self, arg0: Attribute) -> None:
"""
Attribute being connected
"""
@property
def connection_type(self) -> ConnectionType:
"""
Type of connection
:type: ConnectionType
"""
@connection_type.setter
def connection_type(self, arg0: ConnectionType) -> None:
"""
Type of connection
"""
pass
class ConnectionType():
"""
Type of connection)
Members:
CONNECTION_TYPE_REGULAR : Normal connection
CONNECTION_TYPE_DATA_ONLY : Connection only represents data access, not execution flow
CONNECTION_TYPE_EXECUTION : Connection only represents execution flow, not data access
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CONNECTION_TYPE_DATA_ONLY: omni.graph.core._omni_graph_core.ConnectionType # value = <ConnectionType.CONNECTION_TYPE_DATA_ONLY: 1>
CONNECTION_TYPE_EXECUTION: omni.graph.core._omni_graph_core.ConnectionType # value = <ConnectionType.CONNECTION_TYPE_EXECUTION: 2>
CONNECTION_TYPE_REGULAR: omni.graph.core._omni_graph_core.ConnectionType # value = <ConnectionType.CONNECTION_TYPE_REGULAR: 0>
__members__: dict # value = {'CONNECTION_TYPE_REGULAR': <ConnectionType.CONNECTION_TYPE_REGULAR: 0>, 'CONNECTION_TYPE_DATA_ONLY': <ConnectionType.CONNECTION_TYPE_DATA_ONLY: 1>, 'CONNECTION_TYPE_EXECUTION': <ConnectionType.CONNECTION_TYPE_EXECUTION: 2>}
pass
class ExecutionAttributeState():
"""
Current execution state of an attribute [DEPRECATED: See omni.graph.action.IActionGraph]
Members:
DISABLED : Execution is disabled
ENABLED : Execution is enabled
ENABLED_AND_PUSH : Output attribute connection is enabled and the node is pushed to the evaluation stack
LATENT_PUSH : Push this node as a latent event for the current entry point
LATENT_FINISH : Output attribute connection is enabled and the latent state is finished for this node
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
DISABLED: omni.graph.core._omni_graph_core.ExecutionAttributeState # value = <ExecutionAttributeState.DISABLED: 0>
ENABLED: omni.graph.core._omni_graph_core.ExecutionAttributeState # value = <ExecutionAttributeState.ENABLED: 1>
ENABLED_AND_PUSH: omni.graph.core._omni_graph_core.ExecutionAttributeState # value = <ExecutionAttributeState.ENABLED_AND_PUSH: 2>
LATENT_FINISH: omni.graph.core._omni_graph_core.ExecutionAttributeState # value = <ExecutionAttributeState.LATENT_FINISH: 4>
LATENT_PUSH: omni.graph.core._omni_graph_core.ExecutionAttributeState # value = <ExecutionAttributeState.LATENT_PUSH: 3>
__members__: dict # value = {'DISABLED': <ExecutionAttributeState.DISABLED: 0>, 'ENABLED': <ExecutionAttributeState.ENABLED: 1>, 'ENABLED_AND_PUSH': <ExecutionAttributeState.ENABLED_AND_PUSH: 2>, 'LATENT_PUSH': <ExecutionAttributeState.LATENT_PUSH: 3>, 'LATENT_FINISH': <ExecutionAttributeState.LATENT_FINISH: 4>}
pass
class ExtendedAttributeType():
"""
Extended attribute type, if any
Members:
EXTENDED_ATTR_TYPE_REGULAR : Deprecated: use og.ExtendedAttributeType.REGULAR
EXTENDED_ATTR_TYPE_UNION : Deprecated: use og.ExtendedAttributeType.UNION
EXTENDED_ATTR_TYPE_ANY : Deprecated: use og.ExtendedAttributeType.ANY
REGULAR : Attribute has a fixed data type
UNION : Attribute has a list of allowable types of data
ANY : Attribute can take any type of data
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
ANY: omni.graph.core._omni_graph_core.ExtendedAttributeType # value = <ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY: 2>
EXTENDED_ATTR_TYPE_ANY: omni.graph.core._omni_graph_core.ExtendedAttributeType # value = <ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY: 2>
EXTENDED_ATTR_TYPE_REGULAR: omni.graph.core._omni_graph_core.ExtendedAttributeType # value = <ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: 0>
EXTENDED_ATTR_TYPE_UNION: omni.graph.core._omni_graph_core.ExtendedAttributeType # value = <ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION: 1>
REGULAR: omni.graph.core._omni_graph_core.ExtendedAttributeType # value = <ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: 0>
UNION: omni.graph.core._omni_graph_core.ExtendedAttributeType # value = <ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION: 1>
__members__: dict # value = {'EXTENDED_ATTR_TYPE_REGULAR': <ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: 0>, 'EXTENDED_ATTR_TYPE_UNION': <ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION: 1>, 'EXTENDED_ATTR_TYPE_ANY': <ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY: 2>, 'REGULAR': <ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: 0>, 'UNION': <ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION: 1>, 'ANY': <ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY: 2>}
pass
class FileFormatVersion():
"""
Version number for the OmniGraph file format
"""
def __eq__(self, arg0: FileFormatVersion) -> bool: ...
def __gt__(self, arg0: FileFormatVersion) -> bool: ...
def __init__(self, major_version: int, minor_version: int) -> None:
"""
Set up the values defining the file format version
Args:
major_version (int): Major version, introduces incompatibilities
minor_version (int): Minor version, introduces compatible changes only
"""
def __lt__(self, arg0: FileFormatVersion) -> bool: ...
def __neq__(self, arg0: FileFormatVersion) -> bool: ...
def __str__(self) -> str: ...
@property
def majorVersion(self) -> int:
"""
Major version, introduces incompatibilities
:type: int
"""
@majorVersion.setter
def majorVersion(self, arg0: int) -> None:
"""
Major version, introduces incompatibilities
"""
@property
def minorVersion(self) -> int:
"""
Minor version, introduces compatible changes only
:type: int
"""
@minorVersion.setter
def minorVersion(self, arg0: int) -> None:
"""
Minor version, introduces compatible changes only
"""
__hash__ = None
pass
class Graph():
"""
Object containing everything necessary to execute a connected set of nodes.
"""
def __bool__(self) -> bool: ...
def __eq__(self, arg0: Graph) -> bool: ...
def __hash__(self) -> int: ...
def __repr__(self) -> str: ...
def change_pipeline_stage(self, newPipelineStage: GraphPipelineStage) -> None:
"""
Change the pipeline stage that this graph is in (simulation, pre-render, post-render, on-demand)
Args:
newPipelineStage (omni.graph.core.GraphPipelineStage): The new pipeline stage of the graph
"""
def create_graph_as_node(self, name: str, path: str, evaluator: str, is_global_graph: bool, is_backed_by_usd: bool, backing_type: GraphBackingType, pipeline_stage: GraphPipelineStage, evaluation_mode: GraphEvaluationMode = GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC) -> Node:
"""
Creates a graph that is wrapped by a node in the current graph.
Args:
name (str): The name of the node
path (str): The path to the graph
evaluator (str): The name of the evaluator to use for the graph
is_global_graph (bool): Whether this is a global graph
is_backed_by_usd (bool): Whether the constructs are to be backed by USD
backing_type (omni.graph.core.GraphBackingType): The kind of cache backing this graph
pipeline_stage (omni.graph.core.GraphPipelineStage): What stage in the pipeline the global graph is at
(simulation, pre-render, post-render)
evaluation_mode (omni.graph.core.GraphEvaluationMode): What mode to use when evaluating the graph
Returns:
omni.graph.core.Node: Node wrapping the graph that was created
"""
def create_node(self, path: str, node_type: str, use_usd: bool) -> Node:
"""
Given the path to the node and the type of the node, creates a node of that type at that path.
Args:
path (str): The path to the node
node_type (str): The type of the node
use_usd (bool): Whether or not to create the USD backing for the node
Returns:
omni.graph.core.Node: The newly created node
"""
def create_subgraph(self, subgraphPath: str, evaluator: str = '', createUsd: bool = True) -> Graph:
"""
Given the path to the subgraph, create the subgraph at that path.
Args:
subgraphPath (str): The path to the subgraph
evaluator (str): The evaluator type
createUsd (bool): Whether or not to create the USD backing for the node
Returns:
omni.graph.core.Graph: Subgraph object created for the given path.
"""
@staticmethod
def create_variable(*args, **kwargs) -> typing.Any:
"""
Creates a variable on the graph.
Args:
name (str): The name of the variable
type (omni.graph.core.Type): The type of the variable to create.
Returns:
omni.graph.core.IVariable: A reference to the newly created variable, or None if the variable could not be created.
"""
def deregister_error_status_change_callback(self, status_change_handle: int) -> None:
"""
De-registers the error status change callback to be invoked when the error status of nodes change during evaluation.
Args:
status_change_handle (int): The handle that was returned during the register_error_status_change_callback call
"""
def destroy_node(self, node_path: str, update_usd: bool) -> bool:
"""
Given the path to the node, destroys the node at that path.
Args:
node_path (str): The path to the node
update_usd (bool): Whether or not to destroy the USD backing for the node
Returns:
bool: True if the node was successfully destroyed
"""
def evaluate(self) -> None:
"""
Tick the graph by causing it to evaluate.
"""
def find_variable(self, name: str) -> IVariable:
"""
Find the variable with the given name in the graph.
Args:
name (str): The name of the variable to find.
Returns:
omni.graph.core.IVariable | None: The variable with the given name, or None if not found.
"""
@staticmethod
def get_context(*args, **kwargs) -> typing.Any:
"""
Gets the context associated to the graph
Returns:
omni.graph.core.GraphContext: The context associated to the graph
"""
@staticmethod
def get_default_graph_context(*args, **kwargs) -> typing.Any:
"""
Gets the default context associated with this graph
Returns:
omni.graph.core.GraphContext: The default graph context associated with this graph.
"""
def get_evaluator_name(self) -> str:
"""
Gets the name of the evaluator being used on this graph
Returns:
str: The name of the graph evaluator (dirty_push, push, execution)
"""
def get_event_stream(self) -> carb.events._events.IEventStream:
"""
Get the event stream the graph uses for notification of changes.
Returns:
carb.events.IEventStream: Event stream to monitor for graph changes
"""
def get_graph_backing_type(self) -> GraphBackingType:
"""
Gets the data type backing this graph
Returns:
omni.graph.core.GraphBackingType: Returns the type of data structure backing this graph
"""
def get_handle(self) -> int:
"""
Gets a unique handle identifier for this graph
Returns:
int: Unique handle identifier for this graph
"""
def get_instance_count(self) -> int:
"""
Gets the number of instances this graph has
Returns:
int: The number of instances the graph has (0 if the graph is standalone).
"""
def get_node(self, path: str) -> Node:
"""
Given a path to the node, returns the object for the node.
Args:
path (str): The path to the node
Returns:
omni.graph.core.Node: Node object for the given path, None if it does not exist
"""
def get_nodes(self) -> typing.List[Node]:
"""
Gets the list of nodes currently in this graph
Returns:
list[omni.graph.core.Node]: The nodes in this graph.
"""
def get_owning_compound_node(self) -> Node:
"""
Returns the compound node for which this graph is the compound subgraph of.
Returns:
(og.Node) If this graph is a compound graph, the owning compound node. Otherwise, this an invalid node is returned.
"""
def get_parent_graph(self) -> object:
"""
Gets the immediate parent graph of this graph
Returns:
omni.graph.core.Graph | None: The immediate parent graph of this graph (may be None)
"""
def get_path_to_graph(self) -> str:
"""
Gets the path to this graph
Returns:
str: The path to this graph (may be empty).
"""
def get_pipeline_stage(self) -> GraphPipelineStage:
"""
Gets the pipeline stage to which this graph belongs
Returns:
omni.graph.core.PipelineStage: The type of pipeline stage of this graph (simulation, pre-render, post-render)
"""
def get_subgraph(self, path: str) -> Graph:
"""
Gets the subgraph living at the given path below this graph
Args:
path (str): Path to the subgraph to find
Returns:
omni.graph.core.Graph | None: Subgraph at the path, or None if not found
"""
def get_subgraphs(self) -> typing.List[Graph]:
"""
Gets the list of subgraphs under this graph
Returns:
list[omni.graph.core.Graph]: List of graphs that are subgraphs of this graph
"""
def get_variables(self) -> typing.List[IVariable]:
"""
Returns the list of variables defined on the graph.
Returns:
list[omni.graph.core.IVariable]: The current list of variables on the graph.
"""
def inspect(self, inspector: omni.inspect._omni_inspect.IInspector) -> bool:
"""
Runs the inspector on the graph
Args:
inspector (omni.inspect.Inspector): The inspector to run
Returns:
bool: True if the inspector was successfully run on the graph, False if it is not supported
"""
def is_auto_instanced(self) -> bool:
"""
Returns whether this graph is an auto instance or not. An auto instance is a graph that got merged as an instance with all other similar graphs in the stage.
Returns:
bool: True if this graph is an auto instance
"""
def is_compound_graph(self) -> bool:
"""
Returns whether this graph is a compound graph. A compound graph is subgraph that controlled by a compound node.
Returns:
bool: True if this graph is a compound graph
"""
def is_disabled(self) -> bool:
"""
Checks to see if the graph is disabled
Returns:
bool: True if this graph object is disabled.
"""
def is_valid(self) -> bool:
"""
Checks to see if the graph object is valid
Returns:
bool: True if this graph object is valid.
"""
def register_error_status_change_callback(self, callback: object) -> int:
"""
Registers a callback to be invoked after graph evaluation for all the nodes whose error status changed
during the evaluation. The callback receives a list of the nodes whose error status changed.
Args:
callback (callable): The callback function
Returns:
int: A handle that can be used for deregistration. Note the calling module is responsible for deregistration
of the callback in all circumstances, including where the extension is hot-reloaded.
"""
def reload_from_stage(self) -> None:
"""
Force the graph to reload by deleting it and re-parsing from the stage.
This is potentially destructive if you have internal state information in any nodes.
"""
def reload_settings(self) -> None:
"""
Reload the graph settings.
"""
def remove_variable(self, variable: IVariable) -> bool:
"""
Removes the given variable from the graph.
Args:
variable (omni.graph.core.IVariable): The variable to remove.
Returns:
bool: True if the variable was successfully removed, False otherwise.
"""
def rename_node(self, path: str, new_path: str) -> bool:
"""
Given the path to the node, renames the node at that path.
Args:
path (str): The path to the node
new_path (str): The new path
Returns:
bool: True if the node was successfully renamed
"""
def rename_subgraph(self, path: str, new_path: str) -> bool:
"""
Renames the path of a subgraph
Args:
path (str): Path to the subgraph being renamed
new_path (str): New path for the subgraph
"""
def set_auto_instancing_allowed(self, arg0: bool) -> bool:
"""
Allows (or not) this graph to be an auto-instance, ie. to be executed vectorized as an instance amongst all other identical graph
Args:
allowed (bool): Whether this graph is allowed to be an auto instance.
Returns:
bool: Whether this graph was allowed to be an auto instance before this call.
"""
def set_disabled(self, disable: bool) -> None:
"""
Sets whether this graph object is to be disabled or not.
Args:
disable (bool): True if the graph is to be disabled
"""
def set_usd_notice_handling_enabled(self, enable: bool) -> None:
"""
Sets whether this graph object has USD notice handling enabled.
Args:
enable (bool): True to enable USD notice handling, False to disable.
"""
def usd_notice_handling_enabled(self) -> bool:
"""
Checks whether this graph has USD notice handling enabled.
Returns:
bool: True if USD notice handling is enabled on this graph.
"""
@property
def evaluation_mode(self) -> GraphEvaluationMode:
"""
omni.graph.core.GraphEvaluationMode: The evaluation mode sets how the graph will be evaluated.
GRAPH_EVALUATION_MODE_AUTOMATIC - Evaluate the graph in Standalone mode when there are no relationships to it,
otherwise it will be evaluated in Instanced mode.
GRAPH_EVALUATION_MODE_STANDALONE - Evaluates the graph with the graph Prim as the graph target, and ignore Prims with relationships
to the graph Prim. Use this mode when constructing self-contained graphs that evaluate independently.
GRAPH_EVALUATION_MODE_INSTANCED - Evaluates only when the graph there are relationships from OmniGraphAPI interfaces. Each Prim with
a relationship to the graph Prim will cause an evaluation, with the Graph Target set to path of Prim with the OmniGraphAPI interface.
Use this mode when the graph represents as an asset or template that can be applied to multiple Prims.
:type: GraphEvaluationMode
"""
@evaluation_mode.setter
def evaluation_mode(self, arg1: GraphEvaluationMode) -> None:
"""
omni.graph.core.GraphEvaluationMode: The evaluation mode sets how the graph will be evaluated.
GRAPH_EVALUATION_MODE_AUTOMATIC - Evaluate the graph in Standalone mode when there are no relationships to it,
otherwise it will be evaluated in Instanced mode.
GRAPH_EVALUATION_MODE_STANDALONE - Evaluates the graph with the graph Prim as the graph target, and ignore Prims with relationships
to the graph Prim. Use this mode when constructing self-contained graphs that evaluate independently.
GRAPH_EVALUATION_MODE_INSTANCED - Evaluates only when the graph there are relationships from OmniGraphAPI interfaces. Each Prim with
a relationship to the graph Prim will cause an evaluation, with the Graph Target set to path of Prim with the OmniGraphAPI interface.
Use this mode when the graph represents as an asset or template that can be applied to multiple Prims.
"""
pass
class GraphBackingType():
"""
Location of the data backing the graph
Members:
GRAPH_BACKING_TYPE_FLATCACHE_SHARED : Deprecated: Use GRAPH_BACKING_TYPE_FABRIC_SHARED
GRAPH_BACKING_TYPE_FLATCACHE_WITH_HISTORY : Deprecated: Use GRAPH_BACKING_TYPE_FABRIC_WITH_HISTORY
GRAPH_BACKING_TYPE_FLATCACHE_WITHOUT_HISTORY : Deprecated: Use GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY
GRAPH_BACKING_TYPE_FABRIC_SHARED : Data is a regular Fabric instance
GRAPH_BACKING_TYPE_FABRIC_WITH_HISTORY : Data is a Fabric instance without any history
GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY : Data is a Fabric instance with a ring buffer of history
GRAPH_BACKING_TYPE_NONE : No data is stored for the graph
GRAPH_BACKING_TYPE_UNKNOWN : The data backing is not currently known
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
GRAPH_BACKING_TYPE_FABRIC_SHARED: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED: 0>
GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITHOUT_HISTORY: 2>
GRAPH_BACKING_TYPE_FABRIC_WITH_HISTORY: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITH_HISTORY: 1>
GRAPH_BACKING_TYPE_FLATCACHE_SHARED: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED: 0>
GRAPH_BACKING_TYPE_FLATCACHE_WITHOUT_HISTORY: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITHOUT_HISTORY: 2>
GRAPH_BACKING_TYPE_FLATCACHE_WITH_HISTORY: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITH_HISTORY: 1>
GRAPH_BACKING_TYPE_NONE: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_NONE: 4>
GRAPH_BACKING_TYPE_UNKNOWN: omni.graph.core._omni_graph_core.GraphBackingType # value = <GraphBackingType.GRAPH_BACKING_TYPE_UNKNOWN: 3>
__members__: dict # value = {'GRAPH_BACKING_TYPE_FLATCACHE_SHARED': <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED: 0>, 'GRAPH_BACKING_TYPE_FLATCACHE_WITH_HISTORY': <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITH_HISTORY: 1>, 'GRAPH_BACKING_TYPE_FLATCACHE_WITHOUT_HISTORY': <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITHOUT_HISTORY: 2>, 'GRAPH_BACKING_TYPE_FABRIC_SHARED': <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED: 0>, 'GRAPH_BACKING_TYPE_FABRIC_WITH_HISTORY': <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITH_HISTORY: 1>, 'GRAPH_BACKING_TYPE_FABRIC_WITHOUT_HISTORY': <GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_WITHOUT_HISTORY: 2>, 'GRAPH_BACKING_TYPE_NONE': <GraphBackingType.GRAPH_BACKING_TYPE_NONE: 4>, 'GRAPH_BACKING_TYPE_UNKNOWN': <GraphBackingType.GRAPH_BACKING_TYPE_UNKNOWN: 3>}
pass
class GraphContext():
"""
Execution context for a graph
"""
def __bool__(self) -> bool: ...
def __eq__(self, arg0: GraphContext) -> bool: ...
def __hash__(self) -> int: ...
def get_attribute_as_bool(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> bool:
"""
get_attribute_as_bool is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_boolarray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[bool]:
"""
get_attribute_as_boolarray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_double(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> float:
"""
get_attribute_as_double is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_doublearray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.float64]:
"""
get_attribute_as_doublearray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_float(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> float:
"""
get_attribute_as_float is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_floatarray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.float32]:
"""
get_attribute_as_floatarray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_half(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> float:
"""
get_attribute_as_half is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_halfarray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.float32]:
"""
get_attribute_as_halfarray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_int(self, arg0: Attribute, arg1: bool, arg2: bool, arg3: int) -> int:
"""
get_attribute_as_int is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_int64(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> int:
"""
get_attribute_as_int64 is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_int64array(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.int64]:
"""
get_attribute_as_int64array is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_intarray(self, arg0: Attribute, arg1: bool, arg2: bool, arg3: int) -> numpy.ndarray[numpy.int32]:
"""
get_attribute_as_intarray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_nested_doublearray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.float64]:
"""
get_attribute_as_nested_doublearray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_nested_floatarray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.float32]:
"""
get_attribute_as_nested_floatarray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_nested_halfarray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.float32]:
"""
get_attribute_as_nested_halfarray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_nested_intarray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.int32]:
"""
get_attribute_as_nested_intarray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_string(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> str:
"""
get_attribute_as_string is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_uchar(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> int:
"""
get_attribute_as_uchar is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_uchararray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.uint8]:
"""
get_attribute_as_uchararray is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_uint(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> int:
"""
get_attribute_as_uint is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_uint64(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> int:
"""
get_attribute_as_uint64 is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_uint64array(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.uint64]:
"""
get_attribute_as_uint64array is deprecated. Use og.Controller.get() instead.
"""
def get_attribute_as_uintarray(self, attribute: Attribute, getDefault: bool = False, write: bool = False, writeElemCount: int = 0) -> numpy.ndarray[numpy.uint32]:
"""
get_attribute_as_uintarray is deprecated. Use og.Controller.get() instead.
"""
def get_bundle(self, path: str) -> IBundle2:
"""
Get the bundle object as read-write.
Args:
path (str): the path to the bundle
Returns:
omni.graph.core.IBundle2: The bundle object at the path, None if there isn't one
"""
def get_elapsed_time(self) -> float:
"""
Returns the time between last evaluation of the graph and "now"
Returns:
float: the elapsed time
"""
@staticmethod
@typing.overload
def get_elem_count(*args, **kwargs) -> typing.Any:
"""
get_elem_count is deprecated. Use og.Controller.get_array_size() instead.
get_elem_count is deprecated. Use og.Controller.get_array_size() instead.
"""
@typing.overload
def get_elem_count(self, arg0: Attribute) -> int: ...
def get_frame(self) -> float:
"""
Returns the global playback time in frames
Returns:
float: the global playback time in frames
"""
def get_graph(self) -> Graph:
"""
Gets the graph associated with this graph context
Returns:
omni.graph.core.Graph: The graph associated with this graph context.
"""
def get_graph_target(self, index: int = 18446744073709551614) -> str:
"""
Get the Prim path of the graph target.
The graph target is defined as the parent Prim of the compute graph, except during
instancing - where OmniGraph executes a graph once for each Prim. In the case
of instancing, the graph target will change at each execution to be the path of the instance.
If this is called outside of graph execution, the path of the graph Prim is returned, or an empty
token if the graph does not have a Prim associated with it.
Args:
index (int): The index of instance to fetch. By default, the graph context index is used.
Returns:
str: The prim path of the current graph target.
"""
@typing.overload
def get_input_bundle(self, path: str) -> IConstBundle2:
"""
Get the bundle object as read only.
Args:
path (str): the path to the bundle
Returns:
omni.graph.core.IBundle2: The bundle object at the path, None if there isn't one
Get a bundle object that is an input attribute.
Args:
node (omni.graph.core.Node): the node on which the bundle can be found
attribute_name (str): the name of the input attribute
instance (int): an instance index when getting value on an instantiated graph
Returns:
omni.graph.core.IConstBundle2: The bundle object at the path, None if there isn't one
"""
@typing.overload
def get_input_bundle(self, node: Node, attribute_name: str, instance: int = 18446744073709551614) -> IConstBundle2: ...
def get_input_target_bundles(self, node: Node, attribute_name: str, instance: int = 18446744073709551614) -> typing.List[IConstBundle2]:
"""
Get all input targets in the relationship with the given name on the specified compute node.
The targets are returned as bundle objects.
Args:
node (omni.graph.core.Node): the node on which the input targets can be found
attribute_name (str): the name of the relationship attribute
instance (int): an instance index when getting value on an instantiated graph
Returns:
list[omni.graph.core.IConstBundle2]: The list of input targets, as bundle objects.
"""
def get_is_playing(self) -> bool:
"""
Returns the state of global playback
Returns:
bool: True if playback has started, False is playback is stopped
"""
@typing.overload
def get_output_bundle(self, path: str) -> IBundle2:
"""
Get a bundle object that is an output attribute.
Args:
path (str): the path to the bundle
Returns:
omni.graph.core.IBundle2: The bundle object at the path, None if there isn't one
Get a bundle object that is an output attribute.
Args:
node (omni.graph.core.Node): the node on which the bundle can be found
attribute_name (str): the name of the output attribute
instance (int): an instance index when getting value on an instantiated graph
Returns:
omni.graph.core.IBundle2: The bundle object at the path, None if there isn't one
"""
@typing.overload
def get_output_bundle(self, node: Node, attribute_name: str, instance: int = 18446744073709551614) -> IBundle2: ...
def get_time(self) -> float:
"""
Returns the global playback time
Returns:
float: the global playback time in seconds
"""
def get_time_since_start(self) -> float:
"""
Returns the elapsed time since the app started
Returns:
float: the number of seconds since the app started in seconds
"""
def inspect(self, inspector: omni.inspect._omni_inspect.IInspector) -> bool:
"""
Runs the inspector on the graph context
Args:
inspector (omni.inspect.Inspector): The inspector to run
Returns:
bool: True if the inspector was successfully run on the context, False if it is not supported
"""
def is_valid(self) -> bool:
"""
Checks to see if this graph context object is valid
Returns:
bool: True if this object is valid
"""
def set_bool_attribute(self, arg0: bool, arg1: Attribute) -> None:
"""
set_bool_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_boolarray_attribute(self, arg0: typing.List[bool], arg1: Attribute) -> None:
"""
set_boolarray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_double_attribute(self, arg0: float, arg1: Attribute) -> None:
"""
set_double_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_double_matrix_attribute(self, arg0: typing.List[float], arg1: Attribute) -> None:
"""
set_double_matrix_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_doublearray_attribute(self, arg0: typing.List[float], arg1: Attribute) -> None:
"""
set_doublearray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_float_attribute(self, arg0: float, arg1: Attribute) -> None:
"""
set_float_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_floatarray_attribute(self, arg0: typing.List[float], arg1: Attribute) -> None:
"""
set_floatarray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_half_attribute(self, arg0: float, arg1: Attribute) -> None:
"""
set_half_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_halfarray_attribute(self, arg0: typing.List[float], arg1: Attribute) -> None:
"""
set_halfarray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_int64_attribute(self, arg0: int, arg1: Attribute) -> None:
"""
set_int64_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_int64array_attribute(self, arg0: typing.List[int], arg1: Attribute) -> None:
"""
set_int64array_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_int_attribute(self, arg0: int, arg1: Attribute) -> None:
"""
set_int_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_intarray_attribute(self, arg0: typing.List[int], arg1: Attribute) -> None:
"""
set_intarray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_nested_doublearray_attribute(self, arg0: typing.List[typing.List[float]], arg1: Attribute) -> None:
"""
set_nested_doublearray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_nested_floatarray_attribute(self, arg0: typing.List[typing.List[float]], arg1: Attribute) -> None:
"""
set_nested_floatarray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_nested_halfarray_attribute(self, arg0: typing.List[typing.List[float]], arg1: Attribute) -> None:
"""
set_nested_halfarray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_nested_intarray_attribute(self, arg0: typing.List[typing.List[int]], arg1: Attribute) -> None:
"""
set_nested_intarray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_string_attribute(self, arg0: str, arg1: Attribute) -> None:
"""
set_string_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_uchar_attribute(self, arg0: int, arg1: Attribute) -> None:
"""
set_uchar_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_uchararray_attribute(self, arg0: typing.List[int], arg1: Attribute) -> None:
"""
set_uchararray_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_uint64_attribute(self, arg0: int, arg1: Attribute) -> None:
"""
set_uint64_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_uint64array_attribute(self, arg0: typing.List[int], arg1: Attribute) -> None:
"""
set_uint64array_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_uint_attribute(self, arg0: int, arg1: Attribute) -> None:
"""
set_uint_attribute is deprecated. Use og.Controller.set() instead.
"""
def set_uintarray_attribute(self, arg0: typing.List[int], arg1: Attribute) -> None:
"""
set_uintarray_attribute is deprecated. Use og.Controller.set() instead.
"""
@staticmethod
def write_bucket_to_backing(*args, **kwargs) -> typing.Any:
"""
Forces the given bucket to be written to the backing storage. Raises ValueError if the bucket could not be found.
Args:
bucket_id (int): The bucket id of the bucket to be written
"""
pass
class GraphEvaluationMode():
"""
How the graph evaluation is scheduled
Members:
GRAPH_EVALUATION_MODE_AUTOMATIC : Evaluation is scheduled based on graph type
GRAPH_EVALUATION_MODE_STANDALONE : Evaluation is scheduled as a single graph
GRAPH_EVALUATION_MODE_INSTANCED : Evaluation is scheduled by instances
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
GRAPH_EVALUATION_MODE_AUTOMATIC: omni.graph.core._omni_graph_core.GraphEvaluationMode # value = <GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC: 0>
GRAPH_EVALUATION_MODE_INSTANCED: omni.graph.core._omni_graph_core.GraphEvaluationMode # value = <GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED: 2>
GRAPH_EVALUATION_MODE_STANDALONE: omni.graph.core._omni_graph_core.GraphEvaluationMode # value = <GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE: 1>
__members__: dict # value = {'GRAPH_EVALUATION_MODE_AUTOMATIC': <GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC: 0>, 'GRAPH_EVALUATION_MODE_STANDALONE': <GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE: 1>, 'GRAPH_EVALUATION_MODE_INSTANCED': <GraphEvaluationMode.GRAPH_EVALUATION_MODE_INSTANCED: 2>}
pass
class GraphEvent():
"""
Graph modification event.
Members:
CREATE_VARIABLE : Variable was created
REMOVE_VARIABLE : Variable was removed
VARIABLE_TYPE_CHANGE : Variable type was changed
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CREATE_VARIABLE: omni.graph.core._omni_graph_core.GraphEvent # value = <GraphEvent.CREATE_VARIABLE: 0>
REMOVE_VARIABLE: omni.graph.core._omni_graph_core.GraphEvent # value = <GraphEvent.REMOVE_VARIABLE: 1>
VARIABLE_TYPE_CHANGE: omni.graph.core._omni_graph_core.GraphEvent # value = <GraphEvent.VARIABLE_TYPE_CHANGE: 5>
__members__: dict # value = {'CREATE_VARIABLE': <GraphEvent.CREATE_VARIABLE: 0>, 'REMOVE_VARIABLE': <GraphEvent.REMOVE_VARIABLE: 1>, 'VARIABLE_TYPE_CHANGE': <GraphEvent.VARIABLE_TYPE_CHANGE: 5>}
pass
class GraphPipelineStage():
"""
Pipeline stage in which the graph lives
Members:
GRAPH_PIPELINE_STAGE_SIMULATION : The regular evaluation stage
GRAPH_PIPELINE_STAGE_PRERENDER : The stage that evaluates just before rendering
GRAPH_PIPELINE_STAGE_POSTRENDER : The stage that evaluates just after rendering
GRAPH_PIPELINE_STAGE_ONDEMAND : The stage evaluating only when requested
GRAPH_PIPELINE_STAGE_UNKNOWN : The stage is not currently known
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
GRAPH_PIPELINE_STAGE_ONDEMAND: omni.graph.core._omni_graph_core.GraphPipelineStage # value = <GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND: 200>
GRAPH_PIPELINE_STAGE_POSTRENDER: omni.graph.core._omni_graph_core.GraphPipelineStage # value = <GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER: 30>
GRAPH_PIPELINE_STAGE_PRERENDER: omni.graph.core._omni_graph_core.GraphPipelineStage # value = <GraphPipelineStage.GRAPH_PIPELINE_STAGE_PRERENDER: 20>
GRAPH_PIPELINE_STAGE_SIMULATION: omni.graph.core._omni_graph_core.GraphPipelineStage # value = <GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION: 10>
GRAPH_PIPELINE_STAGE_UNKNOWN: omni.graph.core._omni_graph_core.GraphPipelineStage # value = <GraphPipelineStage.GRAPH_PIPELINE_STAGE_UNKNOWN: 100>
__members__: dict # value = {'GRAPH_PIPELINE_STAGE_SIMULATION': <GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION: 10>, 'GRAPH_PIPELINE_STAGE_PRERENDER': <GraphPipelineStage.GRAPH_PIPELINE_STAGE_PRERENDER: 20>, 'GRAPH_PIPELINE_STAGE_POSTRENDER': <GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER: 30>, 'GRAPH_PIPELINE_STAGE_ONDEMAND': <GraphPipelineStage.GRAPH_PIPELINE_STAGE_ONDEMAND: 200>, 'GRAPH_PIPELINE_STAGE_UNKNOWN': <GraphPipelineStage.GRAPH_PIPELINE_STAGE_UNKNOWN: 100>}
pass
class GraphRegistry():
"""
Manager of the node types registered to OmniGraph.
"""
def __init__(self) -> None: ...
def get_event_stream(self) -> carb.events._events.IEventStream:
"""
Get the event stream for the graph registry change notification.
The events that are raised are specified by GraphRegistryEvent. The payload for the
added and removed events is the name of the node type being added or removed, and uses
the key "node_type".
Returns:
carb.events.IEventStream: Event stream to monitor for graph registry changes
"""
def get_node_type_version(self, node_type_name: str) -> int:
"""
Finds the version number of the given node type.
Args:
node_type_name (str): Name of the node type to check
Returns:
int: Version number registered for the node type, None if it is not registered
"""
def inspect(self, inspector: omni.inspect._omni_inspect.IInspector) -> bool:
"""
Runs the inspector on the graph registry
Args:
inspector (omni.inspect.Inspector): The inspector to run
Returns:
bool: True if the inspector was successfully run on the graph registry, False if it is not supported
"""
pass
class GraphRegistryEvent():
"""
Graph Registry modification event.
Members:
NODE_TYPE_ADDED : Node type was registered
NODE_TYPE_REMOVED : Node type was deregistered
NODE_TYPE_NAMESPACE_CHANGED : Namespace of a node type changed
NODE_TYPE_CATEGORY_CHANGED : Category of a node type changed
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
NODE_TYPE_ADDED: omni.graph.core._omni_graph_core.GraphRegistryEvent # value = <GraphRegistryEvent.NODE_TYPE_ADDED: 0>
NODE_TYPE_CATEGORY_CHANGED: omni.graph.core._omni_graph_core.GraphRegistryEvent # value = <GraphRegistryEvent.NODE_TYPE_CATEGORY_CHANGED: 3>
NODE_TYPE_NAMESPACE_CHANGED: omni.graph.core._omni_graph_core.GraphRegistryEvent # value = <GraphRegistryEvent.NODE_TYPE_NAMESPACE_CHANGED: 2>
NODE_TYPE_REMOVED: omni.graph.core._omni_graph_core.GraphRegistryEvent # value = <GraphRegistryEvent.NODE_TYPE_REMOVED: 1>
__members__: dict # value = {'NODE_TYPE_ADDED': <GraphRegistryEvent.NODE_TYPE_ADDED: 0>, 'NODE_TYPE_REMOVED': <GraphRegistryEvent.NODE_TYPE_REMOVED: 1>, 'NODE_TYPE_NAMESPACE_CHANGED': <GraphRegistryEvent.NODE_TYPE_NAMESPACE_CHANGED: 2>, 'NODE_TYPE_CATEGORY_CHANGED': <GraphRegistryEvent.NODE_TYPE_CATEGORY_CHANGED: 3>}
pass
class IBundle2(_IBundle2, IConstBundle2, _IConstBundle2, omni.core._core.IObject):
"""
Provide read write access to recursive bundles.
"""
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@staticmethod
def add_attribute(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use create_attribute() instead.
"""
@staticmethod
def add_attributes(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use create_attributes() instead.
"""
def clear(self) -> None:
"""
DEPRECATED - use clear_contents() instead
"""
def clear_contents(self, bundle_metadata: bool = True, attributes: bool = True, child_bundles: bool = True) -> int:
"""
Removes all attributes and child bundles from this bundle, but keeps the bundle itself.
Args:
bundle_metadata (bool): Clears bundle metadata in this bundle.
attributes (bool): Clears attributes in this bundle.
child_bundles (bool): Clears child bundles in this bundle.
Returns:
omni.core.Result: Success if successfully cleared.
"""
@staticmethod
def copy_attribute(*args, **kwargs) -> typing.Any:
"""
Create new attribute by copying existing one, including its data.
Created attribute is owned by this bundle.
Args:
attribute (omni.graph.core.AttributeData): Attribute whose data type is to be copied.
overwrite (bool): Overwrite existing attribute in this bundle.
Returns:
omni.graph.core.AttributeData: Copied attribute.
Create new attribute by copying existing one, including its data.
Created attribute is owned by this bundle.
Args:
name (str): The new name for copied attribute.
attribute (omni.graph.core.AttributeData): Attribute whose data type is to be copied.
overwrite (bool): Overwrite existing attribute in this bundle.
Returns:
omni.graph.core.AttributeData: Copied attribute.
"""
@staticmethod
def copy_attributes(*args, **kwargs) -> typing.Any:
"""
Create new attributes by copying existing ones, including their data.
Names of new attributes are taken from source attributes.
Created attributes are owned by this bundle.
Args:
attributes (list[omni.graph.core.AttributeData]): Attributes whose data type is to be copied.
overwrite (bool): Overwrite existing attributes in this bundle.
Returns:
list[omni.graph.core.AttributeData]: A list of copied attributes.\
Create new attributes by copying existing ones, including their data, with possibility of giving them new names.
Created attributes are owned by this bundle.
Args:
names (list[str]): Names for the new attributes.
attributes (list[omni.graph.core.AttributeData]): Attributes whose data type is to be copied.
overwrite (bool): Overwrite existing attributes in this bundle.
Returns:
list[omni.graph.core.AttributeData]: A list of copied attributes.
"""
def copy_bundle(self, source_bundle: IConstBundle2, overwrite: bool = True) -> None:
"""
Copy bundle data and metadata from the source bundle to this bundle.
Args:
source_bundle (omni.graph.core.IConstBundle2): Bundle whose data is to be copied.
overwrite (bool): Overwrite existing content of the bundle.
"""
@typing.overload
def copy_child_bundle(self, bundle: IConstBundle2, name: typing.Optional[str] = None) -> IBundle2:
"""
Create new child bundle by copying existing one, with possibility of giving child a new name.
Created bundle is owned by this bundle.
Args:
bundle (omni.graph.core.IConstBundle2): Bundle whose data is to be copied.
name (str): Name of new child.
Returns:
omni.graph.core.IBundle2: Newly copied bundle.
Create new child bundle by copying existing one, with possibility of giving child a new name.
Created bundle is owned by this bundle.
Args:
name (str): Name of new child.
bundle (omni.graph.core.IConstBundle2): Bundle whose data is to be copied.
Returns:
omni.graph.core.IBundle2: Newly copied bundle.
"""
@typing.overload
def copy_child_bundle(self, name: str, bundle: IConstBundle2) -> IBundle2: ...
@typing.overload
def copy_child_bundles(self, bundles: typing.List[IConstBundle2], names: typing.Optional[typing.List[str]] = None) -> typing.List[IBundle2]:
"""
Create new child bundles by copying existing ones, with possibility of giving children new names.
Created bundles are owned by this bundle.
Args:
bundles (list[omni.graph.core.IConstBundle2]): Bundles whose data is to be copied.
names (list[str]): Names of new children.
Returns:
list[omni.graph.core.IBundle2]: Newly copied bundles.
Create new child bundles by copying existing ones, with possibility of giving children new names.
Created bundles are owned by this bundle.
Args:
names (list[str]): Names of new children.
bundles (list[omni.graph.core.IConstBundle2]): Bundles whose data is to be copied.
Returns:
list[omni.graph.core.IBundle2]: Newly copied bundles.
"""
@typing.overload
def copy_child_bundles(self, names: typing.List[str], bundles: typing.List[IConstBundle2]) -> typing.List[IBundle2]: ...
@staticmethod
def create_attribute(*args, **kwargs) -> typing.Any:
"""
Creates attribute based on provided name and type.
Created attribute is owned by this bundle.
Args:
name (str): Name of the attribute.
type (omni.graph.core.Type): Type of the attribute.
element_count (int): Number of elements in the array.
Returns:
omni.graph.core.AttributeData: Newly created attribute.
"""
@staticmethod
def create_attribute_like(*args, **kwargs) -> typing.Any:
"""
Use input attribute as pattern to create attribute in this bundle.
The name and type are taken from pattern attribute, data is not copied.
Created attribute is owned by this bundle.
Args:
pattern_attribute (omni.graph.core.AttributeData): Attribute whose name and type is to be used to create new attribute.
Returns:
omni.graph.core.AttributeData: Newly created attribute.
"""
@staticmethod
def create_attribute_metadata(*args, **kwargs) -> typing.Any:
"""
Create attribute metadata fields.
Args:
attribute (str): Name of the attribute.
field_names (list[str]): Names of new metadata field.
field_types (list[omni.graph.core.Type]): Types of new metadata field.
element_count (int): Number of elements in the arrray.
Returns:
list[omni.graph.core.AttributeData]: Newly created metadata fields.
Create attribute metadata field.
Args:
attribute (str): Name of the attribute.
field_name (str): Name of new metadata field.
field_type (omni.graph.core.Type): Type of new metadata field.
Returns:
omni.graph.core.AttributeData: Newly created metadata field.
"""
@staticmethod
def create_attributes(*args, **kwargs) -> typing.Any:
"""
Creates attributes based on provided names and types.
Created attributes are owned by this bundle.
Args:
names (list[str]): Names of the attributes.
types (list[omni.graph.core.Type]): Types of the attributes.
Returns:
list[omni.graph.core.AttributeData]: A list of created attributes.
"""
@staticmethod
def create_attributes_like(*args, **kwargs) -> typing.Any:
"""
Use input attributes as pattern to create attributes in this bundle.
Names and types for new attributes are taken from pattern attributes, data is not copied.
Created attributes are owned by this bundle.
Args:
pattern_attributes (list[omni.graph.core.AttributeData]): Attributes whose name and type is to be used to create new attributes.
Returns:
list[omni.graph.core.AttributeData]: A list of newly created attributes.
"""
@staticmethod
def create_bundle_metadata(*args, **kwargs) -> typing.Any:
"""
Creates bundle metadata fields based on provided names and types.
Created fields are owned by this bundle.
Args:
field_names (list[str]): Names of the fields.
field_types (list[omni.graph.core.Type]): Types of the fields.
element_count (int): Number of elements in the arrray.
Returns:
list[omni.graph.core.AttributeData]: A list of created fields.
Creates bundle metadata field based on provided name and type.
Created field are owned by this bundle.
Args:
field_name (str): Name of the field.
field_type (omni.graph.core.Type): Type of the field.
Returns:
omni.graph.core.AttributeData: Created field.
"""
def create_child_bundle(self, path: str) -> IBundle2:
"""
Creates immediate child bundle under specified path in this bundle.
Created bundle is owned by this bundle.
This method does not work recursively. Only immediate child can be created.
Args:
path (str): New child path in this bundle.
Returns:
omni.graph.core.IBundle2: Created child bundle.
"""
def create_child_bundles(self, paths: typing.List[str]) -> typing.List[IBundle2]:
"""
Creates immediate child bundles under specified paths in this bundle.
Created bundles are owned by this bundle.
This method does not work recursively. Only immediate children can be created.
Args:
paths (list[str]): New children paths in this bundle.
Returns:
list[omni.graph.core.IBundle2]: A list of created child bundles.
"""
@staticmethod
def get_attribute_by_name(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use get_attribute_by_name(name) instead
Searches for attribute in this bundle by using attribute name.
Args:
name (str): Attribute name to search for.
Returns:
omni.graph.core.AttributeData: An attribute. If attribute is not found then invalid attribute is returned.
"""
def get_attribute_data(self, write: bool = False) -> list:
"""
DEPRECATED - use get_attributes() instead
"""
def get_attribute_data_count(self) -> int:
"""
DEPRECATED - use get_attribute_count() instead
"""
@staticmethod
def get_attribute_metadata_by_name(*args, **kwargs) -> typing.Any:
"""
Search for metadata fields for the attribute by using field names.
Args:
attribute (str): Name of the attribute.
field_names (list[str]): Attribute metadata fields to be searched for.
Returns:
list[omni.graph.core.AttributeData]: Array of metadata fields in the attribute.
Search for metadata field for the attribute by using field name.
Args:
attribute (str): Name of the attribute.
field_name (str): Attribute metadata field to be searched for.
Returns:
omni.graph.core.AttributeData: Metadata fields in the attribute.
"""
def get_attribute_names_and_types(self) -> tuple:
"""
DEPRECATED - use get_attribute_names() or get_attribute_types() instead
"""
@staticmethod
def get_attributes(*args, **kwargs) -> typing.Any:
"""
Searches for attributes in this bundle by using attribute names.
Args:
names (list[str]): Attribute names to search for.
Returns:
list[omni.graph.core.AttributeData]: A list of found attributes.
"""
@staticmethod
def get_attributes_by_name(*args, **kwargs) -> typing.Any:
"""
Searches for attributes in this bundle by using attribute names.
Args:
names (list[str]): Attribute names to search for.
Returns:
list[omni.graph.core.AttributeData]: A list of found attributes.
"""
@staticmethod
def get_bundle_metadata_by_name(*args, **kwargs) -> typing.Any:
"""
Search for field handles in this bundle by using field names.
Args:
field_names (list[str]): Bundle metadata fields to be searched for.
Returns:
list[omni.graph.core.AttributeData]: Metadata fields in this bundle.
Search for field handle in this bundle by using field name.
Args:
field_name (str): Bundle metadata fields to be searched for.
Returns:
omni.graph.core.AttributeData: Metadata field in this bundle.
"""
def get_child_bundle(self, index: int) -> IBundle2:
"""
Get the child bundle by index.
Args:
index (int): Child bundle index in range [0, child_bundle_count).
Returns:
omni.graph.core.IBundle2: Child bundle under the index. If bundle index is out of range, then invalid bundle is returned.
"""
def get_child_bundle_by_name(self, name: str) -> IBundle2:
"""
Lookup for child under specified name.
Args:
path (str): Name to child bundle in this bundle.
Returns:
omni.graph.core.IBundle2: Child bundle in this bundle. If child does not exist under the path, then invalid bundle is returned.
"""
def get_child_bundles(self) -> typing.List[IBundle2]:
"""
Get all child bundle handles in this bundle.
Returns:
list[omni.graph.core.IBundle2]: A list of all child bundles in this bundle.
"""
def get_child_bundles_by_name(self, names: typing.List[str]) -> typing.List[IBundle2]:
"""
Lookup for children under specified names.
Args:
names (list[str]): Names of child bundles in this bundle.
Returns:
list[omni.graph.core.IBundle2]: A list of found child bundles in this bundle.
"""
def get_metadata_storage(self) -> IBundle2:
"""
DEPRECATED - DO NOT USE
"""
def get_parent_bundle(self) -> IBundle2:
"""
Get the parent of this bundle
Returns:
omni.graph.core.IBundle2: The parent of this bundle, or invalid bundle if there is no parent.
"""
def get_prim_path(self) -> str:
"""
DEPRECATED - use get_path() instead
"""
@staticmethod
def insert_attribute(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use copy_attribute() instead
"""
def insert_bundle(self, bundle_to_copy: IConstBundle2) -> None:
"""
DEPRECATED - use copy_bundle() instead.
"""
def is_read_only(self) -> bool:
"""
Returns if this interface is read-only.
"""
def is_valid(self) -> bool:
"""
DEPRECATED - use bool cast instead
"""
@staticmethod
def link_attribute(*args, **kwargs) -> typing.Any:
"""
Adds an attribute to this bundle as link with names taken from target attribute.
Added attribute is a link to other attribute that is part of another bundle.
The link is owned by this bundle, but target of the link is not.
Removing link from this bundle does not destroy the data link points to.
Args:
target_attribute (omni.graph.core.AttributeData): Attribute whose data is to be added.
Returns:
omni.graph.core.AttributeData: Attribute that is a link.
Adds an attribute to this bundle as link with custom name.
Added attribute is a link to other attribute that is part of another bundle.
The link is owned by this bundle, but target of the link is not.
Removing link from this bundle does not destroy the data link points to.
Args:
link_name (str): Name for new link.
target_attribute (omni.graph.core.AttributeData): Attribute whose data is to be added.
Returns:
omni.graph.core.AttributeData: Attribute that is a link.
"""
@staticmethod
def link_attributes(*args, **kwargs) -> typing.Any:
"""
Adds a set of attributes to this bundle as links with names taken from target attributes.
Added attributes are links to other attributes that are part of another bundle.
The links are owned by this bundle, but targets of the links are not.
Removing links from this bundle does not destroy the data links point to.
Args:
target_attributes (list[omni.graph.core.AttributeData]): Attributes whose data is to be added.
Returns:
list[omni.graph.core.AttributeData]: A list of attributes that are links.
Adds a set of attributes to this bundle as links with custom names.
Added attributes are links to other attributes that are part of another bundle.
The links are owned by this bundle, but targets of the links are not.
Removing links from this bundle does not destroy the data links point to.
Args:
link_names (list[str]):
target_attributes (list[omni.graph.core.AttributeData]): Attributes whose data is to be added.
Returns:
list[omni.graph.core.AttributeData]: A list of attributes that are links.
"""
@typing.overload
def link_child_bundle(self, name: str, bundle: IConstBundle2) -> IBundle2:
"""
Link a bundle as child in current bundle, under given name.
Args:
name (str): The name under which the child bundle should be linked
bundle (omni.graph.core.IConstBundle2): The bundle to link
Returns:
omni.graph.core.IBundle2: The linked bundle.
Link a bundle as child in current bundle.
Args:
bundle (omni.graph.core.IConstBundle2): The bundle to link
Returns:
omni.graph.core.IBundle2: The linked bundle.
"""
@typing.overload
def link_child_bundle(self, bundle: IConstBundle2) -> IBundle2: ...
@typing.overload
def link_child_bundles(self, names: typing.List[str], bundles: typing.List[IConstBundle2]) -> typing.List[IBundle2]:
"""
Link a set of bundles as child in current bundle, under given names.
Args:
names (list[str]): The names under which the child bundles should be linked
bundles (list[omni.graph.core.IConstBundle2]): The bundles to link
Returns:
list[omni.graph.core.IBundle2]: The list of created bundles.
Link a set of bundles as child in current bundle.
Args:
bundles (list[omni.graph.core.IConstBundle2]): The bundles to link
Returns:
list[omni.graph.core.IBundle2]: The list of created bundles.
"""
@typing.overload
def link_child_bundles(self, bundles: typing.List[IConstBundle2]) -> typing.List[IBundle2]: ...
def remove_all_attributes(self) -> int:
"""
Remove all attributes from this bundle.
Returns:
int: Number of attributes successfully removed.
"""
def remove_all_child_bundles(self) -> int:
"""
Remove all child bundles from this bundle.
Only empty bundles can be removed.
Returns:
int: Number of child bundles successfully removed.
"""
@typing.overload
def remove_attribute(self, name: str) -> None:
"""
DEPRECATED - use remove_attribute_by_name() instead.
Looks up the attribute and if it is part of this bundle then remove it.
Attribute handle that is not part of this bundle is ignored.
Args:
attribute (omni.graph.core.AttributeData): Attribute whose data is to be removed.
Returns:
omni.core.Result: Success if successfully removed.
"""
@staticmethod
@typing.overload
def remove_attribute(*args, **kwargs) -> typing.Any: ...
@typing.overload
def remove_attribute_metadata(self, attribute: str, field_names: typing.List[str]) -> int:
"""
Remove attribute metadata fields.
Args:
attribute (str): Name of the attribute.
field_names (list[str]): Names of the fields to be removed.
Returns:
int: Number of fields successfully removed.
Remove attribute metadata field.
Args:
attribute (str): Name of the attribute.
field_name (str): Name of the field to be removed.
Returns:
omni.core.Result: Success if successfully removed.
"""
@typing.overload
def remove_attribute_metadata(self, attribute: str, field_name: str) -> int: ...
@typing.overload
def remove_attributes(self, names: typing.List[str]) -> None:
"""
DEPRECATED - use remove_attributes_by_name() instead.
Looks up the attributes and if they are part of this bundle then remove them.
Attribute handles that are not part of this bundle are ignored.
Args:
attributes (list[omni.graph.core.AttributeData]): Attributes whose data is to be removed.
Returns:
int: number of removed attributes
"""
@staticmethod
@typing.overload
def remove_attributes(*args, **kwargs) -> typing.Any: ...
def remove_attributes_by_name(self, names: typing.List[str]) -> int:
"""
Looks up the attributes by names and remove their data and metadata.
Args:
names (list[str]): Names of the attributes whose data is to be removed.
Returns:
omni.core.Result: Success if successfully removed.
"""
@typing.overload
def remove_bundle_metadata(self, field_names: typing.List[str]) -> int:
"""
Looks up bundle metadata fields and if they are part of this bundle metadata then remove them.
Fields that are not part of this bundle are ignored.
Args:
field_names (list[str]): Names of the fields whose data is to be removed.
Returns:
int: Number of fields successfully removed.
Looks up bundle metadata field and if it is part of this bundle metadata then remove it.
Field that is not part of this bundle is ignored.
Args:
field_name (str): Name of the field whose data is to be removed.
Returns:
omni.core.Result: Success if successfully removed.
"""
@typing.overload
def remove_bundle_metadata(self, field_name: str) -> int: ...
def remove_child_bundle(self, bundle: IConstBundle2) -> int:
"""
Looks up the bundle and if it is child of the bundle then remove it.
Bundle handle that is not child of this bundle is ignored.
Only empty bundle can be removed.
Args:
bundle (omni.graph.core.IConstBundle2): bundle to be removed.
Returns:
omni.core.Result: Success if successfully removed.
"""
def remove_child_bundles(self, bundles: typing.List[IConstBundle2]) -> int:
"""
Looks up the bundles and if they are children of the bundle then remove them.
Bundle handles that are not children of this bundle are ignored.
Only empty bundles can be removed.
Args:
bundles (list[omni.graph.core.IConstBundle2]): Bundles to be removed.
Returns:
int: Number of child bundles successfully removed.
"""
def remove_child_bundles_by_name(self, names: typing.List[str]) -> int:
"""
Looks up child bundles by name and remove their data and metadata.
Args:
names (list[str]): Names of the child bundles to be removed.
Returns:
omni.core.Result: Success if successfully removed.
"""
pass
class IBundleChanges(_IBundleChanges, omni.core._core.IObject):
"""
Interface for monitoring and handling changes in bundles and attributes.
The IBundleChanges_abi is an interface that provides methods for checking whether bundles and attributes
have been modified, and cleaning them if they have been modified. This is particularly useful in scenarios
where it's crucial to track changes and maintain the state of bundles and attributes.
This interface provides several methods for checking and cleaning modifications, each catering to different
use cases such as handling single bundles, multiple bundles, attributes, or specific attributes of a single bundle.
The methods of this interface return a BundleChangeType enumeration that indicates whether the checked entity
(bundle or attribute) has been modified.
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@staticmethod
@typing.overload
def activate_change_tracking(*args, **kwargs) -> typing.Any:
"""
@brief Activate tracking for specific bundle on its attributes and children.
@param handle to the specific bundles to enable change tracking.
@return An omni::core::Result indicating the success of the operation.
Activates the change tracking system for a bundle.
This method controls the change tracking system of a bundle. It's only applicable
for read-write bundles.
Args:
bundle: A bundle to activate change tracking system for.
"""
@typing.overload
def activate_change_tracking(self, bundle: IBundle2) -> None: ...
def clear_changes(self) -> int:
"""
Clears all recorded changes.
This method is used to clear or reset all the recorded changes of the bundles and attributes.
It can be used when the changes have been processed and need to be discarded.
An omni::core::Result indicating the success of the operation.
"""
@staticmethod
def create(*args, **kwargs) -> typing.Any: ...
@staticmethod
@typing.overload
def deactivate_change_tracking(*args, **kwargs) -> typing.Any:
"""
@brief Deactivate tracking for specific bundle on its attributes and children.
@param handle to the specific bundles to enable change tracking.
@return An omni::core::Result indicating the success of the operation.
Deactivates the change tracking system for a bundle.
This method controls the change tracking system of a bundle. It's only applicable
for read-write bundles.
Args:
bundle: A bundle to deactivate change tracking system for.
"""
@typing.overload
def deactivate_change_tracking(self, bundle: IBundle2) -> None: ...
@typing.overload
def get_change(self, bundle: IConstBundle2) -> BundleChangeType:
"""
Retrieves the change status of a list of bundles.
This method is used to check if any of the provided bundles or their contents have been modified.
Args:
bundles: A list of the bundles to check for modifications.
Returns:
list[omni.graph.core.BundleChangeType]: A list filled with BundleChangeType values for each bundle.
Retrieves the change status of a specific attribute.
This method is used to check if a specific attribute has been modified.
Args:
attribute: The specific attribute to check for modifications.
Returns:
omni.graph.core.BundleChangeType: A BundleChangeType value indicating the type of change (if any) that has occurred to the attribute.
"""
@staticmethod
@typing.overload
def get_change(*args, **kwargs) -> typing.Any: ...
@typing.overload
def get_changes(self, bundles: typing.List[IConstBundle2]) -> typing.List[BundleChangeType]:
"""
Retrieves the change status of a list of bundles.
This method is used to check if any of the bundles in the provided list or their contents have been modified.
Args:
bundles: A list of the bundles to check for modifications.
Returns:
list[omni.graph.core.BundleChangeType]: A list filled with BundleChangeType values for each bundle.
Retrieves the change status of a list of attributes.
This method is used to check if any of the attributes in the provided list have been modified.
Args:
attributes: A list of attributes to check for modifications.
Returns:
list[omni.graph.core.BundleChangeType]: A list filled with BundleChangeType values for each attribute.
Retrieves the change status for a list of bundles and attributes.
This method is used to check if any of the bundles or attributes in the provided list have been modified.
If an entry in the list is neither a bundle nor an attribute, its change status will be marked as None.
Args:
entries: A list of bundles and attributes to check for modifications.
Returns:
list[omni.graph.core.BundleChangeType]: A list filled with BundleChangeType values for each entry in the provided list.
"""
@staticmethod
@typing.overload
def get_changes(*args, **kwargs) -> typing.Any: ...
@typing.overload
def get_changes(self, entries: typing.Sequence) -> typing.List[BundleChangeType]: ...
pass
class IBundleFactory2(_IBundleFactory2, IBundleFactory, _IBundleFactory, omni.core._core.IObject):
"""
IBundleFactory version 2.
The version 2 allows to retrieve instances of IBundle instances from paths.
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@staticmethod
def get_bundle_from_path(*args, **kwargs) -> typing.Any:
"""
Get read write IBundle interface from path.
Args:
context (omni.graph.core.GraphContext): The context where bundles belong to.
path (str): Location of the bundle.
Returns:
omni.graph.core.IBundle2: Bundle instance.
"""
@staticmethod
def get_const_bundle_from_path(*args, **kwargs) -> typing.Any:
"""
Get read only IBundle interface from path.
Args:
context (omni.graph.core.GraphContext): The context where bundles belong to.
path (str): Location of the bundle.
Returns:
omni.graph.core.IConstBundle2: Bundle instance.
"""
pass
class IBundleFactory(_IBundleFactory, omni.core._core.IObject):
"""
Interface to create new bundles
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@staticmethod
def create(*args, **kwargs) -> typing.Any:
"""
Creates an interface object for bundle factories
Returns:
omni.graph.core.IBundleFactory2: Created instance of bundle factory.
"""
@staticmethod
def create_bundle(*args, **kwargs) -> typing.Any:
"""
Create bundle at given path.
Args:
context (omni.graph.core.GraphContext): The context where bundles are created.
path (str): Location for new bundle.
Returns:
omni.graph.core.IBundle2: Bundle instance.
"""
@staticmethod
def create_bundles(*args, **kwargs) -> typing.Any:
"""
Create bundles at given paths.
Args:
context (omni.graph.core.GraphContext): The context where bundles are created.
paths (list[str]): Locations for new bundles.
Returns:
list[omni.graph.core.IBundle2]: A list of bundle instances.
"""
@staticmethod
def get_bundle(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - no conversion is required
DEPRECATED - no conversion is required
"""
@staticmethod
def get_bundles(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - no conversion is required
DEPRECATED - no conversion is required
"""
pass
class IConstBundle2(_IConstBundle2, omni.core._core.IObject):
"""
Provide read only access to recursive bundles.
"""
def __bool__(self) -> bool:
"""
Returns:
bool: True if this bundle is valid, False otherwise.
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@staticmethod
def add_attribute(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use create_attribute() instead.
"""
@staticmethod
def add_attributes(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use create_attributes() instead.
"""
def clear(self) -> None:
"""
DEPRECATED - use clear_contents() instead
"""
@staticmethod
def get_attribute_by_name(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use get_attribute_by_name(name) instead
Searches for attribute in this bundle by using attribute name.
Args:
name (str): Attribute name to search for.
Returns:
omni.graph.core.AttributeData: An attribute. If attribute is not found then invalid attribute is returned.
"""
def get_attribute_count(self) -> int:
"""
Get the number of attributes in this bundle
Returns:
int: Number of attributes in this bundle.
"""
def get_attribute_data(self, write: bool = False) -> list:
"""
DEPRECATED - use get_attributes() instead
"""
def get_attribute_data_count(self) -> int:
"""
DEPRECATED - use get_attribute_count() instead
"""
@staticmethod
def get_attribute_metadata_by_name(*args, **kwargs) -> typing.Any:
"""
Search for metadata fields for the attribute by using field names.
Args:
attribute (str): Name of the attribute.
field_names (list[str]): Attribute metadata fields to be searched for.
Returns:
list[omni.graph.core.AttributeData]: Array of metadata fields in the attribute.
Search for metadata field for the attribute by using field name.
Args:
attribute (str): Name of the attribute.
field_name (str): Attribute metadata field to be searched for.
Returns:
omni.graph.core.AttributeData: Metadata fields in the attribute.
"""
def get_attribute_metadata_count(self, attribute: str) -> int:
"""
Gets the number of metadata fields in an attribute within the bundle
Args:
attribute (str): Name of the attribute to count metadata for.
Returns:
int: Number of metadata fields in the attribute.
"""
def get_attribute_metadata_names(self, attribute: str) -> typing.List[str]:
"""
Get names of all metadata fields in the attribute.
Args:
attribute (str): Name of the attribute.
Returns:
list[str]: Array of names in the attribute.
"""
@staticmethod
def get_attribute_metadata_types(*args, **kwargs) -> typing.Any:
"""
Get types of all metadata fields in the attribute.
Args:
attribute (string): Name of the attribute.
Returns:
list[omni.graph.core.Type]: Array of types in the attribute.
"""
def get_attribute_names(self) -> typing.List[str]:
"""
Get the names of all attributes in this bundle.
Returns:
list[str]: A list of the names.
"""
def get_attribute_names_and_types(self) -> tuple:
"""
DEPRECATED - use get_attribute_names() or get_attribute_types() instead
"""
@staticmethod
def get_attribute_types(*args, **kwargs) -> typing.Any:
"""
Get the types of all attributes in this bundle.
Returns:
list[omni.graph.core.Type]: A list of the types.
"""
@staticmethod
def get_attributes(*args, **kwargs) -> typing.Any:
"""
Get all attributes in this bundle.
Returns:
list[omni.graph.core.AttributeData]: A list of all attributes in this bundle.
"""
@staticmethod
def get_attributes_by_name(*args, **kwargs) -> typing.Any:
"""
Searches for attributes in this bundle by using attribute names.
Args:
names (list[str]): Attribute names to search for.
Returns:
list[omni.graph.core.AttributeData]: A list of found attributes.
"""
@staticmethod
def get_bundle_metadata_by_name(*args, **kwargs) -> typing.Any:
"""
Search for field handles in this bundle by using field names.
Args:
field_names (list[str]): Bundle metadata fields to be searched for.
Returns:
list[omni.graph.core.AttributeData]: Metadata fields in this bundle.
Search for field handle in this bundle by using field name.
Args:
field_name (str): Bundle metadata fields to be searched for.
Returns:
omni.graph.core.AttributeData: Metadata field in this bundle.
"""
def get_bundle_metadata_count(self) -> int:
"""
Get the number of metadata entries
Returns:
int: Number of metadata fields in this bundle.
"""
def get_bundle_metadata_names(self) -> typing.List[str]:
"""
Get the names of all metadata fields in this bundle.
Returns:
list[str]: Array of names in this bundle.
"""
@staticmethod
def get_bundle_metadata_types(*args, **kwargs) -> typing.Any:
"""
Get the types of all metadata fields in this bundle.
Returns:
list[omni.graph.core.Type]: Array of types in this bundle.
"""
def get_child_bundle(self, index: int) -> IConstBundle2:
"""
Get the child bundle by index.
Args:
index (int): Child bundle index in range [0, child_bundle_count).
Returns:
omni.graph.core.IConstBundle2: Child bundle under the index. If bundle index is out of range, then invalid bundle is returned.
"""
def get_child_bundle_by_name(self, path: str) -> IConstBundle2:
"""
Lookup for child under specified path.
Args:
path (str): Path to child bundle in this bundle.
Returns:
omni.graph.core.IConstBundle2: Child bundle in this bundle. If child does not exist under the path, then invalid bundle is returned.
"""
def get_child_bundle_count(self) -> int:
"""
Get the number of child bundles
Returns:
int: Number of child bundles in this bundle.
"""
def get_child_bundles(self) -> typing.List[IConstBundle2]:
"""
Get all child bundle handles in this bundle.
Returns:
list[omni.graph.core.IConstBundle2]: A list of all child bundles in this bundle.
"""
def get_child_bundles_by_name(self, names: typing.List[str]) -> typing.List[IConstBundle2]:
"""
Lookup for children under specified names.
Args:
names (list[str]): Names to child bundles in this bundle.
Returns:
list[omni.graph.core.IConstBundle2]: A list of found child bundles in this bundle.
"""
@staticmethod
def get_context(*args, **kwargs) -> typing.Any:
"""
Get the context used by this bundle
Returns:
omni.graph.core.GraphContext: The context of this bundle.
"""
def get_metadata_storage(self) -> IConstBundle2:
"""
Get access to metadata storage that contains all metadata information
Returns:
list[omni.graph.core.IBundle2]: List of bundles with the metadata information
"""
def get_name(self) -> str:
"""
Get the name of the bundle
Returns:
str: The name of this bundle.
"""
def get_parent_bundle(self) -> IConstBundle2:
"""
Get the parent bundle
Returns:
omni.graph.core.IConstBundle2: The parent of this bundle, or invalid bundle if there is no parent.
"""
def get_path(self) -> str:
"""
Get the path to this bundle
Returns:
str: The path to this bundle.
"""
def get_prim_path(self) -> str:
"""
DEPRECATED - use get_path() instead
"""
@staticmethod
def insert_attribute(*args, **kwargs) -> typing.Any:
"""
DEPRECATED - use copy_attribute() instead
"""
def insert_bundle(self, bundle_to_copy: IConstBundle2) -> None:
"""
DEPRECATED - use copy_bundle() instead.
"""
def is_read_only(self) -> bool:
"""
Returns if this interface is read-only.
"""
def is_valid(self) -> bool:
"""
DEPRECATED - use bool cast instead
"""
def remove_attribute(self, name: str) -> None:
"""
DEPRECATED - use remove_attribute_by_name() instead.
"""
def remove_attributes(self, names: typing.List[str]) -> None:
"""
DEPRECATED - use remove_attributes_by_name() instead.
"""
@property
def valid(self) -> bool:
"""
:type: bool
"""
pass
class INodeCategories(_INodeCategories, omni.core._core.IObject):
"""
Interface to the list of categories that a node type can belong to
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
def define_category(self, category_name: str, category_description: str) -> bool:
"""
Define a new category
@param[in] categoryName Name of the new category
@param[in] categoryDescription Description of the category
@return false if there was already a category with the given name
"""
@staticmethod
def get_all_categories() -> object:
"""
Get the list of available categories and their descriptions.
Returns:
dict[str,str]: Dictionary with categories as a name:description dictionary if it succeeded, else None
"""
@staticmethod
def get_node_categories(node_id: object) -> object:
"""
Return the list of categories that have been applied to the node.
Args:
node_id (str | Node): The node, or path to the node, whose categories are to be found
Returns:
list[str]: A list of category names applied to the node if it succeeded, else None
"""
@staticmethod
def get_node_type_categories(node_type_id: object) -> object:
"""
Return the list of categories that have been applied to the node type.
Args:
node_type_id (str | NodeType): The node type, or name of the node type, whose categories are to be found
Returns:
list[str]: A list of category names applied to the node type if it succeeded, else None
"""
def remove_category(self, category_name: str) -> bool:
"""
Remove an existing category, mainly to manage the ones created by a node type for itself
@param[in] categoryName Name of the category to remove
@return false if there was no category with the given name
"""
@property
def category_count(self) -> int:
"""
:type: int
"""
pass
class ISchedulingHints2(_ISchedulingHints2, ISchedulingHints, _ISchedulingHints, omni.core._core.IObject):
"""
Interface extension for ISchedulingHints that adds a new "pure" hint
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@typing.overload
def __init__(self, arg0: ISchedulingHints) -> None: ...
@property
def purity_status(self) -> ePurityStatus:
"""
:type: ePurityStatus
"""
@purity_status.setter
def purity_status(self, arg1: ePurityStatus) -> None:
pass
pass
class ISchedulingHints(_ISchedulingHints, omni.core._core.IObject):
"""
Interface to the list of scheduling hints that can be applied to a node type
"""
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
def get_data_access(self, data_type: eAccessLocation) -> eAccessType:
"""
Get the type of access the node has for a given data type
@param[in] dataType Type of data for which access type is being modified
@returns Value of the access type flag
"""
def inspect(self, inspector: omni.inspect._omni_inspect.IInspector) -> bool:
"""
Runs the inspector on the scheduling hints.
@param[in] inspector The inspector class
@return true if the inspection ran successfully, false if the inspection type is not supported
"""
def set_data_access(self, data_type: eAccessLocation, new_access_type: eAccessType) -> None:
"""
Set the flag describing how a node accesses particular data in its compute _abi (defaults to no access).
Setting any of these flags will, in most cases, automatically mark the node as "not threadsafe".
One current exception to this is allowing a node to be both threadsafe and a writer to USD, since
such behavior can be achieved if delayed writebacks (e.g. "registerForUSDWriteBack") are utilized
in the node's compute method.
@param[in] dataType Type of data for which access type is being modified
@param[in] newAccessType New value of the access type flag
"""
@property
def compute_rule(self) -> eComputeRule:
"""
:type: eComputeRule
"""
@compute_rule.setter
def compute_rule(self, arg1: eComputeRule) -> None:
pass
@property
def thread_safety(self) -> eThreadSafety:
"""
:type: eThreadSafety
"""
@thread_safety.setter
def thread_safety(self, arg1: eThreadSafety) -> None:
pass
pass
class IVariable(_IVariable, omni.core._core.IObject):
"""
Object that contains a value that is local to a graph, available from anywhere in the graph
"""
def __bool__(self) -> bool: ...
@typing.overload
def __init__(self, arg0: omni.core._core.IObject) -> None: ...
@typing.overload
def __init__(self) -> None: ...
@staticmethod
def get(*args, **kwargs) -> typing.Any:
"""
Get the value of a variable
Args:
graph_context (omni.graph.core.GraphContext): The GraphContext object to get the variable value from.
instance_path (str): Optional path to the prim instance to fetch the variable value for. By default this will
fetch the variable value from the graph prim.
Returns:
Any: Value of the variable
"""
@staticmethod
def get_array(*args, **kwargs) -> typing.Any:
"""
Get the value of an array variable
Args:
graph_context (omni.graph.core.GraphContext): The GraphContext object to get the variable value from.
get_for_write (bool): Should the data be retrieved for writing?
reserved_element_count (int): If the data is to be retrieved for writing, preallocate this many elements
instance_path (str): Optional path to the prim instance to fetch the variable value for. By default this will
fetch the variable value from the graph prim.
Returns:
Any: Value of the array variable
"""
@staticmethod
def set(*args, **kwargs) -> typing.Any:
"""
Sets the value of a variable
Args:
graph_context (omni.graph.core.GraphContext): The GraphContext object to store the variable value.
on_gpu (bool): Is the data to be set on the GPU?
instance_path (str): Optional path to the prim instance to set the variable value on. By default this will
set the variable value on the graph prim.
Returns:
bool: True if the value was successfully set
"""
@staticmethod
def set_type(*args, **kwargs) -> typing.Any:
"""
Changes the type of a variable. Changing the type of a variable may remove the variable's default value.
Args:
variable_type (omni.graph.core.Type): The type to switch the variable to.
Returns:
bool: True if the type was successfully changed.
"""
@property
def category(self) -> str:
"""
:type: str
"""
@category.setter
def category(self, arg1: str) -> None:
pass
@property
def display_name(self) -> str:
"""
:type: str
"""
@display_name.setter
def display_name(self, arg1: str) -> None:
pass
@property
def name(self) -> str:
"""
:type: str
"""
@property
def scope(self) -> eVariableScope:
"""
:type: eVariableScope
"""
@scope.setter
def scope(self, arg1: eVariableScope) -> None:
pass
@property
def source_path(self) -> str:
"""
:type: str
"""
@property
def tooltip(self) -> str:
"""
:type: str
"""
@tooltip.setter
def tooltip(self, arg1: str) -> None:
pass
@property
def type(self) -> omni::graph::core::Py_Type:
"""
Gets the data type of the variable.
Returns:
omni.graph.core.Type: The data type of the variable.
:type: omni::graph::core::Py_Type
"""
@property
def valid(self) -> bool:
"""
:type: bool
"""
pass
class MemoryType():
"""
Default memory location for an attribute or node's data
Members:
CPU : The memory is on the CPU by default
CUDA : The memory is on the GPU by default
ANY : The memory does not have any default device
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
ANY: omni.graph.core._omni_graph_core.MemoryType # value = <MemoryType.ANY: 2>
CPU: omni.graph.core._omni_graph_core.MemoryType # value = <MemoryType.CPU: 0>
CUDA: omni.graph.core._omni_graph_core.MemoryType # value = <MemoryType.CUDA: 1>
__members__: dict # value = {'CPU': <MemoryType.CPU: 0>, 'CUDA': <MemoryType.CUDA: 1>, 'ANY': <MemoryType.ANY: 2>}
pass
class Node():
"""
An element of execution within a graph, containing attributes and connected to other nodes
"""
def __bool__(self) -> bool: ...
def __eq__(self, arg0: Node) -> bool: ...
def __hash__(self) -> int: ...
def __repr__(self) -> str: ...
def _do_not_use(self) -> bool:
"""
Temporary internal function - do not use
"""
def clear_old_compute_messages(self) -> int:
"""
Clears all compute messages logged for the node prior to its most recent evaluation.
Messages logged during the most recent evaluation remain untouched.
Normally this will be called during graph evaluation so it is of little use unless
you're writing your own evaluation manager.
Returns:
int: The number of messages that were deleted.
"""
@staticmethod
def create_attribute(*args, **kwargs) -> typing.Any:
"""
Creates an attribute with the specified name, type, and port type and returns success state.
Args:
attributeName (str): Name of the attribute.
attributeType (omni.graph.core.Type): Type of the attribute.
portType (omni.graph.core.AttributePortType): The port type of the attribute, defaults to
omni.graph.core.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT
value (Any): The initial value to set on the attribute, default is None
extendedType (omni.graph.core.ExtendedAttributeType): The extended type of the attribute, defaults to
omni.graph.core.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR
unionTypes (str): Comma-separated list of union types if the extended type is
omni.graph.core.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION,
defaults to empty string for non-union types.
Returns:
bool: True if the creation was successful, else False
"""
def deregister_on_connected_callback(self, callback: int) -> None:
"""
De-registers the on_connected callback to be invoked when attributes connect.
Args:
callback (callable): The handle that was returned during the register_on_connected_callback call
"""
def deregister_on_disconnected_callback(self, callback: int) -> None:
"""
De-registers the on_disconnected callback to be invoked when attributes disconnect.
Args:
callback (callable): The handle that was returned during the register_on_disconnected_callback call
"""
def deregister_on_path_changed_callback(self, callback: int) -> None:
"""
Deregisters the on_path_changed callback to be invoked when anything changes in the stage. [DEPRECATED]
Args:
callback (callable): The handle that was returned during the register_on_path_changed_callback call
"""
def get_attribute(self, name: str) -> Attribute:
"""
Given the name of an attribute returns an attribute object to it.
Args:
name (str): The name of the attribute
Returns:
omni.graph.core.Attribute: Attribute with the given name, or None if it does not exist on the node
"""
def get_attribute_exists(self, name: str) -> bool:
"""
Given an attribute name, returns whether this attribute exists or not.
Args:
name (str): The name of the attribute
Returns:
bool: True if the attribute exists on this node, else False
"""
def get_attributes(self) -> typing.List[Attribute]:
"""
Returns the list of attributes on this node.
"""
@staticmethod
def get_backing_bucket_id(*args, **kwargs) -> typing.Any:
"""
Finds this node's bucket id within the backing store. The id is only valid until the next
modification of the backing store, so do not hold on to it.
Returns:
int: The bucket id, raises ValueError if the look up fails.
"""
@staticmethod
def get_compound_graph_instance(*args, **kwargs) -> typing.Any:
"""
Returns a handle to the associated sub-graph, if the given node is a compound node.
Returns:
omni.graph.core.Graph: The subgraph
"""
def get_compute_count(self) -> int:
"""
Returns the number of times this node's compute() has been called. The counter has a limited range and will
eventually roll over to 0, so a higher count cannot be assumed to represent a more recent compute than an
older one.
Returns:
int: Number of times this node's compute() has been called since the counter last rolled over to 0.
"""
@staticmethod
def get_compute_messages(*args, **kwargs) -> typing.Any:
"""
Returns a list of the compute messages currently logged for the node at a specific severity.
Args:
severity (omni.graph.core.Severity): Severity level of the message.
Returns:
list[str]: The list of messages, may be empty.
"""
def get_dynamic_downstream_control(self) -> bool:
"""
Check if the downstream nodes are influenced by this node
Returns:
bool: True if the current node can influence the execution of downstream nodes in dynamic scheduling
"""
def get_event_stream(self) -> carb.events._events.IEventStream:
"""
Get the event stream the node uses for notification of changes.
Returns:
carb.events.IEventStream: Event stream to monitor for node changes
"""
@staticmethod
def get_graph(*args, **kwargs) -> typing.Any:
"""
Get the graph to which this node belongs
Returns:
omni.graph.core.Graph: Graph associated with the current node. The returned graph will be invalid if the
node is not valid.
"""
def get_handle(self) -> int:
"""
Get an opaque handle to the node
Returns:
int: a unique handle to the node
"""
@staticmethod
def get_node_type(*args, **kwargs) -> typing.Any:
"""
Gets the node type of this node
Returns:
omni.graph.core.NodeType: The node type from which this node was created.
"""
def get_prim_path(self) -> str:
"""
Returns the path to the prim currently backing the node.
"""
def get_type_name(self) -> str:
"""
Get the node type name
Returns:
str: The type name of the node.
"""
@staticmethod
def get_wrapped_graph(*args, **kwargs) -> typing.Any:
"""
Get the graph wrapped by this node
Returns:
omni.graph.core.Graph: The graph wrapped by the current node, if any. The returned graph will be invalid
if the node does not wrap a graph or is invalid.
"""
def increment_compute_count(self) -> int:
"""
Increments the node's compute counter. This method is provided primarily for debugging and experimental uses
and should not normally be used by end-users.
Returns:
int: The new compute counter. This may be zero if the counter has just rolled over.
"""
def is_backed_by_usd(self) -> bool:
"""
Check if the node is back by USD or not
Returns:
bool: True if the current node is by an USD prim on the stage.
"""
def is_compound_node(self) -> bool:
"""
Returns whether this node is a compound node. A compound node is a node that has a node type that
is defined by an OmniGraph.
Returns:
bool: True if this node is a compound node, False otherwise.
"""
def is_disabled(self) -> bool:
"""
Check if the node is currently disabled
Returns:
bool: True if the node is disabled.
"""
def is_valid(self) -> bool:
"""
Check the validity of the node
Returns:
bool: True if the node is valid.
"""
@staticmethod
def log_compute_message(*args, **kwargs) -> typing.Any:
"""
Logs a compute message of a given severity for the node.
This method is intended to be used from within the compute() method of a
node to alert the user to any problems or issues with the node's most recent
evaluation. They are accumulated until the next successful evaluation
at which point they are cleared.
If duplicate messages are logged, with the same severity level, only one is
stored.
Args:
severity (omni.graph.core.Severity): Severity level of the message.
message (str): The message.
Returns:
bool: True if the message has already been logged, else False
"""
def node_id(self) -> int:
"""
Returns a unique identifier value for this node.
Returns:
int: Unique identifier value for the node - not persistent through file save and load
"""
def register_on_connected_callback(self, callback: object) -> int:
"""
Registers a callback to be invoked when the node has attributes connected. The callback takes 2 parameters:
the attributes from and attribute to of the connection.
Args:
callback (callable): The callback function
Returns:
int: A handle that could be used for deregistration.
"""
def register_on_disconnected_callback(self, callback: object) -> int:
"""
Registers a callback to be invoked when the node has attributes disconnected. The callback takes 2 parameters:
the attributes from and attribute to of the disconnection.
Args:
callback (callable): The callback function
Returns:
A handle identifying the callback that can be used for deregistration.
"""
def register_on_path_changed_callback(self, callback: object) -> int:
"""
Registers a callback to be invoked when a path changes in the stage. The callback takes 1 parameter:
a list of the paths that were changed. [DEPRECATED]
Args:
callback (callable): The callback function
Returns:
A handle identifying the callback that can be used for deregistration.
"""
def remove_attribute(self, attributeName: str) -> bool:
"""
Removes an attribute with the specified name and type and returns success state.
Args:
attributeName (str): Name of the attribute.
Returns:
bool: True if the removal was successful, False if the attribute was not found
"""
def request_compute(self) -> bool:
"""
Requests a compute of this node
Returns:
bool: True if the request was successful, False if there was an error
"""
def resolve_coupled_attributes(self, attributesArray: typing.List[Attribute]) -> bool:
"""
Resolves attribute types given a set of attributes which are fully type coupled.
For example if node 'Increment' has one input attribute 'a' and one output attribute 'b'
and the types of 'a' and 'b' should always match. If the input is resolved then this function will
resolve the output to the same type.
It will also take into consideration available conversions on the input size.
The type of the first (resolved) provided attribute will be used to resolve others or select appropriate conversions
Note that input attribute types are never inferred from output attribute types.
This function should only be called from the INodeType function 'on_connection_type_resolve'
Args:
attributesArray (list[omni.graph.core.Attribute]): Array of attributes to be resolved as a coupled group
Returns:
bool: True if successful, False otherwise, usually due to mismatched or missing resolved types
"""
@staticmethod
def resolve_partially_coupled_attributes(*args, **kwargs) -> typing.Any:
"""
Resolves attribute types given a set of attributes, that can have differing tuple counts and/or array depth,
and differing but convertible base data type.
The three input buffers are tied together, holding the attribute, the tuple
count, and the array depth of the types to be coupled.
This function will solve base type conversion by targeting the first provided type in the list,
for all other ones that require it.
For example if node 'makeTuple2' has two input attributes 'a' and 'b' and one output 'c' and we want to resolve
any float connection to the types 'a':float, 'b':float, 'c':float[2] (convertible base types and different tuple counts)
then the input buffers would contain:
attrsBuf = [a, b, c]
tuplesBuf = [1, 1, 2]
arrayDepthsBuf = [0, 0, 0]
rolesBuf = [AttributeRole::eNone, AttributeRole::eNone, AttributeRole::eNone]
This is worth noting that 'b' could be of any type convertible to float. But since the first provided
attribute is 'a', the type of 'a' will be used to propagate the type resolution.
Note that input attribute types are never inferred from output attribute types.
This function should only be called from the INodeType function 'on_connection_type_resolve'
Args:
attributesArray (list[omni.graph.core.Attribute]): Array of attributes to be resolved as a coupled group
tuplesArray (list[int]): Array of tuple count desired for each corresponding attribute. Any value
of None indicates the found tuple count is to be used when resolving.
arraySizesArray (list[int]): Array of array depth desired for each corresponding attribute. Any value
of None indicates the found array depth is to be used when resolving.
rolesArray (list[omni.graph.core.AttributeRole]): Array of role desired for each corresponding attribute. Any
value of AttributeRole::eUnknown/None indicates the found role is to be used when resolving.
Returns:
bool: True if successful, False otherwise, usually due to mismatched or missing resolved types
"""
def set_compute_incomplete(self) -> None:
"""
Informs the system that compute is incomplete for this frame. In lazy evaluation systems, this node will be
scheduled on the next frame since it still has more work to do.
"""
def set_disabled(self, disabled: bool) -> None:
"""
Sets whether the node is disabled or not.
Args:
disabled (bool): True for disabled, False for not.
"""
def set_dynamic_downstream_control(self, control: bool) -> None:
"""
Sets whether the current node can influence the execution of downstream nodes in dynamic scheduling
Args:
control (bool): True for being able to disable downstream nodes, False otherwise
"""
pass
class NodeEvent():
"""
Node modification event.
Members:
CREATE_ATTRIBUTE : Attribute was created
REMOVE_ATTRIBUTE : Attribute was removed
ATTRIBUTE_TYPE_RESOLVE : Extended attribute type was resolved
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
ATTRIBUTE_TYPE_RESOLVE: omni.graph.core._omni_graph_core.NodeEvent # value = <NodeEvent.ATTRIBUTE_TYPE_RESOLVE: 2>
CREATE_ATTRIBUTE: omni.graph.core._omni_graph_core.NodeEvent # value = <NodeEvent.CREATE_ATTRIBUTE: 0>
REMOVE_ATTRIBUTE: omni.graph.core._omni_graph_core.NodeEvent # value = <NodeEvent.REMOVE_ATTRIBUTE: 1>
__members__: dict # value = {'CREATE_ATTRIBUTE': <NodeEvent.CREATE_ATTRIBUTE: 0>, 'REMOVE_ATTRIBUTE': <NodeEvent.REMOVE_ATTRIBUTE: 1>, 'ATTRIBUTE_TYPE_RESOLVE': <NodeEvent.ATTRIBUTE_TYPE_RESOLVE: 2>}
pass
class NodeType():
"""
Definition of a node's interface and structure
"""
def __bool__(self) -> bool:
"""
Returns whether the current node type is valid.
"""
def __eq__(self, arg0: NodeType) -> bool:
"""
Returns whether two node type objects refer to the same underlying node type implementation.
"""
def add_extended_input(self, name: str, type: str, is_required: bool, extended_type: ExtendedAttributeType) -> None:
"""
Adds an extended input type to this node type. Every node of this node type would then have this input.
Args:
name (str): The name of the input
type (str): Extra information for the type - for union types, this is a list of types of this union, comma separated
For example, "double,float"
is_required (bool): Whether the input is required or not
extended_type (omni.graph.core.ExtendedAttributeType): The kind of extended attribute this is
e.g. omni.graph.core.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION
"""
def add_extended_output(self, name: str, type: str, is_required: bool, extended_type: ExtendedAttributeType) -> None:
"""
Adds an extended output type to this node type. Every node of this node type would then have this output.
Args:
name (str): The name of the output
type (str): Extra information for the type - for union types, this is a list of types of this union, comma separated
For example, "double,float"
is_required (bool): Whether the output is required or not
extended_type (omni.graph.core.ExtendedAttributeType): The kind of extended attribute this is
e.g. omni.graph.core.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION
"""
def add_extended_state(self, name: str, type: str, is_required: bool, extended_type: ExtendedAttributeType) -> None:
"""
Adds an extended state type to this node type. Every node of this node type would then have this state.
Args:
name (str): The name of the state attribute
type (str): Extra information for the type - for union types, this is a list of types of this union, comma separated
For example, "double,float"
is_required (bool): Whether the state attribute is required or not
extended_type (omni.graph.core.ExtendedAttributeType): The kind of extended attribute this is
e.g. omni.graph.core.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION
"""
def add_input(self, name: str, type: str, is_required: bool, default_value: object = None) -> None:
"""
Adds an input to this node type. Every node of this node type would then have this input.
Args:
name (str): The name of the input
type (str): The type name of the input
is_required (bool): Whether the input is required or not
default_value (any): Default value for the attribute if it is not explicitly set (None means no default)
"""
def add_output(self, name: str, type: str, is_required: bool, default_value: object = None) -> None:
"""
Adds an output to this node type. Every node of this node type would then have this output.
Args:
name (str): The name of the output
type (str): The type name of the output
is_required (bool): Whether the output is required or not
default_value (any): Default value for the attribute if it is not explicitly set (None means no default)
"""
def add_state(self, name: str, type: str, is_required: bool, default_value: object = None) -> None:
"""
Adds an state to this node type. Every node of this node type would then have this state.
Args:
name (str): The name of the state
type (str): The type name of the state
is_required (bool): Whether the state is required or not
default_value (any): Default value for the attribute if it is not explicitly set (None means no default)
"""
def get_all_categories(self) -> list:
"""
Gets the node type's categories
Returns:
list[str]: A list of all categories associated with this node type
"""
def get_all_metadata(self) -> dict:
"""
Gets the node type's metadata
Returns:
dict[str,str]: A dictionary of name:value metadata on the node type
"""
def get_all_subnode_types(self) -> dict:
"""
Finds all subnode types of the current node type.
Returns:
dict[str, omni.graph.core.NodeType]: Dictionary of type_name:type_object for all subnode types of this one
"""
def get_metadata(self, key: str) -> str:
"""
Returns the metadata value for the given key.
Args:
key (str): The metadata keyword
Returns:
str | None: Metadata value for the given keyword, or None if it is not defined
"""
def get_metadata_count(self) -> int:
"""
Gets the number of metadata values set on the node type
Returns:
int: The number of metadata values currently defined on the node type.
"""
def get_node_type(self) -> str:
"""
Get this node type's name
Returns:
str: The name of this node type.
"""
def get_path(self) -> str:
"""
Gets the path to the node type definition
Returns:
str: The path to the node type prim. For compound node definitions, this is path on the stage to the
OmniGraphSchema.OmniGraphCompoundNodeType object that defines the compound.
For other node types, the path returned is unique, but does not represent a valid Prim on the stage.
"""
def get_scheduling_hints(self) -> ISchedulingHints:
"""
Gets the set of scheduling hints currently set on the node type.
Returns:
omni.graph.core.ISchedulingHints: The scheduling hints for this node type
"""
def has_state(self) -> bool:
"""
Checks to see if instantiations of the node type has internal state
Returns:
bool: True if nodes of this type will have internal state data, False if not.
"""
def inspect(self, inspector: omni.inspect._omni_inspect.IInspector) -> bool:
"""
Runs the inspector on the node type
Args:
inspector (omni.inspect.Inspector): The inspector to run
Returns:
bool: True if the inspector was successfully run on the node type, False if it is not supported
"""
def is_compound_node_type(self) -> bool:
"""
Checks to see if this node type defines a compound node type
Returns:
bool: True if this node type is a compound node type, meaning its implementation is defined by an OmniGraph
"""
def is_valid(self) -> bool:
"""
Checks to see if this object is valid
Returns:
bool: True if this node type object is valid.
"""
def set_has_state(self, has_state: bool) -> None:
"""
Sets the boolean indicating a node has state.
Args:
has_state (bool): Whether the node has state or not
"""
def set_metadata(self, key: str, value: str) -> bool:
"""
Sets the metadata value for the given key.
Args:
key (str): The metadata keyword
value (str): The value of the metadata
"""
def set_scheduling_hints(self, scheduling_hints: ISchedulingHints) -> None:
"""
Modify the scheduling hints defined on the node type.
Args:
scheduling_hints (omni.graph.core.ISchedulingHints): New set of scheduling hints for the node type
"""
__hash__ = None
pass
class OmniGraphBindingError(Exception, BaseException):
pass
class PtrToPtrKind():
"""
Memory type for the pointer to a GPU data array
Members:
NA : Memory is CPU or type is not an array
CPU : Pointers to GPU arrays live on the CPU
GPU : Pointers to GPU arrays live on the GPU
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
CPU: omni.graph.core._omni_graph_core.PtrToPtrKind # value = <PtrToPtrKind.CPU: 1>
GPU: omni.graph.core._omni_graph_core.PtrToPtrKind # value = <PtrToPtrKind.NA: 0>
NA: omni.graph.core._omni_graph_core.PtrToPtrKind # value = <PtrToPtrKind.NA: 0>
__members__: dict # value = {'NA': <PtrToPtrKind.NA: 0>, 'CPU': <PtrToPtrKind.CPU: 1>, 'GPU': <PtrToPtrKind.NA: 0>}
pass
class Severity():
"""
Severity level of the log message
Members:
INFO : Message is informational only
WARNING : Message is regarding a recoverable unexpected situation
ERROR : Message is regarding an unrecoverable unexpected situation
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
ERROR: omni.graph.core._omni_graph_core.Severity # value = <Severity.ERROR: 2>
INFO: omni.graph.core._omni_graph_core.Severity # value = <Severity.INFO: 0>
WARNING: omni.graph.core._omni_graph_core.Severity # value = <Severity.WARNING: 1>
__members__: dict # value = {'INFO': <Severity.INFO: 0>, 'WARNING': <Severity.WARNING: 1>, 'ERROR': <Severity.ERROR: 2>}
pass
class Type():
"""
Full definition of the data type owned by an attribute
"""
def __eq__(self, arg0: Type) -> bool: ...
def __getstate__(self) -> tuple: ...
def __hash__(self) -> int: ...
def __init__(self, base_type: BaseDataType, tuple_count: int = 1, array_depth: int = 0, role: AttributeRole = AttributeRole.NONE) -> None: ...
def __ne__(self, arg0: Type) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, arg0: tuple) -> None: ...
def __str__(self) -> str: ...
def get_base_type_name(self) -> str:
"""
Gets the name of this type's base data type
Returns:
str: Name of just the base data type of this type, e.g. "float"
"""
def get_ogn_type_name(self) -> str:
"""
Gets the OGN-style name of this type
Returns:
str: Name of this type in OGN format, which differs slightly from the USD format, e.g. "float[3]"
"""
def get_role_name(self) -> str:
"""
Gets the name of the role of this type
Returns:
str: Name of just the role of this type, e.g. "color"
"""
def get_type_name(self) -> str:
"""
Gets the name of this data type
Returns:
str: Name of this type, e.g. "float3"
"""
def is_compatible_raw_data(self, type_to_compare: Type) -> bool:
"""
Does a role-insensitive comparison with the given Type.
For example double[3] != pointd[3], but they are compatible and so this function would return True.
Args:
type_to_compare (omni.graph.core.Type): Type to compare for compatibility
Returns:
bool: True if the given type is compatible with this type
"""
def is_matrix_type(self) -> bool:
"""
Checks if the type one of the matrix types, whose tuples are interpreted as a square array
Returns:
bool: True if this type is one of the matrix types
"""
@property
def array_depth(self) -> int:
"""
(int) Zero for a single value, one for an array.
:type: int
"""
@array_depth.setter
def array_depth(self, arg1: int) -> None:
"""
(int) Zero for a single value, one for an array.
"""
@property
def base_type(self) -> BaseDataType:
"""
(omni.graph.core.BaseDataType) Base type of the attribute.
:type: BaseDataType
"""
@base_type.setter
def base_type(self, arg1: BaseDataType) -> None:
"""
(omni.graph.core.BaseDataType) Base type of the attribute.
"""
@property
def role(self) -> AttributeRole:
"""
(omni.graph.core.AttributeRole) The semantic role of the type.
:type: AttributeRole
"""
@role.setter
def role(self, arg1: AttributeRole) -> None:
"""
(omni.graph.core.AttributeRole) The semantic role of the type.
"""
@property
def tuple_count(self) -> int:
"""
(int) Number of components in each tuple. 1 for a single value (scalar), 3 for a point3d, etc.
:type: int
"""
@tuple_count.setter
def tuple_count(self, arg1: int) -> None:
"""
(int) Number of components in each tuple. 1 for a single value (scalar), 3 for a point3d, etc.
"""
pass
class _IBundle2(IConstBundle2, _IConstBundle2, omni.core._core.IObject):
pass
class _IBundleChanges(omni.core._core.IObject):
pass
class _IBundleFactory2(IBundleFactory, _IBundleFactory, omni.core._core.IObject):
pass
class _IBundleFactory(omni.core._core.IObject):
pass
class _IConstBundle2(omni.core._core.IObject):
pass
class _INodeCategories(omni.core._core.IObject):
pass
class _ISchedulingHints2(ISchedulingHints, _ISchedulingHints, omni.core._core.IObject):
pass
class _ISchedulingHints(omni.core._core.IObject):
pass
class _IVariable(omni.core._core.IObject):
pass
class eAccessLocation():
"""
What type of non-attribute data does this node access
Members:
E_USD : Accesses the USD stage data
E_GLOBAL : Accesses data that is not part of the node or node type
E_STATIC : Accesses data that is shared by every instance of a particular node type
E_TOPOLOGY : Accesses information on the topology of the graph to which the node belongs
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
E_GLOBAL: omni.graph.core._omni_graph_core.eAccessLocation # value = <eAccessLocation.E_GLOBAL: 1>
E_STATIC: omni.graph.core._omni_graph_core.eAccessLocation # value = <eAccessLocation.E_STATIC: 2>
E_TOPOLOGY: omni.graph.core._omni_graph_core.eAccessLocation # value = <eAccessLocation.E_TOPOLOGY: 3>
E_USD: omni.graph.core._omni_graph_core.eAccessLocation # value = <eAccessLocation.E_USD: 0>
__members__: dict # value = {'E_USD': <eAccessLocation.E_USD: 0>, 'E_GLOBAL': <eAccessLocation.E_GLOBAL: 1>, 'E_STATIC': <eAccessLocation.E_STATIC: 2>, 'E_TOPOLOGY': <eAccessLocation.E_TOPOLOGY: 3>}
pass
class eAccessType():
"""
How does the node access the data described by the enum eAccessLocation
Members:
E_NONE : There is no access to data of the associated type
E_READ : There is only read access to data of the associated type
E_WRITE : There is only write access to data of the associated type
E_READ_WRITE : There is both read and write access to data of the associated type
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
E_NONE: omni.graph.core._omni_graph_core.eAccessType # value = <eAccessType.E_NONE: 0>
E_READ: omni.graph.core._omni_graph_core.eAccessType # value = <eAccessType.E_READ: 1>
E_READ_WRITE: omni.graph.core._omni_graph_core.eAccessType # value = <eAccessType.E_READ_WRITE: 3>
E_WRITE: omni.graph.core._omni_graph_core.eAccessType # value = <eAccessType.E_WRITE: 2>
__members__: dict # value = {'E_NONE': <eAccessType.E_NONE: 0>, 'E_READ': <eAccessType.E_READ: 1>, 'E_WRITE': <eAccessType.E_WRITE: 2>, 'E_READ_WRITE': <eAccessType.E_READ_WRITE: 3>}
pass
class eComputeRule():
"""
How the node is allowed to be computed
Members:
E_DEFAULT : Nodes are computed according to the default evaluator rules
E_ON_REQUEST : The evaluator may skip computing this node until explicitly requested with INode::requestCompute
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
E_DEFAULT: omni.graph.core._omni_graph_core.eComputeRule # value = <eComputeRule.E_DEFAULT: 0>
E_ON_REQUEST: omni.graph.core._omni_graph_core.eComputeRule # value = <eComputeRule.E_ON_REQUEST: 1>
__members__: dict # value = {'E_DEFAULT': <eComputeRule.E_DEFAULT: 0>, 'E_ON_REQUEST': <eComputeRule.E_ON_REQUEST: 1>}
pass
class ePurityStatus():
"""
The purity of the node implementation. For some context, a "pure" node is
one whose initialize, compute, and release methods are entirely deterministic,
i.e. they will always produce the same output attribute values for a given set
of input attribute values, and do not access, rely on, or otherwise mutate data
external to the node's scope
Members:
E_IMPURE : Node is assumed to not be pure
E_PURE : Node can be considered pure if explicitly specified by the node author
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
E_IMPURE: omni.graph.core._omni_graph_core.ePurityStatus # value = <ePurityStatus.E_IMPURE: 0>
E_PURE: omni.graph.core._omni_graph_core.ePurityStatus # value = <ePurityStatus.E_PURE: 1>
__members__: dict # value = {'E_IMPURE': <ePurityStatus.E_IMPURE: 0>, 'E_PURE': <ePurityStatus.E_PURE: 1>}
pass
class eThreadSafety():
"""
How thread safe is the node during evaluation
Members:
E_SAFE : Nodes can be evaluated in multiple threads safely
E_UNSAFE : Nodes cannot be evaluated in multiple threads safely
E_UNKNOWN : The thread safety status of the node type is unknown
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
E_SAFE: omni.graph.core._omni_graph_core.eThreadSafety # value = <eThreadSafety.E_SAFE: 0>
E_UNKNOWN: omni.graph.core._omni_graph_core.eThreadSafety # value = <eThreadSafety.E_UNKNOWN: 2>
E_UNSAFE: omni.graph.core._omni_graph_core.eThreadSafety # value = <eThreadSafety.E_UNSAFE: 1>
__members__: dict # value = {'E_SAFE': <eThreadSafety.E_SAFE: 0>, 'E_UNSAFE': <eThreadSafety.E_UNSAFE: 1>, 'E_UNKNOWN': <eThreadSafety.E_UNKNOWN: 2>}
pass
class eVariableScope():
"""
Scope in which the variable has been made available
Members:
E_PRIVATE : Variable is accessible only to its graph
E_READ_ONLY : Variable can be read by other graphs
E_PUBLIC : Variable can be read/written by other graphs
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
E_PRIVATE: omni.graph.core._omni_graph_core.eVariableScope # value = <eVariableScope.E_PRIVATE: 0>
E_PUBLIC: omni.graph.core._omni_graph_core.eVariableScope # value = <eVariableScope.E_PUBLIC: 2>
E_READ_ONLY: omni.graph.core._omni_graph_core.eVariableScope # value = <eVariableScope.E_READ_ONLY: 1>
__members__: dict # value = {'E_PRIVATE': <eVariableScope.E_PRIVATE: 0>, 'E_READ_ONLY': <eVariableScope.E_READ_ONLY: 1>, 'E_PUBLIC': <eVariableScope.E_PUBLIC: 2>}
pass
def _commit_output_attributes_data(python_commit_db: dict) -> None:
"""
For internal use only. Batch commit of attribute values
Args:
python_commit_db : Dictionary of attributes as keys and data as values
"""
def _prefetch_input_attributes_data(python_prefetch_db: list) -> list:
"""
For internal use only.
Args:
python_prefetch_db : List of attributes
Returns:
list[Any]: Prefetched attribute values
"""
def acquire_interface(plugin_name: str = None, library_path: str = None) -> ComputeGraph:
pass
def attach(stage_id: int, mps: float) -> None:
"""
Attach the graph to a particular stage.
Args:
stage_id (int): The stage id of the stage to attach to
mps (float): the meters per second setting for the stage
"""
def deregister_node_type(name: str) -> bool:
"""
Deregisters a python subnode type with OmniGraph.
Args:
name (str): Name of the Python node type being deregistered
Returns:
bool: True if the deregistration was successful, else False
"""
def deregister_post_load_file_format_upgrade_callback(postload_handle: int) -> None:
"""
De-registers the postload callback to be invoked when the file format version changes.
Args:
postload_handle (int): The handle that was returned during the register_post_load_file_format_upgrade_callback call
"""
def deregister_pre_load_file_format_upgrade_callback(preload_handle: int) -> None:
"""
De-registers the preload callback to be invoked when the file format version changes.
Args:
preload_handle (int): The handle that was returned during the register_pre_load_file_format_upgrade_callback call
"""
def detach() -> None:
"""
Detaches the graph from the currently attached stage.
"""
def get_all_graphs() -> typing.List[Graph]:
"""
Get all of the top-level non-orchestration graphs
Returns:
list[omni.graph.core.Graph]: A list of the top level graphs (non-orchestration) in OmniGraph.
"""
def get_all_graphs_and_subgraphs() -> typing.List[Graph]:
"""
Get all of the non-orchestration graphs
Returns:
list[omni.graph.core.Graph]: A list of the (non-orchestration) in OmniGraph.
"""
def get_bundle_tree_factory_interface() -> IBundleFactory:
"""
Gets an object that can interface with an IBundleFactory
Returns:
omni.graph.core.IBundleFactory: Object that can interface with the bundle tree
"""
def get_compute_graph_contexts() -> typing.List[GraphContext]:
"""
Gets all of the current graph contexts
Returns:
list[omni.graph.core.GraphContext]: A list of all graph contexts in OmniGraph.
"""
def get_global_orchestration_graphs() -> typing.List[Graph]:
"""
Gets the global orchestration graphs
Returns:
list[omni.graph.core.Graph]: A list of the global orchestration graphs that house all other graphs.
"""
def get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage: GraphPipelineStage) -> typing.List[Graph]:
"""
Returns a list of the global orchestration graphs that house all other graphs for a given pipeline stage.
Args:
pipeline_stage (omni.graph.core.GraphPipelineStage): The pipeline stage in question
Returns:
list[omni.graph.core.Graph]: A list of the global orchestration graphs in the given pipeline stage
"""
def get_graph_by_path(path: str) -> object:
"""
Finds the graph with the given path.
Args:
path (str): The path of the graph. For example "/World/PushGraph"
Returns:
omni.graph.core.Graph: The matching graph, or None if it was not found.
"""
def get_graphs_in_pipeline_stage(pipeline_stage: GraphPipelineStage) -> typing.List[Graph]:
"""
Returns a list of the non-orchestration graphs for a given pipeline stage (simulation, pre-render, post-render)
Args:
pipeline_stage (omni.graph.core.GraphPipelineStage): The pipeline stage in question
Returns:
list[omni.graph.core.Graph]: The list of graphs belonging to the pipeline stage
"""
def get_node_by_path(path: str) -> object:
"""
Get a node that lives at a given path
Args:
path (str): Path at which to find the node
Returns:
omni.graph.core.Node: The node corresponding to a node path in OmniGraph, None if no node was found at that path.
"""
def get_node_categories_interface() -> INodeCategories:
"""
Gets an object for accessing the node categories
Returns:
omni.graph.core.INodeCategories: Object that can interface with the category data
"""
def get_node_type(node_type_name: str) -> NodeType:
"""
Returns the registered node type object with the given name.
Args:
node_type_name (str): Name of the registered NodeType to find and return
Returns:
omni.graph.core.NodeType: NodeType object registered with the given name, None if it is not registered
"""
def get_registered_nodes() -> typing.List[str]:
"""
Get the currently registered node type names
Returns:
list[str]: The list of names of node types currently registered
"""
def is_global_graph_prim(prim_path: str) -> bool:
"""
Determines if the prim path passed in represents a prim that is backing a global graph
Args:
prim_path (str): The path to the prim in question
Returns:
bool: True if the prim path represents a prim that is backing a global graph, False otherwise
"""
def on_shutdown() -> None:
"""
For internal use only. Called to allow the Python API to clean up prior to the extension being unloaded.
"""
def register_node_type(name: object, version: int) -> None:
"""
Registers a new python subnode type with OmniGraph.
Args:
name (str): Name of the Python node type being registered
version (int): Version number of the Python node type being registered
"""
def register_post_load_file_format_upgrade_callback(callback: object) -> int:
"""
Registers a callback to be invoked when the file format version changes. Happens after the
file has already been parsed and stage attached to. The callback takes 3 parameters: the old file format version,
the new file format version, and the affected graph object.
Args:
callback (callable): The callback function
Returns:
int: A handle that could be used for deregistration. Note the calling module is responsible for deregistration
of the callback in all circumstances, including where the extension is hot-reloaded.
"""
def register_pre_load_file_format_upgrade_callback(callback: object) -> int:
"""
Registers a callback to be invoked when the file format version changes. Happens before the
file has already been parsed and stage attached to. The callback takes 3 parameters: the old file format version,
the new file format version, and a graph object (always invalid since the graph has not been created yet).
Args:
callback (callable): The callback function
Returns:
int: A handle that could be used for deregistration. Note the calling module is responsible for deregistration
of the callback in all circumstances, including where the extension is hot-reloaded.
"""
def register_python_node() -> None:
"""
Registers the unique Python node type with OmniGraph. This houses all of the Python node implementations as subtypes.
"""
def release_interface(arg0: ComputeGraph) -> None:
pass
def set_test_failure(has_failure: bool) -> None:
"""
Sets or clears a generic test failure.
Args:
has_failure (bool): If True then increment the test failure count, else clear it.
"""
def shutdown_compute_graph() -> None:
"""
Shuts down the compute graph. All data not backed by USD will be lost.
"""
def test_failure_count() -> int:
"""
Gets the number of active test failures
Returns:
int: The number of currently active test failures.
"""
def update(current_time: float, elapsed_time: float) -> None:
"""
Ticks the graph with the current time and elapsed time.
Args:
current_time (float): The current time
elapsed_time (float): The elapsed time since the last tick
"""
ACCORDING_TO_CONTEXT_GRAPH_INDEX = 18446744073709551614
APPLIED_SCHEMA: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.APPLIED_SCHEMA: 11>
ASSET: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.ASSET: 12>
AUTHORING_GRAPH_INDEX = 18446744073709551615
BOOL: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.BOOL: 1>
BUNDLE: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.BUNDLE: 16>
COLOR: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.COLOR: 4>
CONNECTION: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.CONNECTION: 14>
DOUBLE: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.DOUBLE: 9>
ERROR: omni.graph.core._omni_graph_core.Severity # value = <Severity.ERROR: 2>
EXECUTION: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.EXECUTION: 13>
FLOAT: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.FLOAT: 8>
FRAME: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.FRAME: 8>
HALF: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.HALF: 7>
INFO: omni.graph.core._omni_graph_core.Severity # value = <Severity.INFO: 0>
INSTANCING_GRAPH_TARGET_PATH = '_OMNI_GRAPH_TARGET'
INT: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.INT: 3>
INT64: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.INT64: 5>
MATRIX: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.MATRIX: 14>
NONE: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.NONE: 0>
NORMAL: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.NORMAL: 2>
OBJECT_ID: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.OBJECT_ID: 15>
PATH: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.PATH: 17>
POSITION: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.POSITION: 3>
PRIM: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.PRIM: 13>
PRIM_TYPE_NAME: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.PRIM_TYPE_NAME: 12>
QUATERNION: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.QUATERNION: 6>
RELATIONSHIP: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.RELATIONSHIP: 11>
TAG: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.TAG: 15>
TARGET: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TARGET: 20>
TEXCOORD: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TEXCOORD: 5>
TEXT: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TEXT: 10>
TIMECODE: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TIMECODE: 9>
TOKEN: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.TOKEN: 10>
TRANSFORM: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.TRANSFORM: 7>
UCHAR: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.UCHAR: 2>
UINT: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.UINT: 4>
UINT64: omni.graph.core._omni_graph_core.BaseDataType # value = <BaseDataType.UINT64: 6>
UNKNOWN: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.UNKNOWN: 21>
VECTOR: omni.graph.core._omni_graph_core.AttributeRole # value = <AttributeRole.VECTOR: 1>
WARNING: omni.graph.core._omni_graph_core.Severity # value = <Severity.WARNING: 1>
_internal = omni.graph.core._omni_graph_core._internal
_og_unstable = omni.graph.core._omni_graph_core._og_unstable
| 198,295 |
unknown
| 37.729687 | 838 | 0.62404 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/commands.py
|
import traceback
import omni.graph.tools as __ogt
from ._impl.commands import * # noqa: F401,PLW0401,PLW0614
_trace = "".join(traceback.format_stack())
__ogt.DeprecatedImport(f"Import 'omni.graph.core as og; help(og.cmds)' to access the OmniGraph commands\n{_trace}")
| 272 |
Python
| 29.33333 | 115 | 0.735294 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/__init__.py
|
"""
This file contains the interfaces that external Python scripts can use.
Import this file and use the APIs exposed below.
To get documentation on this module and methods import this file into a Python interpreter and run dir/help, like this:
.. code-block:: python
import omni.graph.core as og
help(og.get_graph_by_path)
"""
# fmt: off
# isort: off
import omni.core # noqa: F401 (Required for proper resolution of ONI wrappers)
# Get the bindings into the module
from . import _omni_graph_core # noqa: F401,PLW0406
from ._omni_graph_core import *
from ._impl.extension import _PublicExtension # noqa: F401
from ._impl.autonode.type_definitions import (
Color3d,
Color3f,
Color3h,
Color4d,
Color4f,
Color4h,
Double,
Double2,
Double3,
Double4,
Float,
Float2,
Float3,
Float4,
Half,
Half2,
Half3,
Half4,
Int,
Int2,
Int3,
Int4,
Matrix2d,
Matrix3d,
Matrix4d,
Normal3d,
Normal3f,
Normal3h,
Point3d,
Point3f,
Point3h,
Quatd,
Quatf,
Quath,
TexCoord2d,
TexCoord2f,
TexCoord2h,
TexCoord3d,
TexCoord3f,
TexCoord3h,
Timecode,
Token,
TypeRegistry,
UChar,
UInt,
Vector3d,
Vector3f,
Vector3h,
)
from ._impl.attribute_types import get_port_type_namespace
from ._impl.attribute_values import AttributeDataValueHelper
from ._impl.attribute_values import AttributeValueHelper
from ._impl.attribute_values import WrappedArrayType
from ._impl.bundles import Bundle
from ._impl.bundles import BundleContainer
from ._impl.bundles import BundleContents
from ._impl.bundles import BundleChanges
from ._impl.commands import cmds
from ._impl.controller import Controller
from ._impl.data_typing import data_shape_from_type
from ._impl.data_typing import DataWrapper
from ._impl.data_typing import Device
from ._impl.data_view import DataView
from ._impl.database import Database
from ._impl.database import DynamicAttributeAccess
from ._impl.database import DynamicAttributeInterface
from ._impl.database import PerNodeKeys
from ._impl.dtypes import Dtype
from ._impl.errors import OmniGraphError
from ._impl.errors import OmniGraphValueError
from ._impl.errors import ReadOnlyError
from ._impl.extension_information import ExtensionInformation
from ._impl.graph_controller import GraphController
from ._impl.inspection import OmniGraphInspector
from ._impl.node_controller import NodeController
from ._impl.object_lookup import ObjectLookup
from ._impl.runtime import RuntimeAttribute
from ._impl.settings import Settings
from ._impl.threadsafety_test_utils import ThreadsafetyTestUtils
from ._impl.traversal import traverse_downstream_graph
from ._impl.traversal import traverse_upstream_graph
from ._impl.type_resolution import resolve_base_coupled
from ._impl.type_resolution import resolve_fully_coupled
from ._impl.utils import attribute_value_as_usd
from ._impl.utils import get_graph_settings
from ._impl.utils import get_kit_version
from ._impl.utils import GraphSettings
from ._impl.utils import in_compute
from ._impl.utils import is_attribute_plain_data
from ._impl.utils import is_in_compute
from ._impl.utils import python_value_as_usd
from ._impl.utils import TypedValue
from . import autonode
from . import typing
from . import _unstable
# ==============================================================================================================
# These are symbols that should technically be prefaced with an underscore because they are used internally but
# not part of the public API but that would cause a lot of refactoring work so for now they are just added to the
# module contents but not the module exports.
# _ _ _____ _____ _____ ______ _ _
# | | | |_ _| __ \| __ \| ____| \ | |
# | |__| | | | | | | | | | | |__ | \| |
# | __ | | | | | | | | | | __| | . ` |
# | | | |_| |_| |__| | |__| | |____| |\ |
# |_| |_|_____|_____/|_____/|______|_| \_|
#
from ._impl.generate_ogn import generate_ogn_from_node
from ._impl.registration import PythonNodeRegistration
from ._impl.utils import load_example_file
from ._impl.utils import remove_attributes_if
from ._impl.utils import sync_to_usd
# ==============================================================================================================
# Soft-deprecated imports. Kept around for backward compatibility for one version.
# _____ ______ _____ _____ ______ _____ _______ ______ _____
# | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
# | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
# | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
# | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
# |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
#
from omni.graph.tools import RenamedClass as __RenamedClass # pylint: disable=wrong-import-order
from omni.graph.tools.ogn import MetadataKeys as __MetadataKeys # pylint: disable=wrong-import-order
MetadataKeys = __RenamedClass(__MetadataKeys, "MetadataKeys", "MetadataKeys has moved to omni.graph.tools.ogn")
# Ready for deletion, once omni.graph.window has removed its usage - OM-96121
def get_global_container_graphs() -> list[_omni_graph_core.Graph]:
import carb
carb.log_warn("get_global_container_graphs() has been deprecated - use get_global_orchestration_graphs() instead")
return _omni_graph_core.get_global_orchestration_graphs()
# ==============================================================================================================
# The bindings may have internal (single-underscore prefix) and external symbols. To be consistent with our export
# rules the internal symbols will be part of the module but not part of the published __all__ list, and the external
# symbols will be in both.
__bindings = []
for __bound_name in dir(_omni_graph_core):
# TODO: Right now the bindings and the core both define the same object type so they both can't be exported
# here so remove it from the bindings and it will be dealt with later.
if __bound_name in ["Bundle"]:
continue
if not __bound_name.startswith("__"):
if not __bound_name.startswith("_"):
__bindings.append(__bound_name)
globals()[__bound_name] = getattr(_omni_graph_core, __bound_name)
__all__ = __bindings + [
"attribute_value_as_usd",
"AttributeDataValueHelper",
"AttributeValueHelper",
"autonode",
"Bundle",
"BundleContainer",
"BundleContents",
"BundleChanges",
"cmds",
"Controller",
"data_shape_from_type",
"Database",
"DataView",
"DataWrapper",
"Device",
"Dtype",
"DynamicAttributeAccess",
"DynamicAttributeInterface",
"ExtensionInformation",
"get_graph_settings",
"get_kit_version",
"get_port_type_namespace",
"GraphController",
"GraphSettings",
"in_compute",
"is_attribute_plain_data",
"is_in_compute",
"MetadataKeys",
"NodeController",
"ObjectLookup",
"OmniGraphError",
"OmniGraphInspector",
"OmniGraphValueError",
"PerNodeKeys",
"python_value_as_usd",
"ReadOnlyError",
"resolve_base_coupled",
"resolve_fully_coupled",
"RuntimeAttribute",
"Settings",
"ThreadsafetyTestUtils",
"TypedValue",
"typing",
"WrappedArrayType",
"traverse_downstream_graph",
"traverse_upstream_graph",
"Color3d",
"Color3f",
"Color3h",
"Color4d",
"Color4f",
"Color4h",
"Double",
"Double2",
"Double3",
"Double4",
"Float",
"Float2",
"Float3",
"Float4",
"Half",
"Half2",
"Half3",
"Half4",
"Int",
"Int2",
"Int3",
"Int4",
"Matrix2d",
"Matrix3d",
"Matrix4d",
"Normal3d",
"Normal3f",
"Normal3h",
"Point3d",
"Point3f",
"Point3h",
"Quatd",
"Quatf",
"Quath",
"TexCoord2d",
"TexCoord2f",
"TexCoord2h",
"TexCoord3d",
"TexCoord3f",
"TexCoord3h",
"Timecode",
"Token",
"TypeRegistry",
"UChar",
"UInt",
"Vector3d",
"Vector3f",
"Vector3h",
]
_HIDDEN = [
"generate_ogn_from_node",
"get_global_container_graphs",
"PythonNodeRegistration",
"load_example_file",
"register_ogn_nodes",
"remove_attributes_if",
"sync_to_usd",
]
# isort: on
# fmt: on
| 8,492 |
Python
| 29.117021 | 119 | 0.606689 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/setup.py
|
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name="torch_wrap",
ext_modules=[CUDAExtension("torch_wrap", ["Py_WrapTensor.cpp"])],
cmdclass={"build_ext": BuildExtension},
)
| 244 |
Python
| 26.222219 | 69 | 0.733607 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/autonode.py
|
"""AutoNode - module for decorating code to populate it into OmniGraph nodes.
Allows generating nodes by decorating free functions, classes and modules by adding `@AutoFunc()` or `@AutoClass()` to
the declaration of the class.
Generating code relies on function signatures provided by python's type annotations, therefore the module only supports
native python types with `__annotations__`. CPython classes need need to be wrapped for now.
"""
from ._impl.autonode.autonode import (
AutoClass,
AutoFunc,
register_autonode_type_extension,
unregister_autonode_type_extension,
)
from ._impl.autonode.event import IEventStream
from ._impl.autonode.type_definitions import (
AutoNodeDefinitionGenerator,
AutoNodeDefinitionWrapper,
AutoNodeTypeConversion,
)
__all__ = [
"AutoClass",
"AutoFunc",
"AutoNodeDefinitionGenerator",
"AutoNodeDefinitionWrapper",
"AutoNodeTypeConversion",
"IEventStream",
"register_autonode_type_extension",
"unregister_autonode_type_extension",
]
| 1,030 |
Python
| 31.218749 | 119 | 0.750485 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/omnigraph_utils.py
|
from omni.graph.tools import DeprecationError
raise DeprecationError("Import of omnigraph_utils no longer supported. Use 'import omni.graph.core as og' instead.")
| 164 |
Python
| 40.24999 | 116 | 0.810976 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_1_33.py
|
"""Backward compatible module for omni.graph. version 1.33 and earlier.
This module contains everything that was formerly visible by default but will no longer be part of the Python API
for omni.graph. If there is something here you rely on contact the OmniGraph team and let them know.
Currently the module is in pre-deprecation, meaning you can still access everything here from the main module with
.. code-block:: python
import omni.graph. as og
og.pre_deprecated_but_still_visible()
Once the soft deprecation is enabled you will only be able to access the deprecated function with an explicit import:
.. code-block:: python
import omni.graph. as og
import omni.graph._1_33 as og1_33
if i_want_v1_33:
og1_33.soft_deprecated_but_still_accessible()
else:
og.current_function()
When hard deprecation is in place all functionality will be removed and import of this module will fail:
.. code-block:: python
import omni.graph._1_33 as ot1_33
# Raises DeprecationError
"""
from omni.graph.tools._impl.deprecate import (
DeprecatedClass,
DeprecatedImport,
DeprecateMessage,
RenamedClass,
deprecated_function,
)
from omni.graph.tools.ogn import MetadataKeys
# ==============================================================================================================
# Everything below here is deprecated, kept around for backward compatibility for one version.
# _____ ______ _____ _____ ______ _____ _______ ______ _____
# | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \
# | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | |
# | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | |
# | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| |
# |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/
#
from ._impl.attribute_types import extract_attribute_type_information, get_attribute_configuration
from ._impl.helpers import graph_iterator
from ._impl.object_lookup import ObjectLookup as _ObjectLookup
from ._impl.performance import OmniGraphPerformance
from ._impl.topology_commands import ConnectAttrsCommand as _ConnectAttrs
from ._impl.topology_commands import ConnectPrimCommand as _ConnectPrim
from ._impl.topology_commands import CreateAttrCommand as _CreateAttr
from ._impl.topology_commands import CreateGraphAsNodeCommand as _CreateGraphAsNode
from ._impl.topology_commands import CreateNodeCommand as _CreateNode
from ._impl.topology_commands import CreateSubgraphCommand as _CreateSubgraph
from ._impl.topology_commands import CreateVariableCommand as _CreateVariable
from ._impl.topology_commands import DeleteNodeCommand as _DeleteNode
from ._impl.topology_commands import DisconnectAllAttrsCommand as _DisconnectAllAttrs
from ._impl.topology_commands import DisconnectAttrsCommand as _DisconnectAttrs
from ._impl.topology_commands import DisconnectPrimCommand as _DisconnectPrim
from ._impl.topology_commands import RemoveAttrCommand as _RemoveAttr
from ._impl.topology_commands import RemoveVariableCommand as _RemoveVariable
from ._impl.utils import is_attribute_plain_data, temporary_setting
from ._impl.v1_5_0.context_helper import ContextHelper
from ._impl.v1_5_0.omnigraph_helper import (
BundledAttribute_t,
ConnectData_t,
ConnectDatas_t,
CreateNodeData_t,
CreateNodeDatas_t,
CreatePrimData_t,
CreatePrimDatas_t,
DeleteNodeData_t,
DeleteNodeDatas_t,
DisconnectData_t,
DisconnectDatas_t,
OmniGraphHelper,
SetValueData_t,
SetValueDatas_t,
)
from ._impl.v1_5_0.replaced_functions import attribute_type_from_ogn_type_name, attribute_type_from_usd_type_name
from ._impl.v1_5_0.update_file_format import can_set_use_schema_prims_setting, update_to_include_schema
from ._impl.v1_5_0.utils import (
ALLOW_IMPLICIT_GRAPH_SETTING,
ATTRIBUTE_TYPE_HINTS,
ATTRIBUTE_TYPE_TYPE_HINTS,
DISABLE_PRIM_NODES_SETTING,
ENABLE_LEGACY_PRIM_CONNECTIONS,
EXTENDED_ATTRIBUTE_TYPE_HINTS,
NODE_TYPE_HINTS,
USE_SCHEMA_PRIMS_SETTING,
)
from ._impl.value_commands import DisableGraphCommand as _DisableGraph
from ._impl.value_commands import DisableGraphUSDHandlerCommand as _DisableGraphUSDHandler
from ._impl.value_commands import DisableNodeCommand as _DisableNode
from ._impl.value_commands import EnableGraphCommand as _EnableGraph
from ._impl.value_commands import EnableGraphUSDHandlerCommand as _EnableGraphUSDHandler
from ._impl.value_commands import EnableNodeCommand as _EnableNode
from ._impl.value_commands import RenameNodeCommand as _RenameNode
from ._impl.value_commands import RenameSubgraphCommand as _RenameSubgraph
from ._impl.value_commands import SetAttrCommand as _SetAttr
from ._impl.value_commands import SetAttrDataCommand as _SetAttrData
from ._impl.value_commands import SetVariableTooltipCommand as _SetVariableTooltip
__all__ = [
"ALLOW_IMPLICIT_GRAPH_SETTING",
"attribute_type_from_ogn_type_name",
"attribute_type_from_usd_type_name",
"ATTRIBUTE_TYPE_HINTS",
"ATTRIBUTE_TYPE_TYPE_HINTS",
"BundledAttribute_t",
"can_set_use_schema_prims_setting",
"ConnectAttrsCommand",
"ConnectData_t",
"ConnectDatas_t",
"ConnectPrimCommand",
"ContextHelper",
"CreateAttrCommand",
"CreateGraphAsNodeCommand",
"CreateNodeCommand",
"CreateNodeData_t",
"CreateNodeDatas_t",
"CreatePrimData_t",
"CreatePrimDatas_t",
"CreateSubgraphCommand",
"CreateVariableCommand",
"DeleteNodeCommand",
"DeleteNodeData_t",
"DeleteNodeDatas_t",
"deprecated_function",
"DeprecatedClass",
"DeprecatedImport",
"DeprecateMessage",
"DISABLE_PRIM_NODES_SETTING",
"DisableGraphCommand",
"DisableGraphUSDHandlerCommand",
"DisableNodeCommand",
"DisconnectAllAttrsCommand",
"DisconnectAttrsCommand",
"DisconnectData_t",
"DisconnectDatas_t",
"DisconnectPrimCommand",
"ENABLE_LEGACY_PRIM_CONNECTIONS",
"EnableGraphCommand",
"EnableGraphUSDHandlerCommand",
"EnableNodeCommand",
"EXTENDED_ATTRIBUTE_TYPE_HINTS",
"extract_attribute_type_information",
"get_attribute_configuration",
"graph_iterator",
"is_attribute_plain_data",
"MetadataKeys",
"NODE_TYPE_HINTS",
"OmniGraphHelper",
"OmniGraphPerformance",
"OmniGraphTypes",
"RemoveAttrCommand",
"RemoveVariableCommand",
"RenamedClass",
"RenameNodeCommand",
"RenameSubgraphCommand",
"SetAttrCommand",
"SetAttrDataCommand",
"SetValueData_t",
"SetValueDatas_t",
"SetVariableTooltipCommand",
"temporary_setting",
"update_to_include_schema",
"USE_SCHEMA_PRIMS_SETTING",
]
ConnectAttrsCommand = RenamedClass(
_ConnectAttrs, "ConnectAttrsCommand", "import omni.graph.core as og; og.cmds.ConnectAttrs"
)
ConnectPrimCommand = RenamedClass(
_ConnectPrim, "ConnectPrimCommand", "import omni.graph.core as og; og.cmds.ConnectPrim"
)
CreateAttrCommand = RenamedClass(_CreateAttr, "CreateAttrCommand", "import omni.graph.core as og; og.cmdsCreateAttr")
CreateGraphAsNodeCommand = RenamedClass(
_CreateGraphAsNode, "CreateGraphAsNodeCommand", "import omni.graph.core as og; og.cmds.CreateGraphAsNode"
)
CreateNodeCommand = RenamedClass(_CreateNode, "CreateNodeCommand", "import omni.graph.core as og; og.cmds.CreateNode")
CreateSubgraphCommand = RenamedClass(
_CreateSubgraph, "CreateSubgraphCommand", "import omni.graph.core as og; og.cmds.CreateSubgraph"
)
CreateVariableCommand = RenamedClass(
_CreateVariable, "CreateVariableCommand", "import omni.graph.core as og; og.cmds.CreateVariable"
)
DeleteNodeCommand = RenamedClass(_DeleteNode, "DeleteNodeCommand", "import omni.graph.core as og; og.cmds.DeleteNode")
DisableGraphCommand = RenamedClass(
_DisableGraph, "DisableGraphCommand", "import omni.graph.core as og; og.cmds.DisableGraph"
)
DisableGraphUSDHandlerCommand = RenamedClass(
_DisableGraphUSDHandler,
"DisableGraphUSDHandlerCommand",
"import omni.graph.core as og; og.cmds.DisableGraphUSDHandler",
)
DisableNodeCommand = RenamedClass(
_DisableNode, "DisableNodeCommand", "import omni.graph.core as og; og.cmds.DisableNode"
)
DisconnectAllAttrsCommand = RenamedClass(
_DisconnectAllAttrs, "DisconnectAllAttrsCommand", "import omni.graph.core as og; og.cmds.DisconnectAllAttrs"
)
DisconnectAttrsCommand = RenamedClass(
_DisconnectAttrs, "DisconnectAttrsCommand", "import omni.graph.core as og; og.cmds.DisconnectAttrs"
)
DisconnectPrimCommand = RenamedClass(
_DisconnectPrim, "DisconnectPrimCommand", "import omni.graph.core as og; og.cmds.DisconnectPrim"
)
EnableGraphCommand = RenamedClass(
_EnableGraph, "EnableGraphCommand", "import omni.graph.core as og; og.cmds.EnableGraph"
)
EnableGraphUSDHandlerCommand = RenamedClass(
_EnableGraphUSDHandler,
"EnableGraphUSDHandlerCommand",
"import omni.graph.core as og; og.cmds.EnableGraphUSDHandler",
)
EnableNodeCommand = RenamedClass(_EnableNode, "EnableNodeCommand", "import omni.graph.core as og; og.cmds.EnableNode")
OmniGraphTypes = RenamedClass(_ObjectLookup, "OmniGraphTypes")
RemoveAttrCommand = RenamedClass(_RemoveAttr, "RemoveAttrCommand", "import omni.graph.core as og; og.cmds.RemoveAttr")
RemoveVariableCommand = RenamedClass(
_RemoveVariable, "RemoveVariableCommand", "import omni.graph.core as og; og.cmds.RemoveVariable"
)
RenameNodeCommand = RenamedClass(_RenameNode, "RenameNodeCommand", "import omni.graph.core as og; og.cmds.RenameNode")
RenameSubgraphCommand = RenamedClass(
_RenameSubgraph, "RenameSubgraphCommand", "import omni.graph.core as og; og.cmds.RenameSubgraph"
)
SetAttrCommand = RenamedClass(_SetAttr, "SetAttrCommand", "import omni.graph.core as og; og.cmds.SetAttr")
SetAttrDataCommand = RenamedClass(
_SetAttrData, "SetAttrDataCommand", "import omni.graph.core as og; og.cmds.SetAttrData"
)
SetVariableTooltipCommand = RenamedClass(
_SetVariableTooltip, "SetVariableTooltipCommand", "import omni.graph.core as og; og.cmds.SetVariableTooltip"
)
| 10,113 |
Python
| 41.317991 | 118 | 0.722338 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_unstable.py
|
# =============================================================================================================================
# This submodule is work-in-progress and subject to change without notice
# _ _ _____ ______ _______ __ ______ _ _ _____ ______ ___ _ _____ _____ _____ _ __
# | | | |/ ____| ____| /\|__ __| \ \ / / __ \| | | | __ \ / __ \ \ / / \ | | | __ \|_ _|/ ____| |/ /
# | | | | (___ | |__ / \ | | \ \_/ / | | | | | | |__) | | | | \ \ /\ / /| \| | | |__) | | | | (___ | ' /
# | | | |\___ \| __| / /\ \ | | \ /| | | | | | | _ / | | | |\ \/ \/ / | . ` | | _ / | | \___ \| <
# | |__| |____) | |____ / ____ \| | | | | |__| | |__| | | \ \ | |__| | \ /\ / | |\ | | | \ \ _| |_ ____) | . \
# \____/|_____/|______| /_/ \_\_| |_| \____/ \____/|_| \_\ \____/ \/ \/ |_| \_| |_| \_\_____|_____/|_|\_|
from . import _omni_graph_core as __cpp_bindings
from ._impl.unstable.commands import cmds # noqa: F401
from ._impl.unstable.subgraph_compound_commands import ( # noqa: F401
validate_attribute_for_promotion_from_compound_subgraph,
validate_nodes_for_compound_subgraph,
)
# Import the c++ bindings from the _unstable submodule.
__bindings = []
for __bound_name in dir(__cpp_bindings._og_unstable): # noqa PLW0212
if not __bound_name.startswith("__"):
if not __bound_name.startswith("_"):
__bindings.append(__bound_name)
globals()[__bound_name] = getattr(__cpp_bindings._og_unstable, __bound_name) # noqa PLW0212
__all__ = __bindings + [
"cmds",
"validate_attribute_for_promotion_from_compound_subgraph",
"validate_nodes_for_compound_subgraph",
]
| 1,754 |
Python
| 55.612901 | 127 | 0.343786 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/typing.py
|
"""OmniGraph submodule that handles all of the OmniGraph API typing information.
.. code-block:: python
import omni.graph.core.typing as ogty
def do_attribute_stuff(attribute: ogty.Attribute_t):
pass
"""
from ._impl.typing import (
Attribute_t,
Attributes_t,
AttributeSpec_t,
AttributeSpecs_t,
AttributesWithValues_t,
AttributeType_t,
AttributeTypeSpec_t,
AttributeWithValue_t,
ExtendedAttribute_t,
Graph_t,
Graphs_t,
GraphSpec_t,
GraphSpecs_t,
NewNode_t,
Node_t,
Nodes_t,
NodeSpec_t,
NodeSpecs_t,
NodeType_t,
Prim_t,
PrimAttrs_t,
Prims_t,
)
from ._impl.utils import AttributeValue_t, AttributeValues_t, ValueToSet_t
__all__ = [
"Attribute_t",
"Attributes_t",
"AttributeSpec_t",
"AttributeSpecs_t",
"AttributesWithValues_t",
"AttributeType_t",
"AttributeTypeSpec_t",
"AttributeValue_t",
"AttributeValues_t",
"AttributeWithValue_t",
"ExtendedAttribute_t",
"Graph_t",
"Graphs_t",
"GraphSpec_t",
"GraphSpecs_t",
"NewNode_t",
"Node_t",
"Nodes_t",
"NodeSpec_t",
"NodeSpecs_t",
"NodeType_t",
"Prim_t",
"PrimAttrs_t",
"Prims_t",
"ValueToSet_t",
]
| 1,247 |
Python
| 19.129032 | 80 | 0.615878 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/bindings.py
|
"""Temporary measure for backwards compatibility to import bindings from old module structure.
The generated PyBind libraries used to be in omni/graph/core/bindings/. They were moved to
omni/graph/core to correspond to the example extension structure for Python imports. All this
file does is make the old import "import omni.graph.core.bindings._omni_graph_core" work the
same as the new one "import omni.graph.core._omni_graph_core"
"""
import omni.graph.core._omni_graph_core as bindings
_omni_graph_core = bindings
| 521 |
Python
| 46.454541 | 94 | 0.792706 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/inspection.py
|
"""Helpers for running inspection on OmniGraph objects"""
import json
from contextlib import suppress
from typing import Dict, List, Optional, Union
import carb
import omni.graph.core as og
from .errors import OmniGraphError
# The types the inspector understands
_OmniGraphObjectTypes = Union[og.Graph, og.GraphContext, og.GraphRegistry, og.NodeType]
class OmniGraphInspector:
"""Provides simple interfaces for inspection of OmniGraph objects"""
def __init__(self):
"""Import the inspection interface, logging a warning if it doesn't exist.
This allows the functions to silently fail, while still providing an alert to the user as to why their
inspection operations might not work as expected.
"""
try:
import omni.inspect as oi
except ImportError as error:
carb.log_warn(f"Load the omni.inspect extension to use OmniGraphInspector ({error})")
oi = None
self.__oi = oi
# ----------------------------------------------------------------------
def available(self) -> bool:
"""Returns true if the inspection capabilities are available"""
return self.__oi is not None
# ----------------------------------------------------------------------
def memory_use(self, omnigraph_object: _OmniGraphObjectTypes) -> int:
"""Returns the number of bytes of memory used by the object, if it supports it
Args:
omnigraph_object: Object whose memory use is to be inspected
Raises:
OmniGraphError: If the object type doesn't support memory inspection
"""
if not self.__oi:
return 0
if type(omnigraph_object) not in [og.GraphContext, og.NodeType]:
raise OmniGraphError("Memory use can only be inspected on graph contexts and node types")
memory_inspector = self.__oi.IInspectMemoryUse()
omnigraph_object.inspect(memory_inspector)
return memory_inspector.total_used()
# ----------------------------------------------------------------------
def as_text(self, omnigraph_object: _OmniGraphObjectTypes, file_path: Optional[str] = None) -> str:
"""Returns the serialized data belonging to the context (for debugging)
Args:
omnigraph_object: Object whose memory use is to be inspected
file_path: If a string then dump the output to a file at that path, otherwise return a string with the dump
Returns:
If no file_path was specified then return the inspected data.
If a file_path was specified then return the path where the data was written (should be the same)
Raises:
OmniGraphError: If the object type doesn't support memory inspection
"""
if not self.__oi:
return ""
if not isinstance(omnigraph_object, og.GraphContext):
raise OmniGraphError("Serialization only works on graph contexts")
serializer = self.__oi.IInspectSerializer()
if file_path is None:
serializer.set_output_to_string()
else:
serializer.output_to_file_path = file_path
omnigraph_object.inspect(serializer)
return serializer.as_string() if file_path is None else serializer.get_output_location()
# ----------------------------------------------------------------------
def as_json(
self,
omnigraph_object: _OmniGraphObjectTypes,
file_path: Optional[str] = None,
flags: Optional[List[str]] = None,
) -> str:
"""Outputs the JSON format data belonging to the context (for debugging)
Args:
omnigraph_object: Object whose memory use is to be inspected
file_path: If a string then dump the output to a file at that path, otherwise return a string with the dump
flags: Set of enabled flags on the inspection object. Valid values are:
maps: Show all of the attribute type maps (lots of redundancy here, and independent of data present)
noDataDetails: Hide the minutiae of where each attribute's data is stored in FlatCache
Returns:
If no file_path was specified then return the inspected data.
If a file_path was specified then return the path where the data was written (should be the same)
Raises:
OmniGraphError: If the object type doesn't support memory inspection
"""
if not self.__oi:
return "{}"
if not type(omnigraph_object) in [og.GraphContext, og.Graph, og.NodeType, og.GraphRegistry]:
raise OmniGraphError(
"JSON serialization only works on graphs, graph contexts, node types, and the registry"
)
if flags is None:
flags = []
serializer = self.__oi.IInspectJsonSerializer()
for flag in flags:
serializer.set_flag(flag, True)
if file_path is None:
serializer.set_output_to_string()
else:
serializer.output_to_file_path = file_path
omnigraph_object.inspect(serializer)
if "help" in flags:
return serializer.help_information()
return serializer.as_string() if file_path is None else serializer.get_output_location()
# ----------------------------------------------------------------------
def attribute_locations(self, context: og.GraphContext) -> Dict[str, Dict[str, int]]:
"""Find all of the attribute data locations within FlatCache for the given context.
Args:
context: Graph context whose FlatCache data is to be inspected
Returns:
Dictionary with KEY = path, VALUE = { attribute name : attribute memory location }
"""
if not self.__oi:
return {}
serializer = self.__oi.IInspectJsonSerializer()
serializer.set_output_to_string()
context.inspect(serializer)
ignored_suffixes = ["_gpuElemCount", "_elemCount", "_cpuElemCount"]
try:
json_data = json.loads(serializer.as_string())["GraphContext"]["FlatCache"]["Bucket Contents"]
locations = {}
for bucket_id, bucket_info in json_data.items():
with suppress(KeyError):
paths = bucket_info["Path List"]
path_locations = [{} for _ in paths] if paths else [{}]
for storage_name, storage_info in bucket_info["Mirrored Arrays"].items():
abort = False
for suffix in ignored_suffixes:
if storage_name.endswith(suffix):
abort = True
if abort:
continue
# If the storage has no CPU location ignore it for now
with suppress(KeyError):
location = storage_info["CPU Data Location"]
data_size = storage_info["CPU Data Size"]
data_size = data_size / len(paths) if paths else data_size
if paths:
for i, _path in enumerate(paths):
path_locations[i][storage_name] = hex(int(location))
location += data_size
else:
path_locations[0][storage_name] = hex(int(location))
if paths:
for i, path in enumerate(paths):
locations[path] = path_locations[i]
else:
locations[f"NULL{bucket_id}"] = path_locations[0]
return locations
except Exception as error:
raise OmniGraphError("Could not get the FlatCache contents to analyze") from error
| 7,945 |
Python
| 42.900552 | 119 | 0.567149 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/attribute_types.py
|
"""Support for nicer access to attribute types"""
from contextlib import suppress
import omni.graph.core as og
from .object_lookup import ObjectLookup
from .typing import AttributeWithValue_t
# Deprecated function support
from .v1_5_0.replaced_functions import BASE_DATA_TYPE_MAP # noqa
from .v1_5_0.replaced_functions import ROLE_MAP # noqa
from .v1_5_0.replaced_functions import attribute_type_from_ogn_type_name # noqa
from .v1_5_0.replaced_functions import attribute_type_from_usd_type_name # noqa
# Mapping of the port type onto the namespace that the port type will enforce on attributes with that type
PORT_TYPE_NAMESPACES = {
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: "inputs",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: "outputs",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: "state",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_UNKNOWN: "unknown",
}
# Mapping of the port type onto the namespace that the port type will enforce on attributes with that type
PORT_TYPE_NAMESPACES = {
og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: "inputs",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: "outputs",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: "state",
og.AttributePortType.ATTRIBUTE_PORT_TYPE_UNKNOWN: "unknown",
}
# ================================================================================
def get_port_type_namespace(port_type: og.AttributePortType) -> str:
"""Returns a string representing the namespace attributes of the named port type reside in"""
return PORT_TYPE_NAMESPACES[port_type]
# ----------------------------------------------------------------------
def get_attribute_configuration(attr: AttributeWithValue_t):
"""Get the array configuration information from the attribute.
Attributes can be simple, tuples, or arrays of either. The information on what this is will be
encoded in the attribute type name. This method decodes that type name to find out what type of
attribute data the attribute will use.
The method also gives the right answers for both Attribute and AttributeData with some suitable AttributeError
catches to special case on unimplemented methods.
Args:
attr: Attribute whose configuration is being determined
Returns:
Tuple of:
str: Name of the full/resolved data type used by the attribute (e.g. "float[3][]")
str: Name of the simple data type used by the attribute (e.g. "float")
bool: True if the data type is a tuple or array (e.g. "float3" or "float[]")
bool: True if the data type is a matrix and should be flattened (e.g. "matrixd[3]" or "framed[4][]")
Raises:
TypeError: If the attribute type is not yet supported
"""
# The actual data in extended types is the resolved type name; the attribute type is always token
ogn_type = attr.get_resolved_type() if isinstance(attr, og.Attribute) else attr.get_type()
type_name = ogn_type.get_ogn_type_name()
# The root name is important for lookup
root_type_name = ogn_type.get_base_type_name()
if ogn_type.base_type == og.BaseDataType.UNKNOWN and (
attr.get_extended_type()
in (og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION)
):
raise TypeError(f"Attribute '{attr.get_name()}' is not resolved, and so has no concrete type")
is_array_type = ogn_type.array_depth > 0 and ogn_type.role not in [og.AttributeRole.TEXT, og.AttributeRole.PATH]
is_matrix_type = (
type_name.startswith("matrix") or type_name.startswith("frame") or type_name.startswith("transform")
)
# Gather nodes automatically add one level of array to their attributes
is_gather_node = False
with suppress(AttributeError):
is_gather_node = attr.get_node().get_type_name() == "Gather"
if is_gather_node:
if is_array_type:
raise TypeError("Array types on Gather nodes are not yet supported in Python")
is_array_type = True
# Arrays of arrays are not yet supported in flatcache so they cannot be supported in Python
if ogn_type.array_depth > 1:
raise TypeError("Nested array types are not yet supported in Python")
return (type_name, root_type_name, is_array_type, is_matrix_type)
# ==============================================================================================================
def extract_attribute_type_information(attribute_object: AttributeWithValue_t) -> og.Type:
"""Decompose the type of an attribute into the parts relevant to getting and setting values.
The naming of the attribute get and set methods in the Python bindings are carefully constructed to correspond
to the ones returned here, to avoid construction of huge lookup tables. It makes the types instantly recognize
newly added support, and it makes them easier to expand, at the cost of being less explicit about the
correspondance between type and method.
Note:
If the attribute type is determined at runtime (e.g. Union or Any) then the resolved type is used.
When the type is not yet resolved the raw types of the attributes are returned (usually "token")
Args:
attribute_object: Attribute-like object that has an attribute type that can be decomposed
Returns:
og.Type with the type information of the attribute_object
Raises:
TypeError: If the attribute type or attribute type object is not supported
"""
# The actual data in extended types is the resolved type name; the attribute type is always token
type_name = None
with suppress(AttributeError):
if attribute_object.get_extended_type() in [
og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY,
og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION,
]:
type_name = attribute_object.get_resolved_type()
if type_name is None:
try:
type_name = attribute_object.get_type_name()
except AttributeError:
type_name = attribute_object.get_type()
# If a type was directly returned then it already has the information required
if isinstance(type_name, og.Type):
return type_name
return og.AttributeType.type_from_sdf_type_name(type_name)
# ==============================================================================================================
def get_attr_type(attr_info: AttributeWithValue_t):
"""
Get the type for the given attribute, taking in to account extended type
Args:
attr: Attribute whose type is to be determined
Returns:
The type of the attribute
"""
if isinstance(attr_info, og.AttributeData):
return attr_info.get_type()
attribute = ObjectLookup.attribute(attr_info)
if attribute is None:
raise og.OmniGraphError(f"Could not identify attribute from {attr_info} to get its type")
return attribute.get_resolved_type()
| 7,019 |
Python
| 43.150943 | 116 | 0.671748 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/helpers.py
|
"""
Classes and functions that provide simpler access to data through the ABI from Python.
Typically this creates a Pythonic layer over top of the ABI; flatcache in particular.
"""
import omni.graph.core as og # noqa
import omni.graph.tools as ogt
# ==============================================================================================================
# Backward compatibility
from .errors import OmniGraphError # noqa
from .object_lookup import ObjectLookup # noqa
from .utils import ATTRIBUTE_TYPE_HINTS # noqa
from .utils import NODE_TYPE_HINTS # noqa
from .utils import graph_iterator # noqa
OmniGraphTypes = ogt.RenamedClass(ObjectLookup, "OmniGraphTypes")
from .errors import ReadOnlyError # noqa
from .v1_5_0.context_helper import ContextHelper # noqa
from .v1_5_0.omnigraph_helper import OmniGraphHelper # noqa
| 839 |
Python
| 40.999998 | 112 | 0.676996 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/graph_controller.py
|
"""Helpers for modifying the contents of a graph"""
from __future__ import annotations
import asyncio
from enum import Enum
from typing import Any, Dict, List, Optional, Tuple, Union
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
import omni.kit
import omni.usd
from carb import log_info
from pxr import Sdf, Tf, Usd
from .commands import cmds
from .object_lookup import ObjectLookup
from .typing import (
AttributeSpec_t,
Graph_t,
NewNode_t,
Node_t,
Nodes_t,
NodeType_t,
Path_t,
Prim_t,
PrimAttrs_t,
Variable_t,
VariableName_t,
VariableType_t,
)
from .utils import DBG, _flatten_arguments, _Unspecified
# ==============================================================================================================
class GraphController:
"""Helper class that provides a simple interface to modifying the contents of a graph"""
# --------------------------------------------------------------------------------------------------------------
def __init__(self, *args, **kwargs):
"""Initializes the class with a particular configuration.
The arguments are flexible so that classes can initialize only what they need for the calls they
will be making. Both arguments are optional, and there may be other arguments present that will be ignored.
Args:
update_usd (bool): Should any graphs, nodes, and prims referenced in operations be updated immediately to
USD? (default True)
undoable (bool): If True the operations performed with this instance of the class are added to the undo
queue, else they are done immediately and forgotten (default True)
"""
(self.__update_usd, self.__undoable) = _flatten_arguments(
optional=[("update_usd", True), ("undoable", True)],
args=args,
kwargs=kwargs,
)
# Dual function methods that can be called either from an object or directly from the class
self.create_graph = self.__create_graph_obj
self.create_node = self.__create_node_obj
self.create_prim = self.__create_prim_obj
self.create_variable = self.__create_variable_obj
self.delete_node = self.__delete_node_obj
self.expose_prim = self.__expose_prim_obj
self.connect = self.__connect_obj
self.disconnect = self.__disconnect_obj
self.disconnect_all = self.__disconnect_all_obj
# --------------------------------------------------------------------------------------------------------------
@classmethod
def create_graph(obj, *args, **kwargs) -> og.Graph: # noqa: N804,PLC0202,PLE0202
"""Create a graph from the description
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. The second argument can be positional or by keyword and is
mandatory, resulting in an error if omitted. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
.. code-block:: python
new_graph = og.GraphController.create_graph("/TestGraph")
controller = og.GraphController(undoable=True)
controller.create_graph({"graph_path": "/UndoableGraph", "evaluator_name": "execution"})
Args:
obj: Either cls or self, depending on how the function was called
graph_id: Parameters describing the graph to be created. If the graph is just a path then a default graph
will be created at that location. If the identifier is a dictionary then it will be interpreted
as a set of parameters describing the type of graph to create:
"graph_path": Full path to the graph prim to be created to house the OmniGraph
"evaluator_name": Type of evaluator the graph should use (default "push")
"fc_backing_type": og.GraphBackingType that tells you what kind of FlatCache to use for graph data
(default og.GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED)
"pipeline_stage": og.GraphPipelineStage that tells you which pipeline stage this graph fits into
(default og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION)
"evaluation_mode": og.GraphEvaluationMode that tells you which evaluation mode this graph uses
(default og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC)
update_usd (bool): If specified then override whether to create the graph with a USD backing (default True)
undoable (bool): If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Returns:
(og.Graph) The created graph
Raises:
og.OmniGraphError if the graph creation failed for any reason
"""
return obj.__create_graph(obj, args=args, kwargs=kwargs)
def __create_graph_obj(self, *args, **kwargs) -> og.Graph:
"""Implements :py:meth:`.GraphController.create_graph` when called as an object method"""
return self.__create_graph(
self, update_usd=self.__update_usd, undoable=self.__undoable, args=args, kwargs=kwargs
)
@staticmethod
def __create_graph(
obj,
graph_id: Union[Graph_t, Dict[str, Any]] = _Unspecified,
update_usd: bool = True,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
) -> og.Graph:
"""Implements :py:meth:`.GraphController.create_graph`"""
(graph_id, update_usd, undoable) = _flatten_arguments(
mandatory=[("graph_id", graph_id)],
optional=[("update_usd", update_usd), ("undoable", undoable)],
args=args,
kwargs=kwargs,
)
def __default_create_args(graph_path: str) -> Dict[str, Any]:
"""Returns the default arguments for the CreateGraphAsNode command for the given graph path"""
return {
"graph_path": graph_path,
"node_name": graph_path.rsplit("/", 1)[1],
"evaluator_name": "push",
"is_global_graph": True,
"backed_by_usd": True if update_usd is None else update_usd,
"fc_backing_type": og.GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED,
"pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION,
"evaluation_mode": og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC,
}
def __add_orchestration_graph(graph_cmd_args: Dict[str, Any]):
"""Modify the dictionary to include the appropriate orchestration graph as a parameter"""
try:
pipeline_stage = graph_cmd_args["pipeline_stage"]
orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage)
graph_cmd_args["graph"] = orchestration_graphs[0]
except (KeyError, IndexError) as error:
raise og.OmniGraphError(f"Could not find orchestration graph for stage {pipeline_stage}") from error
success = True
graph_node = None
if isinstance(graph_id, str):
cmd_args = __default_create_args(graph_id)
elif isinstance(graph_id, dict):
if "graph_path" not in graph_id:
raise og.OmniGraphError(f"Tried to create graph without graph path using {graph_id}")
cmd_args = __default_create_args(graph_id["graph_path"])
cmd_args.update(graph_id)
else:
raise og.OmniGraphError(f"Graph description must be a path or an argument dictionary, not {graph_id}")
__add_orchestration_graph(cmd_args)
if undoable:
(success, graph_node) = cmds.CreateGraphAsNode(**cmd_args)
else:
success = True
graph_node = cmds.imm.CreateGraphAsNode(**cmd_args)
if graph_node is None or not graph_node.is_valid() or not success:
raise og.OmniGraphError(f"Failed to wrap graph in node given {graph_id}")
graph = graph_node.get_wrapped_graph()
if graph is None:
raise og.OmniGraphError(f"Failed to construct graph given {graph_id}")
return graph
# --------------------------------------------------------------------------------------------------------------
@classmethod
def create_node(obj, *args, **kwargs) -> og.Graph: # noqa: N804,PLC0202,PLE0202
"""Create an OmniGraph node of the given type and version at the given path.
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. "node_id" and "node_type_id" are mandatory, and can be specified
either as positional or keyword arguments. All others are by keyword only and optional, defaulting to the value
set in the constructor in the object context where available, and the function defaults elsewhere.
.. code-block:: python
og.GraphController.create_node("/MyGraph/MyNode", "omni.graph.nodes.NodeType")
og.GraphController(update_usd=True).create_node("/MyGraph/MyNode", "omni.graph.nodes.NodeType")
og.GraphController.create_node("/MyGraph/MyNode", "omni.graph.nodes.NodeType", update_usd=True)
og.GraphController.create_node(node_id="/MyGraph/MyNode", node_type="omni.graph.nodes.NodeType")
Args:
obj: Either cls or self, depending on how the function was called
node_id: Absolute path, or (Relative Path, Graph) where the node will be constructed. If an absolute path
was passed in it must be part of an existing graph.
node_type_id: Unique identifier for the type of node to create (name or og.NodeType)
allow_exists: If True then succeed if a node with matching path, type, and version already exists. It is
still a failure if one of those properties on the existing node does not match.
version: Version of the node type to create. By default it creates the most recent.
update_usd: If specified then override whether to create the node with a USD backing or not (default True)
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Raises:
og.OmniGraphError: If one or more of the nodes could not be added to the scene for some reason.
Returns:
OmniGraph node or list of nodes added to the scene
"""
return obj.__create_node(obj, args=args, kwargs=kwargs)
def __create_node_obj(self, *args, **kwargs) -> og.Node:
"""Implements :py:meth:`.GraphController.create_node` when called as an object method"""
return self.__create_node(
self, update_usd=self.__update_usd, undoable=self.__undoable, args=args, kwargs=kwargs
)
@staticmethod
def __create_node(
obj,
node_id: NewNode_t = _Unspecified,
node_type_id: NodeType_t = _Unspecified,
allow_exists: bool = False,
version: int = None,
update_usd: bool = True,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
) -> og.Node:
"""Implements :py:meth:`.GraphController.create_node`"""
(node_id, node_type_id, allow_exists, version, update_usd, undoable) = _flatten_arguments(
mandatory=[("node_id", node_id), ("node_type_id", node_type_id)],
optional=[
("allow_exists", allow_exists),
("version", version),
("update_usd", update_usd),
("undoable", undoable),
],
args=args,
kwargs=kwargs,
)
_ = DBG and log_info(f"Create '{node_id}' of type '{node_type_id}', allow={allow_exists}, version={version}")
if version is not None:
raise og.OmniGraphError("Creating nodes with specific versions not supported")
graph = None
if isinstance(node_id, tuple):
# Handle the (node, graph) pair version of the parameters
(node_path, graph_id) = node_id
if not isinstance(node_path, str):
raise og.OmniGraphError(f"Node identifier '{node_id}' can only be a (str, graph) pair")
graph = ObjectLookup.graph(graph_id)
if graph is None:
raise og.OmniGraphError(f"Tried to create a node with unknown graph spec '{graph_id}'")
node_path = f"{graph.get_path_to_graph()}/{node_path}"
else:
# Infer the graph from the full node path
(graph, node_path) = ObjectLookup.split_graph_from_node_path(node_id)
if graph is None:
raise og.OmniGraphError(f"Tried to create a node in a path without a graph - '{node_id}'")
if node_path is None:
raise og.OmniGraphError(f"Tried to create a node from a graph path '{graph.get_path_to_graph()}'")
node_path = f"{graph.get_path_to_graph()}/{node_path}"
try:
node_type = ObjectLookup.node_type(node_type_id)
node_type_name = node_type.get_node_type()
except og.OmniGraphError:
node_type = None
node_type_name = None
node = graph.get_node(node_path)
if node is not None and node.is_valid():
if allow_exists:
current_node_type = node.get_type_name()
if node_type_id is None or node_type_id == current_node_type:
return node
error = f"already exists as type {current_node_type}"
else:
error = "already exists"
raise og.OmniGraphError(f"Creation of {node_path} as type {node_type} failed - {error}")
if node_type_name is None:
extension = node_type_id.rsplit(".", 1)[0]
more = "" if extension == node_type_id else f". Perhaps the extension '{extension}' is not loaded?"
raise og.OmniGraphError(f"Could not create node using unrecognized type '{node_type_id}'{more}")
if undoable:
(_, new_node) = cmds.CreateNode(
graph=graph, node_path=node_path, node_type=node_type_name, create_usd=update_usd
)
else:
new_node = cmds.imm.CreateNode(graph, node_path, node_type_name, update_usd)
return new_node
# --------------------------------------------------------------------------------------------------------------
@classmethod
def create_prim(obj, *args, **kwargs) -> Usd.Prim: # noqa: N804,PLC0202,PLE0202
"""Create a prim node containing a predefined set of attribute values and a ReadPrim OmniGraph node for it
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. The "prim_path" is mandatory and can appear as either a positional
or keyword argument. All others are optional, also by position or keyword, defaulting to the value set in the
constructor in the object context if available, and the function defaults elsewhere.
.. code-block:: python
og.GraphController.create_prim("/MyPrim")
og.GraphController(undoable=False).create_prim("/MyPrim", undoable=True) # Will be undoable
og.GraphController().create_prim(prim_path="/MyPrim", prim_type="MyPrimType")
og.GraphController.create_prim("/MyPrim", )
Args:
obj: Either cls or self depending on how the function was called
prim_path: Location of the prim
attribute_values: Dictionary of {NAME: (TYPE, VALUE)} for all prim attributes
The TYPE recognizes OGN format, SDF format, or og.Type values
The VALUE should be in a format suitable for passing to pxr::UsdAttribute.Set()
prim_type: The type of prim to create. (default "OmniGraphPrim")
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Returns:
Created Usd.Prim
Raises:
og.OmniGraphError: If any of the attribute specifications could not be applied to the prim, or if the
prim could not be created.
"""
return obj.__create_prim(obj, args=args, kwargs=kwargs)
def __create_prim_obj(self, *args, **kwargs) -> og.Graph:
"""Implements :py:meth:`.GraphController.create_prim` when called as an object method"""
return self.__create_prim(self, undoable=self.__undoable, args=args, kwargs=kwargs)
@staticmethod
def __create_prim(
obj,
prim_path: Path_t = _Unspecified,
attribute_values: PrimAttrs_t = None,
prim_type: str = None,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
) -> Usd.Prim:
"""Implements :py:meth:`.GraphController.create_prim`"""
(prim_path, attribute_values, prim_type, undoable) = _flatten_arguments(
mandatory=[("prim_path", prim_path)],
optional=[
("attribute_values", attribute_values),
("prim_type", prim_type),
("undoable", undoable),
],
args=args,
kwargs=kwargs,
)
# Use the prim path to create the prim
stage = omni.usd.get_context().get_stage()
prim_path = str(prim_path)
# Give a better message than GetPrimAtPath would provide if the prim already existed
existing_prim = stage.GetPrimAtPath(prim_path)
if existing_prim is not None and existing_prim.IsValid():
raise og.OmniGraphError(f"Cannot create prim at {prim_path} - that path is already occupied")
# Make sure the prim won't end up inside an OmniGraph
(graph, _) = ObjectLookup.split_graph_from_node_path(prim_path)
if graph is not None:
raise og.OmniGraphError(
f"Tried to create a prim inside a graph - '{prim_path}' is in '{graph.get_path_to_graph()}'"
)
# Do simple validation on the attribute_values types
if not isinstance(attribute_values, dict):
raise og.OmniGraphError(
f"Attribute values must be a name:(type, value) dictionary - got '{attribute_values}'"
)
if undoable:
(success, _) = omni.kit.commands.execute(
"CreatePrim", prim_path=prim_path, prim_type=prim_type if prim_type is not None else "OmniGraphPrim"
)
else:
omni.kit.commands.create(
"CreatePrim", prim_path=prim_path, prim_type=prim_type if prim_type is not None else "OmniGraphPrim"
).do()
success = True
prim = stage.GetPrimAtPath(prim_path)
if not success or not prim.IsValid():
raise og.OmniGraphError(f"Failed to create prim at {prim_path}")
# Walk the list of attribute descriptions, creating them on the prim as they go
for attribute_name, attribute_data in attribute_values.items():
try:
(attribute_type_name, attribute_value) = attribute_data
if not isinstance(attribute_type_name, str) and not isinstance(attribute_type_name, og.Type):
raise TypeError
except (TypeError, ValueError) as error:
raise og.OmniGraphError(
f"Attribute values must be a name:(type, value) dictionary - got '{attribute_values}'"
) from error
if isinstance(attribute_type_name, og.Type):
attribute_type = attribute_type_name
else:
attribute_type = og.AttributeType.type_from_ogn_type_name(attribute_type_name)
if attribute_type.base_type == og.BaseDataType.UNKNOWN:
attribute_type = og.AttributeType.type_from_sdf_type_name(attribute_type_name)
if attribute_type.base_type == og.BaseDataType.UNKNOWN:
raise og.OmniGraphError(
f"Attribute type '{attribute_type_name}' was not a legal type, nor an OGN or Sdf type name"
)
# The attribute type managers already know how to get the SdfValueType so ask the appropriate one
manager = ogn.get_attribute_manager_type(attribute_type.get_ogn_type_name())
sdf_type_name = manager.sdf_type_name()
if sdf_type_name is None:
raise og.OmniGraphError(
f"Attribute type '{attribute_type_name}' could not be translated into a valid Sdf type name"
)
sdf_type = getattr(Sdf.ValueTypeNames, sdf_type_name)
usd_value = og.attribute_value_as_usd(attribute_type, attribute_value)
attribute = prim.CreateAttribute(attribute_name, sdf_type)
if not attribute.IsValid():
raise og.OmniGraphError(
f"Attribute type '{attribute_type_name}' could not be created or set to '{usd_value}'"
)
attribute.Set(usd_value)
return prim
# --------------------------------------------------------------------------------------------------------------
@classmethod
def create_variable(obj, *args, **kwargs) -> og.IVariable: # noqa: N804,PLC0202,PLE0202
"""Creates a variable with the given name on the graph
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
Args:
graph_id: The graph to create a variable on
name: The name of the variable to create
var_type: The type of the variable to create, either a string or an OG.Type
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Raises:
og.OmniGraphError: If the variable can't be created
Returns:
The created variable
"""
return obj.__create_variable(obj, args=args, kwargs=kwargs)
def __create_variable_obj(self, *args, **kwargs) -> og.Graph:
"""Implements :py:meth:`.GraphController.create_variable` when called as an object method"""
return self.__create_variable(self, undoable=self.__undoable, args=args, kwargs=kwargs)
@staticmethod
def __create_variable(
obj,
graph_id: Graph_t = _Unspecified,
name: VariableName_t = _Unspecified,
var_type: VariableType_t = _Unspecified,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
) -> og.IVariable:
"""Implements :py:meth:`.GraphController.create_variable`"""
(graph_id, name, var_type, undoable) = _flatten_arguments(
mandatory=[("graph_id", graph_id), ("name", name), ("var_type", var_type)],
optional=[("undoable", undoable)],
args=args,
kwargs=kwargs,
)
_ = DBG and log_info(f"Create variable {name} with type {var_type} on {graph_id}")
graph = ObjectLookup.graph(graph_id)
if isinstance(var_type, str):
og_type = og.AttributeType.type_from_ogn_type_name(var_type)
elif isinstance(var_type, og.Type):
og_type = var_type
else:
raise og.OmniGraphError(f"{type} is not a valid Type object")
variable = None
if undoable:
(_, variable) = cmds.CreateVariable(graph=graph, variable_name=name, variable_type=og_type)
else:
variable = cmds.imm.CreateVariable(graph=graph, variable_name=name, variable_type=og_type)
if variable is None:
raise og.OmniGraphError(f"Could not create variable named {name} with type {og_type} on the graph")
return variable
# --------------------------------------------------------------------------------------------------------------
@classmethod
def delete_node(obj, *args, **kwargs) -> bool: # noqa: N804,PLC0202,PLE0202
"""Deletes one or more OmniGraph nodes.
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
Args:
obj: Either cls or self depending on how the function was called
node_id: Specification of a node or list of nodes to be deleted
graph_id: Only required if the node_id does not contain enough information to uniquely identify it
ignore_if_missing: If True then succeed even if no node with a matching path exists
update_usd: If specified then override whether to delete the node's USD backing (default True)
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Raises:
og.OmniGraphError: If the node does not exist
Returns:
True if the node is gone
"""
return obj.__delete_node(obj, args=args, kwargs=kwargs)
def __delete_node_obj(self, *args, **kwargs) -> bool:
"""Implements :py:meth:`.GraphController.delete_node` when called as an object method"""
return self.__delete_node(
self, update_usd=self.__update_usd, undoable=self.__undoable, args=args, kwargs=kwargs
)
@staticmethod
def __delete_node(
obj,
node_id: Nodes_t = _Unspecified,
graph_id: Optional[Graph_t] = None,
ignore_if_missing: bool = False,
update_usd: bool = True,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
) -> bool:
"""Implements :py:meth:`.GraphController.delete_node`"""
(node_id, graph_id, ignore_if_missing, update_usd, undoable) = _flatten_arguments(
mandatory=[("node_id", node_id)],
optional=[
("graph_id", graph_id),
("ignore_if_missing", ignore_if_missing),
("update_usd", update_usd),
("undoable", undoable),
],
args=args,
kwargs=kwargs,
)
_ = DBG and log_info(f"Delete '{node_id}' on '{graph_id}', ignore_if_missing={ignore_if_missing}")
graph = ObjectLookup.graph(graph_id)
def __delete_one_node(node: Node_t) -> bool:
"""Remove a single node from its graph"""
nodes_graph = graph
try:
omnigraph_node = ObjectLookup.node(node, graph)
nodes_graph = omnigraph_node.get_graph()
except Exception as error:
if ignore_if_missing:
return True
raise og.OmniGraphError(f"Could not find node {node} to delete") from error
node_path = omnigraph_node.get_prim_path()
if undoable:
(status, _) = cmds.DeleteNode(graph=nodes_graph, node_path=node_path, modify_usd=update_usd)
else:
cmds.imm.DeleteNode(graph=nodes_graph, node_path=node_path, modify_usd=update_usd)
status = True
return status
if isinstance(node_id, list):
return all(__delete_one_node(node) for node in node_id)
return __delete_one_node(node_id)
# --------------------------------------------------------------------------------------------------------------
ExposePrimNode_t = Tuple[Prim_t, NewNode_t]
"""Typing for information required to expose a prim in a node"""
ExposePrimNodes_t = Union[ExposePrimNode_t, List[ExposePrimNode_t]]
"""Typing for information required to expose a list of prims in nodes"""
class PrimExposureType(Enum):
"""Value that specifies the method of exposing USD prims to OmniGraph"""
AS_ATTRIBUTES = "attributes"
AS_BUNDLE = "bundle"
AS_WRITABLE = "writable"
PrimExposureType_t = Union[str, PrimExposureType]
@classmethod
def node_type_to_expose(cls, exposure_type: PrimExposureType_t) -> str:
"""Returns the type of node that will be used to expose the prim for a given exposure type"""
if exposure_type in [cls.PrimExposureType.AS_ATTRIBUTES, cls.PrimExposureType.AS_ATTRIBUTES.value]:
return "omni.graph.nodes.ReadPrim"
if exposure_type in [cls.PrimExposureType.AS_BUNDLE, cls.PrimExposureType.AS_BUNDLE.value]:
return "omni.graph.nodes.ReadPrimBundle"
assert exposure_type in [cls.PrimExposureType.AS_WRITABLE, cls.PrimExposureType.AS_WRITABLE.value]
return "omni.graph.nodes.WritePrim"
@classmethod
def exposed_attribute_name(cls, exposure_type: PrimExposureType_t) -> str:
"""Returns the name of the attribute that will be used to expose the prim for a given exposure type"""
return "inputs:prim"
# --------------------------------------------------------------------------------------------------------------
@classmethod
def expose_prim(obj, *args, **kwargs) -> og.Node: # noqa: N804,PLC0202,PLE0202
"""Create a new compute node attached to an ordinary USD prim or list of prims.
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
Args:
obj: Either cls or self depending on how the function was called
exposure_type: Method for exposing the prim to OmniGraph
prim_id: Identifier of an existing prim in the USD stage
node_path_id: Identifier of a node path that is valid but does not currently exist
update_usd: If specified then override whether to delete the node's USD backing (default True)
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Returns:
Node exposing the prim to OmniGraph
Raises:
og.OmniGraphError: if the prim does not exist, or the node path already exists
"""
return obj.__expose_prim(obj, args=args, kwargs=kwargs)
def __expose_prim_obj(self, *args, **kwargs) -> og.Graph:
"""Implements :py:meth:`.GraphController.expose_prim` when called as an object method"""
return self.__expose_prim(
self, update_usd=self.__update_usd, undoable=self.__undoable, args=args, kwargs=kwargs
)
@staticmethod
def __expose_prim(
obj,
exposure_type: PrimExposureType_t = _Unspecified,
prim_id: Prim_t = _Unspecified,
node_path_id: NewNode_t = _Unspecified,
update_usd: bool = True,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
) -> og.Node:
"""Implements :py:meth:`.GraphController.expose_prim`"""
(exposure_type, prim_id, node_path_id, update_usd, undoable) = _flatten_arguments(
mandatory=[("exposure_type", exposure_type), ("prim_id", prim_id), ("node_path_id", node_path_id)],
optional=[("update_usd", update_usd), ("undoable", undoable)],
args=args,
kwargs=kwargs,
)
_ = DBG and log_info(
f"Expose prim using exposure_type={exposure_type}, prim_id={prim_id}, node_path={node_path_id}"
f", update_usd={update_usd}, undoable={undoable}"
)
node_type = obj.node_type_to_expose(exposure_type)
attribute_name = obj.exposed_attribute_name(exposure_type)
prim = og.ObjectLookup.prim(prim_id)
if not prim.IsValid():
raise og.OmniGraphError(f"Could not expose an invalid prim '{prim_id}'")
node_path = og.ObjectLookup.node_path(node_path_id)
new_node = obj.create_node(node_path, node_type, allow_exists=False, update_usd=update_usd, undoable=undoable)
# Give the USD scene time to update
asyncio.ensure_future(omni.kit.app.get_app().next_update_async())
# The commented-out lines are what the commands should be, except that at the moment the ConnectPrim command
# is not working with the new prim configuration. Once that is fixed these lines can be restored and we won't
# have to go to the USD commands for this function.
# prim_attribute = og.ObjectLookup.attribute("inputs:prim", new_node)
# cmds.ConnectPrim(attr=prim_attribute, prim_path=str(prim.GetPrimPath()), is_bundle_connection=True)
stage = omni.usd.get_context().get_stage()
if undoable:
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{new_node.get_prim_path()}.{attribute_name}"),
target=prim.GetPath(),
)
else:
omni.kit.commands.create(
"AddRelationshipTarget",
relationship=stage.GetPropertyAtPath(f"{new_node.get_prim_path()}.{attribute_name}"),
target=prim.GetPath(),
).do()
return new_node
# --------------------------------------------------------------------------------------------------------------
@classmethod
def __decode_connection_point(cls, port_spec: AttributeSpec_t) -> Union[str, og.Attribute]: # noqa: PLW0238
"""Decipher the connection point to figure out where the connection/disconnection should happen
Args:
port_spec: Location for the connection. It can be an :py:class:`omni.graph.core.Attribute` when a real
physical connection is to be made in OmniGraph, or a string that references an object when the
connection is being made to a path attribute, which can connect to any object in the USD stage
by name.
Returns:
If an :py:class:`omni.graph.core.Attribute` could be deciphered from the port_spec then returns that, else
returns a string pointing to the object passed in, if possible.
"""
try:
# If the attribute was found then just return it directly
attribute = ObjectLookup.attribute(port_spec)
return attribute
except og.OmniGraphError:
return ObjectLookup.attribute_path(port_spec)
# --------------------------------------------------------------------------------------------------------------
@classmethod
def connect(obj, *args, **kwargs): # noqa: N804,PLC0202,PLE0202
"""Create a connection between two attributes
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
Args:
obj: Either cls or self depending on how the function was called
src_spec: Specification of the attribute to be the source end of the connection
dst_spec: Specification of the attribute to be the destination end of the connection
update_usd: If specified then override whether to delete the node's USD backing (default True)
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Raises:
OmniGraphError: If attributes could not be found or the connection fails
"""
obj.__connect(obj, args=args, kwargs=kwargs)
def __connect_obj(self, *args, **kwargs):
"""Implements :py:meth:`.GraphController.connect` when called as an object method"""
self.__connect(self, update_usd=self.__update_usd, undoable=self.__undoable, args=args, kwargs=kwargs)
@staticmethod
def __connect(
obj,
src_spec: AttributeSpec_t = _Unspecified,
dst_spec: AttributeSpec_t = _Unspecified,
update_usd: bool = True,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
):
"""Implement :py:meth:`.GraphController.connect`"""
(src_spec, dst_spec, update_usd, undoable) = _flatten_arguments(
mandatory=[("src_spec", src_spec), ("dst_spec", dst_spec)],
optional=[("update_usd", update_usd), ("undoable", undoable)],
args=args,
kwargs=kwargs,
)
connection_msg = f"`{src_spec}` -> `{dst_spec}`"
_ = DBG and log_info(f"Connect {connection_msg}")
src_location = obj.__decode_connection_point(src_spec) # noqa: PLW0212
src_path = src_location if isinstance(src_location, str) else src_location.get_path()
dst_location = obj.__decode_connection_point(dst_spec) # noqa: PLW0212
dst_path = dst_location if isinstance(dst_location, str) else dst_location.get_path()
if isinstance(src_location, str) and isinstance(dst_location, str):
raise og.OmniGraphError(f"At least one end of the connection must be an attribute - {connection_msg}")
_ = DBG and log_info(f" Connect Attr {src_path} to {dst_path}")
try:
if isinstance(src_location, str):
dst_type = dst_location.get_resolved_type()
if dst_type.role != og.AttributeRole.PATH:
raise og.OmniGraphError(
f"Path strings can only connect to path attributes, destination had {dst_type}"
)
# TODO: Create callback so that the path attribute gets updated when its target is renamed
cmds.SetAttr(attr=dst_location, value=src_location)
elif isinstance(dst_location, str):
src_type = src_location.get_resolved_type()
if src_type.role != og.AttributeRole.PATH:
raise og.OmniGraphError(f"Path strings can only connect to path attributes, source had {src_type}")
# TODO: Create callback so that the path attribute gets updated when its target is renamed
cmds.SetAttr(attr=src_location, value=dst_location)
else:
if undoable:
(success, _) = cmds.ConnectAttrs(
src_attr=src_location, dest_attr=dst_location, modify_usd=update_usd
)
else:
success = cmds.imm.ConnectAttrs(
src_attr=src_location, dest_attr=dst_location, modify_usd=update_usd
)
if not success:
raise og.OmniGraphError(f"Failed to connect '{src_location}' to '{dst_location}'")
except og.OmniGraphError as error:
raise og.OmniGraphError(f"Failed to connect {src_path} -> {dst_path}") from error
# --------------------------------------------------------------------------------------------------------------
@classmethod
def disconnect(obj, *args, **kwargs): # noqa: N804,PLC0202,PLE0202
"""Break a connection between two attributes
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
Args:
obj: Either cls or self depending on how the function was called
src_spec: Specification of the attribute that is the source end of the connection
dst_spec: Specification of the attribute that is the destination end of the connection
update_usd: If specified then override whether to delete the node's USD backing (default True)
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Raises:
OmniGraphError: If attributes could not be found or the disconnection fails
"""
return obj.__disconnect(obj, args=args, kwargs=kwargs)
def __disconnect_obj(self, *args, **kwargs):
"""Implements :py:meth:`.GraphController.disconnect` when called as an object method"""
return self.__disconnect(self, update_usd=self.__update_usd, undoable=self.__undoable, args=args, kwargs=kwargs)
@staticmethod
def __disconnect(
obj,
src_spec: AttributeSpec_t = _Unspecified,
dst_spec: AttributeSpec_t = _Unspecified,
update_usd: bool = True,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
):
"""Implement :py:meth:`.GraphController.disconnect`"""
(src_spec, dst_spec, update_usd, undoable) = _flatten_arguments(
mandatory=[("src_spec", src_spec), ("dst_spec", dst_spec)],
optional=[("update_usd", update_usd), ("undoable", undoable)],
args=args,
kwargs=kwargs,
)
_ = DBG and log_info(f"Disconnect `{src_spec}` -> `{dst_spec}`")
success = False
src_location = obj.__decode_connection_point(src_spec) # noqa: PLW0212
src_path = src_location if isinstance(src_location, str) else src_location.get_path()
dst_location = obj.__decode_connection_point(dst_spec) # noqa: PLW0212
dst_path = dst_location if isinstance(dst_location, str) else dst_location.get_path()
if isinstance(src_location, str) and isinstance(dst_location, str):
raise og.OmniGraphError(
f"At least one end of the disconnection must be an attribute - '{src_location}' -> '{dst_location}'"
)
_ = DBG and log_info(f" Disconnect Attr {src_path} to {dst_path}")
try:
if isinstance(src_location, str):
dst_type = dst_location.get_resolved_type()
if dst_type.role != og.AttributeRole.PATH:
raise og.OmniGraphError(
f"Path strings can only disconnect from path attributes, destination had {dst_type}"
)
# TODO: Remove callback on path attributes
elif isinstance(dst_location, str):
src_type = src_location.get_resolved_type()
if src_type.role != og.AttributeRole.PATH:
raise og.OmniGraphError(
f"Path strings can only disconnect from path attributes, source had {src_type}"
)
# TODO: Remove callback on path attributes
elif undoable:
if not cmds.DisconnectAttrs(src_attr=src_location, dest_attr=dst_location, modify_usd=update_usd)[0]:
raise og.OmniGraphError
elif not cmds.imm.DisconnectAttrs(src_attr=src_location, dest_attr=dst_location, modify_usd=update_usd):
raise og.OmniGraphError
except og.OmniGraphError as error:
if not success:
raise og.OmniGraphError(f"Failed to disconnect {src_path} -> {dst_path}") from error
# --------------------------------------------------------------------------------------------------------------
@classmethod
def disconnect_all(obj, *args, **kwargs): # noqa: N804,PLC0202,PLE0202
"""Break all connections to and from an attribute
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
Args:
obj: Either cls or self depending on how the function was called
attribute_spec: Attribute whose connections are to be removed. (attr or (attr, node) pair)
update_usd: If specified then override whether to delete the node's USD backing (default True)
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Raises:
OmniGraphError: If attribute could not be found, connection didn't exist, or disconnection fails
"""
return obj.__disconnect_all(obj, args=args, kwargs=kwargs)
def __disconnect_all_obj(self, *args, **kwargs):
"""Implements :py:meth:`.GraphController.disconnect_all` when called as an object method"""
return self.__disconnect_all(
self, update_usd=self.__update_usd, undoable=self.__undoable, args=args, kwargs=kwargs
)
@staticmethod
def __disconnect_all(
obj,
attribute_spec: AttributeSpec_t = _Unspecified,
update_usd: bool = True,
undoable: bool = True,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
):
"""Implements :py:meth:`.GraphController.disconnect_all`"""
(attribute_spec, update_usd, undoable) = _flatten_arguments(
mandatory=[("attribute_spec", attribute_spec)],
optional=[("update_usd", update_usd), ("undoable", undoable)],
args=args,
kwargs=kwargs,
)
_ = DBG and (f"Disconnect all from {attribute_spec}")
if isinstance(attribute_spec, tuple):
attribute = ObjectLookup.attribute(*attribute_spec)
else:
attribute = ObjectLookup.attribute(attribute_spec)
if undoable:
(success, _) = cmds.DisconnectAllAttrs(attr=attribute, modify_usd=update_usd)
else:
success = cmds.imm.DisconnectAllAttrs(attr=attribute, modify_usd=update_usd)
# TODO: Also remove the callbacks if the attribute was a path attribute
if not success:
raise og.OmniGraphError(f"Failed to break connections on `{attribute_spec}`")
# --------------------------------------------------------------------------------------------------------------
@classmethod
def set_variable_default_value(cls, variable_id: Variable_t, value):
"""Sets the default value of a variable object.
Args:
variable_id: The variable whose value is to be set
value: The value to set
Raises:
OmniGraphError: If the variable is not valid, does not have valid usd backing, or value
is not a compatible type
"""
_ = DBG and (f"Set variable {variable_id} to {value}")
variable = ObjectLookup.variable(variable_id)
stage = omni.usd.get_context().get_stage()
attr = stage.GetAttributeAtPath(variable.source_path)
if not attr:
raise og.OmniGraphError(f"Variable {variable.name} does not have a valid backing attribute")
try:
attr.Set(value)
except Tf.ErrorException as error:
raise og.OmniGraphError(f"Variable {variable.name} type is not compatible with {type(value)}") from error
# --------------------------------------------------------------------------------------------------------------
@classmethod
def get_variable_default_value(cls, variable_id: Variable_t):
"""Gets the default value of the given variable
Args:
variable_id: The variable whose value is to be set
Returns:
The default value of the variable.
Raises:
OmniGraphError: If the variable is not valid or does not have valid usd backing.
"""
_ = DBG and (f"Get variable {variable_id}")
variable = ObjectLookup.variable(variable_id)
stage = omni.usd.get_context().get_stage()
attr = stage.GetAttributeAtPath(variable.source_path)
if not attr:
raise og.OmniGraphError(f"Variable {variable.name} does not have a valid backing attribute")
return attr.Get()
| 49,388 |
Python
| 48.587349 | 120 | 0.595813 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/controller.py
|
# noqa: PLC0302
"""Utilities that handles interactions with the set of OmniGraph graphs and their contents.
The main class is og.Controller, which is an aggregate that implements each of the smaller interfaces that handle
various pieces of the graph manipulation. They are mainly kept separate to avoid a big monolithic implementation
class, while providing a single point of contact for graph manipulation due to the multiple interfaces it inherits.
All of the classes used here follow a pattern that allows the main functions to be called using either an object or a
class, accessing the same underlying functionality but with potentially different arguments.
.. code-block:: python
class SharedMethodNames:
def __init__(self, *args, **kwargs):
# Replace the classmethod in instantiated objects with the internal object-based implementation
self.dual_method = self.__dual_method_obj
@staticmethod
def __dual_method(obj, *args, **kwargs):
# Implementation of the actual method
@classmethod
def dual_method(cls, *args, **kwargs):
# Any manipulation of the arguments for class-based use is done first, then the implementation is called
cls.__dual_method(cls, *args, **kwargs)
def __dual_method_obj(self, *args, **kwargs):
# Any manipulation of the arguments for object-based use is done first, then the implementation is called
self.__dual_method(self, *args, **kwargs)
For example, here is an implementation of a class containing a "square()" function that will square the value it owns.
The object will initialized the value as part of its __init__() function, whereas the class method will take the value
as one of its arguments.
.. code-block:: python
class FlexibleSquare:
def __init__(self, value: float):
self.square = self.__square_obj
self.__value = value
@staticmethod
def __square(obj, value: float) -> float:
return value * value
@classmethod
def square(cls, value: float) -> float:
return cls.__square(cls, value)
def __square_obj(self) -> float:
return self.__square(self, self.__value)
print(f"Square of 3 is {FlexibleSquare.square(3)}")
five = FlexibleSquare(5)
print(f"Square of 5 is {five.square()}")
It might also make sense to allow override in the method for the object's method:
def __square_obj(self, value: float = None) -> float:
return self.__square(self, self.__value if value is None else value)
print(f"Square of 3 is {FlexibleSquare.square(3)}")
five = FlexibleSquare(5)
print(f"Square of 5 is {five.square()}")
print(f"Square of 4 is {five.square(4)}")
"""
from __future__ import annotations
import asyncio
from contextlib import suppress
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import omni.graph.core as og
import omni.graph.tools.ogn as ogn
from omni.kit import undo
from pxr import Sdf, Usd
from .data_view import DataView
from .errors import OmniGraphError
from .graph_controller import GraphController
from .node_controller import NodeController
from .object_lookup import ObjectLookup
from .typing import (
AttributeSpec_t,
AttributeSpecs_t,
AttributeType_t,
GraphSpec_t,
GraphSpecs_t,
NewNode_t,
NodeSpec_t,
NodeType_t,
Path_t,
PrimAttrs_t,
VariableName_t,
VariableType_t,
)
from .utils import AttributeValues_t, ValueToSet_t, _flatten_arguments, _Unspecified
# Dictionary type mapping the relative path of a node that was created by the edit() method to the node/prim it created
# TODO: path_to_object_map + graph_path could be broken into a separate class for easier handling
PathToObjectMap_t = Dict[str, Union[og.Node, Usd.Prim]]
# ==============================================================================================================
def _get_as_list(value: Union[Any, List[Any]]) -> List[Any]:
"""Utility to ensure that a passed-in item is returned as a list.
Args:
value: Value or list of values to convert
Returns:
The value itself if it was already a list, otherwise a single element list containing the value
"""
return value if isinstance(value, list) else [value]
# ==============================================================================================================
def _find_actual_path(path_id: Path_t, root_path: str, path_to_object_map: Dict[str, Any]) -> str:
"""Finds the actual creation path, applying node mapping and graph path prepending when needed"""
node_path = str(path_id)
if node_path.startswith("/"):
return node_path
try:
node_object = path_to_object_map[node_path]
return node_object.get_prim_path() if isinstance(node_object, og.Node) else node_object
except KeyError:
return f"{root_path}/{node_path}"
# ==============================================================================================================
class Controller(GraphController, NodeController, DataView, ObjectLookup):
# begin-controller-docs
r"""Class to provide a simple interface to a variety OmniGraph manipulation functions.
Provides functions for creating nodes, making and breaking connections, and setting values.
Graph manipulation functions are undoable, value changes are not.
Functions are set up to be as flexible as possible, accepting a wide variety of argument variations.
Here is a summary of the interface methods you can access through this class, grouped by interface class. The ones
marked with an "*" indicate that they have both a classmethod version and an object method version. In those cases
the methods use object member values which have corresponding arguments in the classmethod version. (e.g. if the
method uses the "update_usd" member value then the method will also have a "update_usd:bool" argument)
Controller
\* edit Perform a collection of edits on a graph (the union of all interfaces)
async evaluate Runs evaluation on one or more graphs as a waitable (typically called from async tests)
evaluate_sync Runs evaluation on one or more graphs immediately
ObjectLookup
attribute Looks up an og.Attribute from a description
attribute_path Looks up an attribute string path from a description
attribute_type Looks up an og.Type from a description
graph Looks up an og.Graph from a description
node Looks up an og.Node from a description
node_path Looks up a node string path from a description
prim Looks up an Usd.Prim from a description
prim_path Looks up a Usd.Prim string path from a description
split_graph_from_node_path Separate a graph and a relative node path from a full node path
GraphController
\* connect Makes connections between attribute pairs
\* create_graph Creates a new og.Graph
\* create_node Creates a new og.Node
\* create_prim Creates a new Usd.Prim
\* create_variable Creates a new og.IVariable
\* delete_node Deletes a list of og.Nodes
\* disconnect Breaks connections between attribute pairs
\* disconnect_all Breaks all connections to and from specific attributes
\* expose_prim Expose a USD prim to OmniGraph through an importing node
NodeController
\* create_attribute Create a new dynamic attribute on a node
\* remove_attribute Remove an existing dynamic attribute from a node
safe_node_name Get a node name in a way that's safe for USD
DataView
\* get Get the value of an attribute's data
\* get_array_size Get the number of elements in an array attribute's data
\* set Set the value of an attribute's data
Class Attributes:
class Keys: Helper for managing the keywords needed for the edit() function
Attributes:
__path_to_object_map: Mapping from the node or prim path specified to the created node or prim
Raises:
OmniGraphError: If the requested operation could not be performed
"""
# end-controller-docs
Keys = ogn.GraphSetupKeys
TYPE_CHECKING = True
"""If True then verbose type checking will happen in various locations so that more legible error messages can
be emitted. Set it to False to run a little bit faster, with errors just reporting raw Python error messages.
"""
# --------------------------------------------------------------------------------------------------------------
def __init__(self, *args, **kwargs):
"""Set up state information. You only need to create an instance of the Controller if you are going to
use the edit() function more than once, when it needs to remember the node mapping used for creation.
Args are passed on to the parent classes who have inits and interpreted by them as they see fit.
Args:
graph_id: Must be by keyword. If specified then operations are performed on this graph_id unless it is
overridden in a particular function call.
Check the help information for :py:meth:`GraphController.__init__`, :py:meth:`NodeController.__init__`,
:py:meth:`DataView.__init__`, and :py:meth:`ObjectLookup.__init__` for details on what constructor arguments
are accepted.
"""
(self.__graph_id, self.__path_to_object_map, self.__update_usd, self.__undoable) = _flatten_arguments(
optional=[("graph_id", None), ("path_to_object_map", None), ("update_usd", True), ("undoable", True)],
args=args,
kwargs=kwargs,
)
GraphController.__init__(self, *args, **kwargs)
NodeController.__init__(self, *args, **kwargs)
DataView.__init__(self, *args, **kwargs)
ObjectLookup.__init__(self)
# Dual function methods that can be called either from an object or directly from the class
self.edit = self.__edit_obj
self.evaluate = self.__evaluate_obj
self.evaluate_sync = self.__evaluate_sync_obj
# --------------------------------------------------------------------------------------------------------------
@dataclass
class _EditArgs:
"""Collection of shared arguments that are passed to a bunch of the edit implementation methods
Members:
path_to_object_map: Dictionary of the mappings of the node names to instantiated node paths
graph_path: Path location of the graph on which the edits take place
update_usd: Should editing operations immediately update the USD backing?
undoable: Should editing operations be undoable?
"""
path_to_object_map: PathToObjectMap_t = None
graph_path: str = None
update_usd: bool = None
undoable: bool = None
# --------------------------------------------------------------------------------------------------------------
@classmethod
async def evaluate(obj, *args, **kwargs): # noqa: N804,PLC0202,PLE0202
"""Wait for the next Graph evaluation cycle - await this function to ensure it is finished before returning.
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object.
.. code-block:: python
await og.Controller.evaluate() # Evaluates all graphs
controller = og.Controller.edit("/TestGraph", {})
await controller.evaluate() # Evaluates only "/TestGraph"
await og.Controller.evaluate("/TestGraph") # Evaluates only "/TestGraph"
controller.evaluate(graph_id="/OtherGraph") # Evaluates only "/OtherGraph" (not its own "/TestGraph")
Args:
obj: Either cls or self depending on how the function was called
graph_id (GraphSpecs_t): Graph or list of graphs to evaluate - None means all existing graphs
"""
await obj.__evaluate(obj, args=args, kwargs=kwargs)
async def __evaluate_obj(self, *args, **kwargs) -> Any:
"""Implements :py:meth:`.Controller.evaluate` when called as an object method"""
await self.__evaluate(self, graph_id=self.__graph_id, args=args, kwargs=kwargs)
@staticmethod
async def __evaluate(
obj,
graph_id: Optional[GraphSpecs_t] = None,
args: List[Any] = None,
kwargs: Dict[str, Any] = None,
):
"""Implements :py:meth:`.Controller.evaluate`"""
(graph_id,) = _flatten_arguments(
optional=[("graph_id", graph_id)],
args=args,
kwargs=kwargs,
)
graphs = obj.graph(graph_id)
if graphs is None:
graphs = og.get_all_graphs()
elif not isinstance(graphs, list):
graphs = [graphs]
for graph in graphs:
graph.evaluate()
# --------------------------------------------------------------------------------------------------------------
@classmethod
def evaluate_sync(obj, *args, **kwargs): # noqa: N804,PLC0202,PLE0202
"""Run the next Graph evaluation cycle immediately.
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object.
.. code-block:: python
og.Controller.evaluate_sync() # Evaluates all graphs
controller = og.Controller.edit("/TestGraph", {})
controller.evaluate_sync() # Evaluates only "/TestGraph"
og.Controller.evaluate_sync("/TestGraph") # Evaluates only "/TestGraph"
controller.evaluate_sync(graph_id="/OtherGraph") # Evaluates only "/OtherGraph" (not its own "/TestGraph")
Args:
obj: Either cls or self depending on how evaluate_sync() was called
graph_id (GraphSpecs_t): Graph or list of graphs to evaluate - None means all existing graphs
"""
return obj.__evaluate_sync(obj, *args, **kwargs)
def __evaluate_sync_obj(self, *args, **kwargs) -> Any:
"""Implements :py:meth:`.Controller.evaluate_sync` when called as an object method"""
return self.__evaluate_sync(self, *args, **kwargs)
@staticmethod
def __evaluate_sync(obj, graph_id: Optional[GraphSpecs_t] = None):
"""Implements :py:meth:`.Controller.evaluate_sync`"""
created_loop = False
try:
loop = asyncio.get_running_loop()
except RuntimeError:
created_loop = True
loop = asyncio.new_event_loop()
loop.run_until_complete(obj.evaluate(graph_id))
if created_loop:
loop.close()
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def __mapped_node_path(node_path: str, path_to_object_map: PathToObjectMap_t) -> str:
"""Returns the node path after subjecting it to the object path mapping"""
try:
node = path_to_object_map[node_path]
return node.get_prim_path() if isinstance(node, og.Node) else str(node.GetPrimPath())
except KeyError:
return node_path
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def __mapped_attribute_spec( # noqa: PLW0238
attr_spec: AttributeSpec_t, path_to_object_map: PathToObjectMap_t
) -> AttributeSpec_t:
"""Returns the attribute spec with any necessary mapping of local path to fully created path made"""
# Check for Node.Attr format
if isinstance(attr_spec, og.Attribute):
return attr_spec
if isinstance(attr_spec, str):
paths = attr_spec.split(".")
# Attribute without node has no mapping
if len(paths) == 1:
return attr_spec
# Remap node path and rejoin with attribute
if len(paths) == 2:
return ".".join([Controller.__mapped_node_path(paths[0], path_to_object_map), paths[1]])
raise og.OmniGraphError(f"Attribute spec can only have one '.' separator - saw '{attr_spec}'")
if isinstance(attr_spec, (tuple, list)):
if len(attr_spec) != 2:
raise og.OmniGraphError(f"Attribute spec should be a (name, node) pair - saw '{attr_spec}'")
# Make it reversible when it can be inferred
if isinstance(attr_spec[0], og.Node):
return (attr_spec[1], attr_spec[0])
if isinstance(attr_spec[1], og.Node):
return attr_spec
return (attr_spec[0], Controller.__mapped_node_path(attr_spec[1], path_to_object_map))
# Nothing else has a mapping
return attr_spec
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def _process_create_nodes(
obj,
nodes_to_create: List[Tuple[NewNode_t, NodeType_t]],
edit_args: Controller._EditArgs,
):
"""Creates a list of nodes, updating the path_to_object_map to include the new mappings
Args:
nodes_to_create: List of nodes that are to be created
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Raises:
og.OmniGraphError: If any of the nodes could not be created
"""
if obj.TYPE_CHECKING:
for element in nodes_to_create:
type_wrong = (not isinstance(element, (tuple, list))) or len(element) != 2
type_wrong |= type(element[0]) not in [str, og.Node, Sdf.Path, Usd.Prim]
type_wrong |= type(element[1]) not in [str, og.NodeType, og.Node, Usd.Prim]
if type_wrong:
raise og.OmniGraphError(
f"Node creation spec must be (node_path, node_type) pairs - got '{element}'"
)
# Before creation make sure the graph path is prepended or the mapped location is found to the node
# path if the path is not absolute
nodes_constructed = [
obj.create_node(
_find_actual_path(node_path, edit_args.graph_path, edit_args.path_to_object_map),
node_type,
update_usd=edit_args.update_usd,
undoable=edit_args.undoable,
)
for node_path, node_type in nodes_to_create
]
just_names = [name for (name, _node_type) in nodes_to_create]
edit_args.path_to_object_map.update(dict(zip(just_names, nodes_constructed)))
return nodes_constructed
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def _process_delete_nodes(
obj,
nodes_to_delete: List[NodeSpec_t],
edit_args: Controller._EditArgs,
):
"""Deletes a list of nodes, updating the path_to_object_map to remove any that are no longer in it
Args:
nodes_to_delete: List of nodes that are to be deleted
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Raises:
og.OmniGraphError: If the nodes could not be found or could not be deleted
"""
if obj.TYPE_CHECKING:
for element in nodes_to_delete:
if isinstance(element, og.Node) and not element.is_valid():
raise og.OmniGraphError(f"Node deletion spec points to an invalid node - '{element}'")
if (
not isinstance(element, str)
and not isinstance(element, Usd.Prim)
and not isinstance(element, og.Node)
):
raise og.OmniGraphError(f"Node deletion spec must be a string, node, or prim - got '{element}'")
for element in set(nodes_to_delete):
# Make sure the path to object map no longer has the reference to the deleted node
if isinstance(element, og.Node):
for node_path, node in edit_args.path_to_object_map.items():
if node == element:
del edit_args.path_to_object_map[node_path]
break
obj.delete_node(element, update_usd=edit_args.update_usd, undoable=edit_args.undoable)
elif isinstance(element, Usd.Prim):
omnigraph_node = og.get_node_by_path(element.GetPrimPath())
if omnigraph_node is not None and omnigraph_node.is_valid():
for node_path, node in edit_args.path_to_object_map.items():
if node == omnigraph_node:
del edit_args.path_to_object_map[node_path]
break
obj.delete_node(element, update_usd=edit_args.update_usd, undoable=edit_args.undoable)
else:
if element in edit_args.path_to_object_map:
node_path = og.ObjectLookup.node_path(edit_args.path_to_object_map[element])
del edit_args.path_to_object_map[element]
obj.delete_node(node_path, update_usd=edit_args.update_usd, undoable=edit_args.undoable)
else:
obj.delete_node(
f"{edit_args.graph_path}/{element}",
update_usd=edit_args.update_usd,
undoable=edit_args.undoable,
)
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def _process_connections(
obj,
connection_definitions: List[Tuple[AttributeSpec_t, AttributeSpec_t]],
breaking_connections: bool,
edit_args: Controller._EditArgs,
):
"""Process the edit section connections to be made or broken
Args:
connection_definitions: List of (src, dst) attribute pairs of the connections to be processed
breaking_connections: If True then disconnect the pairs, otherwise connect the pairs
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Raises:
og.OmniGraphError: If any of the attributes could not be found or the connections failed
"""
for src_spec, dst_spec in connection_definitions:
src_attr = obj.__mapped_attribute_spec(src_spec, edit_args.path_to_object_map) # noqa: PLW0212
dst_attr = obj.__mapped_attribute_spec(dst_spec, edit_args.path_to_object_map) # noqa: PLW0212
if breaking_connections:
obj.disconnect(src_attr, dst_attr, update_usd=edit_args.update_usd, edit_args=edit_args.undoable)
else:
obj.connect(src_attr, dst_attr, update_usd=edit_args.update_usd, edit_args=edit_args.undoable)
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def _process_disconnect_all(obj, attribute_specs: AttributeSpecs_t, edit_args: Controller._EditArgs):
"""Process the edit section connections to be made or broken
Args:
path_to_object_map: The map in use with local path names to created objects
attribute_specs: List of attribute from which all connections are to be broken
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Raises:
og.OmniGraphError: If the attribute could not be found or the disconnect failed
"""
attribute_specs = attribute_specs if isinstance(attribute_specs, list) else [attribute_specs]
for attribute_spec in attribute_specs:
attribute = (obj.__mapped_attribute_spec(attribute_spec, edit_args.path_to_object_map),) # noqa: PLW0212
obj.disconnect_all(attribute, update_usd=edit_args.update_usd, undoable=edit_args.undoable)
# --------------------------------------------------------------------------------------------------------------
PrimCreationData_t = Union[Tuple[Path_t, PrimAttrs_t], Tuple[Path_t, str], Tuple[Path_t, PrimAttrs_t, str]]
@staticmethod
def _process_create_prims(
obj,
prim_definitions: List[PrimCreationData_t],
edit_args: Controller._EditArgs,
) -> List[Usd.Prim]:
"""Process the edit section specifying prim creation
Args:
prim_definitions: List of prim paths with optional attribute values and prim type to create on the prim
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Returns:
List of prims that were created that correspond to the definitions
Raises:
og.OmniGraphError if there was a problem with the prim path or attribute definition
"""
def __create_one_prim(prim_definition: obj.PrimCreationData_t) -> Usd.Prim:
"""Normalize the inputs to turn them all into types suitable for calling create_prim with"""
prim_path = None
prim_attributes = {}
prim_type = None
if isinstance(prim_definition, (str, Sdf.Path)):
prim_path = prim_definition
elif isinstance(prim_definition, (tuple, list)) and isinstance(prim_definition[0], (str, Sdf.Path)):
if len(prim_definition) == 2:
if isinstance(prim_definition[1], str):
(prim_path, prim_type) = prim_definition
elif isinstance(prim_definition[1], dict):
(prim_path, prim_attributes) = prim_definition
elif (
len(prim_definition) == 3
and isinstance(prim_definition[1], dict)
and isinstance(prim_definition[2], str)
):
(prim_path, prim_attributes, prim_type) = prim_definition
if prim_path is None:
raise og.OmniGraphError(
f"Prim definitions must be name, (name,values), (name,type) or (name,values,type) -"
f" '{prim_definition}' is not recognized"
)
return obj.create_prim(
_find_actual_path(str(prim_path), "", {}), prim_attributes, prim_type, undoable=edit_args.undoable
)
# Loop through all prim definitions, creating them as we go
return [__create_one_prim(prim_definition) for prim_definition in prim_definitions]
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def _process_expose_prims(
obj,
exposure_definitions: List[GraphController.ExposePrimNode_t],
edit_args: Controller._EditArgs,
) -> List[og.Node]:
"""Process the edit section specifying prim creation
Args:
exposure_definitions: List of (exposure_type, prim, node_path) mappings giving the type of exposure,
prim to expose, and new node path at which it will be exposed
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Returns:
List of nodes that were created to expose the specified prims
Raises:
og.OmniGraphError if there was a problem with the prim or node path
"""
nodes_constructed = [
obj.expose_prim(
exposure_type,
_find_actual_path(prim_id, "", edit_args.path_to_object_map) if isinstance(prim_id, str) else prim_id,
_find_actual_path(node_path, edit_args.graph_path, edit_args.path_to_object_map),
update_usd=edit_args.update_usd,
undoable=edit_args.undoable,
)
for (exposure_type, prim_id, node_path) in exposure_definitions
]
just_names = [node_path for (_, _, node_path) in exposure_definitions]
edit_args.path_to_object_map.update(dict(zip(just_names, nodes_constructed)))
return nodes_constructed
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def _process_set_values(obj, value_definitions: AttributeValues_t, edit_args: Controller._EditArgs):
"""Process the edit section specifying value setting
Args:
value_definitions: List of (AttributeSpec_t, value) tuples indicating the attributes and the values to set
on them. The attribute spec will have the path_to_object_map applied to them if they
contain a relative node path. Optionally it will be a 3-tuple where the third member
is an AttributeType_t that specifies a resolve type for the attribute. This is only
valid for extended attribute types.
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Raises:
og.OmniGraphError: If the attributes could not be found, the values were invalid, or setting failed
"""
def _process_set_value(attribute_id: AttributeSpec_t, value: ValueToSet_t, type_info: AttributeType_t = None):
"""Sets a single value on an attribute"""
attribute_spec = obj.__mapped_attribute_spec(attribute_id, edit_args.path_to_object_map) # noqa: PLW0212
if type_info is not None:
value = og.TypedValue(value, type_info)
obj.set(
og.ObjectLookup.attribute(attribute_spec),
value,
update_usd=edit_args.update_usd,
undoable=edit_args.undoable,
)
if isinstance(value_definitions, list):
_ = [_process_set_value(*value_definition) for value_definition in value_definitions]
else:
_process_set_value(*value_definitions)
# --------------------------------------------------------------------------------------------------------------
@staticmethod
def _process_create_variable(
obj, variable_definitions: List[Tuple[VariableName_t, VariableType_t]], edit_args: Controller._EditArgs
) -> List[og.IVariable]:
"""Process the edit section that creates new variables
Args:
variable_definition: List of descriptions for variables to be created
edit_args: The common arguments used to configure editing operations :py:class:`Controller._EditArgs`
Returns:
List of variables created
"""
return [
obj.create_variable(edit_args.graph_path, name, var_type, undoable=edit_args.undoable)
for (name, var_type) in variable_definitions
]
# --------------------------------------------------------------------------------------------------------------
@classmethod
def edit( # noqa: PLC0202,PLE0202
obj, *args, **kwargs # noqa: N804
) -> Tuple[og.Graph, List[og.Node], List[Usd.Prim], PathToObjectMap_t]:
"""Edit and/or create an OmniGraph from the given description.
This function provides a single call that will make a set of modifications to an OmniGraph. It can be used to
create a new graph from scratch or to make changes to an existing graph.
If the "undoable" mode is not set to False then a single undo will revert everything done via this call.
The description below contains different sections that perform different operations on the graph. They are
always done in the order listed to minimize conflicts. If you need to execute them in a different order then use
multiple calls to edit().
This function can be called either from the class or using an instantiated object. When callling from an object
context the arguments passed in will take precedence over the arguments provided to the constructor. Here are
some of the legal ways to call the edit function:
.. code-block:: python
# For example purposes "cmds()" is a function that returns a dictionary of editing commands
(graph, _, _, _) = og.Controller.edit("/TestGraph", cmds())
new_controller = og.Controller(graph)
new_controller.edit(cmds())
og.Controller.edit(graph, cmds())
new_controller.edit(graph, cmds())
new_controller.edit(graph, cmds(), undoable=False) # Overrides the normal undoable state of new_controller
Below is the list of the allowed operations, in the order in which they will be performed.
The parameters are described as lists, though if you have only one parameter for a given operation you can pass
it without it being in a list.
.. code-block:: python
{ OPERATION: [List, Of, Arguments] }
{ OPERATION: SingleArgument }
For brevity the shortcut "keys = og.Controller.Keys" is assumed to exist.
- keys.DELETE_NODES: NodeSpecs_t
Deletes a node or list of nodes. If the node specification is a relative path then it must be in the
list of full paths that the controller created in a previous call to edit().
{ keys.DELETE_NODES: ["NodeInGraph", "/Some/Other/Graph/Node", my_omnigraph_node] }
- keys.CREATE_NODES: [(Path_t, NodeType_t)]
Constructs a node of the given type at the given path. If the path is a relative one then it is
added directly under the graph being edited. A map is remembered between the given path, relative or
absolute, and the node created at it so that further editing functions can refer to the node by that
name directly rather than trying to infer the final full name.
{ keys.CREATE_NODES: [("NodeInGraph", "omni.graph.tutorial.SimpleData"),
("Inner/Node/Path", og.NodeType(node_type_name))] }
- keys.CREATE_PRIMS: [(Path_t, {ATTR_NAME: (AttributeType_t, ATTR_VALUE)}, Optional(PRIM_TYPE))]
Constructs a prim at path "PRIM_PATH" containing a set of attributes with specified types and values.
Only those attribute types supported by USD can be used here, though the type specification can be in
OGN form - invalid types result in an error. Whereas relative paths on nodes are treated as being
relative to the graph, for prims a relative path is relative to the stage root. Prims are not allowed
inside an OmniGraph and attempts to create one there will result in an error.
Note that the PRIM_TYPE can appear with or without an attribute definition. (Many prim types are part
of a schema and do not require explicit attributes to be added.)
{ keys.PRIMS: [("/World/Prim", {"speed": ("double", 1.0)}),
("/World/Cube", "Cube"),
("RootPrim", {
"mass": (Type(BaseDataType.DOUBLE), 3.0),
"force:gravity": ("double", 32.0)
})]}
- keys.CONNECT: [(AttributeSpec_t, AttributeSpec_t)]
Makes a connection between the given source and destination attributes. The local name of a newly
created node may be made as part of the node in the spec, or the node portion of the attribute path:
{ keys.CONNECT: [("NodeInGraph.outputs:value", ("inputs:value", "NodeInGraph"))]}
- keys.DISCONNECT: [(AttributeSpec_t, AttributeSpec_t)]
Breaks a connection between the given source and destination attributes. The local name of a newly
created node may be made as part of the node in the spec, or the node portion of the attribute path:
{ keys.DISCONNECT: [("NodeInGraph.outputs:value", ("inputs:value", "NodeInGraph"))]}
- keys.EXPOSE_PRIMS: [(cls.PrimExposureType, Prim_t, NewNode_t)]
Exposes a prim to OmniGraph through creation of one of the node types designed to do that.
The first member of the tuple is the method used to expose the prim. The prim path is
the second member of the tuple and it must already exist in the USD stage. The third member
of the tuple is a node name with the same restrictions as the name in the CREATE_NODES edit.
{ keys.EXPOSE_PRIMS: [(cls.PrimExposureType.AS_BUNDLE, "/World/Cube", "BundledCube")] }
- keys.SET_VALUES: [AttributeSpec_t, Any] or [AttributeSpec_t, Any, AttributeType_t]
Sets the value of the given list of attributes.
{ keys.SET_VALUES[("/World/Graph/Node.inputs:attr1", 1.0), (("inputs:attr2", node), 2.0)] }
In the case of extended attribute types you may also need to supply a data type, which is the type the
attribute will resolve to when the value is set. To supply a type, add it as a third parameter to the
attribute value:
{ keys.SET_VALUES[("inputs:ext1", node), 2.0, "float"] }
- keys.CREATE_VARIABLES: [(VariableName_t, VariableType_t)]
Constructs a variable on the graph with the given name and type. The type can be specified
as either a ogn type string (e.g. "float4"), or as an og.Type (e.g. og.Type(og.BaseDataType.FLOAT))
{ keys.CREATE_VARIABLES[("velocity", "float3"), ("count", og.Type(og.BaseDataType.INT))] }
Here's a simple call that first deletes an existing node "/World/PushGraph/OldNode", then creates two nodes of
type "omni.graph.tutorials.SimpleData", connects their "a_int" attributes, disconnects their "a_float"
attributes and sets the input "a_int" of the source node to the value 5. It also creates two unused USD Prim
nodes, one with a float attribute named "attrFloat" with value 2.0, and the other with a boolean attribute
named "attrBool" with the value true.
.. code-block:: python
controller = og.Controller()
keys = og.Controller.Keys
(graph, nodes_constructed, prims_constructed, path_to_object_map) = controller.edit("/World/PushGraph", {
keys.DELETIONS: [
"OldNode"
],
keys.CREATE_NODES: [
("src", "omni.graph.tutorials.SimpleData"),
("dst", "omni.graph.tutorials.SimpleData")
],
keys.CREATE_PRIMS: [
("Prim1", {"attrFloat": ("float", 2.0)),
("Prim2", {"attrBool": ("bool", true)),
],
keys.CONNECT: [
("src.outputs:a_int", "dst.inputs:a_int")
],
keys.DISCONNECT: [
("src.outputs:a_float", "dst.inputs:a_float")
],
keys.SET_VALUES: [
("src.inputs:a_int", 5)
]
keys.CREATE_VARIABLES: [
("a_float_var", og.Type(og.BaseDataType.FLOAT)),
("a_bool_var", "bool")
]
}
)
.. note::
The controller object remembers where nodes are created so that you can use short forms for the node paths
for convenience. That's why in the above graph the node paths for creation and the node specifications in
the connections just says "src" and "dst". As they have no leading "/" they are treated as being relative
to the graph path and will actually end up in "/World/PushGraph/src" and "/World/PushGraph/dst".
Node specifications with a leading "/" are assumed to be absolute paths and must be inside the path of an
existing or created graph. e.g. the NODES reference could have been "/World/PushGraph/src", however using
"/src" would have been an error.
This node path mapping is remembered across multiple calls to edit() so you can always use the shortform
so long as you use the same Controller object.
Args:
obj: Either cls or self depending on how edit() was called
graph_id: Identifier that says which graph is being edited. See :py:meth:`GraphController.create_graph`
for the data types accepted for the graph description.
edit_commands: Dictionary of commands and parameters indicating what modifications are to be made
to the specified graph. A strict set of keys is accepted. Each of the values in the
dictionary can be either a single value or a list of values of the proscribed type.
path_to_object_map: Dictionary of relative paths mapped on to their full path after creation so that the
edit_commands can use either full paths or short-forms to specify the nodes.
update_usd: If specified then override whether to update the USD after the operations (default False)
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
(default True)
Returns:
A 4-tuple consisting of:
- the og.Graph being used for the operation
- the list of og.Nodes created by the operation
- the list of Usd.Prims created by the operation
- the map of node/prim path name to the created og.Node/Usd.Prim objects. Can usually be ignored; it
will be used internally to manage the shortform names of the paths used in multiple commands.
Raises:
og.OmniGraphError if any of the graph creation instructions could not be fulfilled
The graph will be left in the partially constructed state it reached at the time of the error
"""
return obj.__edit(obj, args=args, kwargs=kwargs)
def __edit_obj(self, *args, **kwargs):
"""Implements :py:meth:`Controller.edit` as an object method"""
results = self.__edit(
self,
graph_id=self.__graph_id,
path_to_object_map=self.__path_to_object_map,
update_usd=self.__update_usd,
undoable=self.__undoable,
args=args,
kwargs=kwargs,
)
self.__graph_id = results[0]
self.__path_to_object_map = results[3]
return results
@staticmethod
def __edit(
obj,
graph_id: Union[GraphSpec_t, Dict[str, Any]] = _Unspecified,
edit_commands: Optional[Dict[str, Any]] = None,
path_to_object_map: PathToObjectMap_t = None,
update_usd: bool = True,
undoable: bool = True,
args: List[str] = None,
kwargs: Dict[str, Any] = None,
) -> Tuple[og.Graph, List[og.Node], List[Usd.Prim]]:
"""Implements :py:meth:`Controller.edit`"""
(graph_id, edit_commands, path_to_object_map, update_usd, undoable) = _flatten_arguments(
mandatory=[("graph_id", graph_id)],
optional=[
("edit_commands", edit_commands),
("path_to_object_map", path_to_object_map),
("update_usd", update_usd),
("undoable", undoable),
],
args=args,
kwargs=kwargs,
)
if edit_commands is None:
edit_commands = {}
if path_to_object_map is None:
path_to_object_map = {}
# If the undo or usd update states were specified then add them to the arguments everywhere
shared_kwargs = Controller._EditArgs(
update_usd=update_usd,
undoable=undoable,
path_to_object_map=path_to_object_map,
)
# Separate the actual work so that it can be configured before being called
def __do_the_edits():
# A dictionary ID always indicates the graph should be created, otherwise check if it already exists
graph = obj.graph(graph_id) if not isinstance(graph_id, dict) else None
nodes_constructed = []
prims_constructed = []
# If the graph couldn't be found then infer that it should be created with the given specification.
if graph is None:
graph = obj.create_graph(graph_id)
# The graph could be in an illegal state when halfway through editing operations. This will disable it
# until all operations are completed. It's up to the caller to ensure that the state is legal after all
# operations are completed.
graph_was_disabled = graph.is_disabled()
graph.set_disabled(True)
graph_path = graph.get_path_to_graph()
shared_kwargs.graph_path = graph_path
try:
# Syntax check first
for instruction, _data in edit_commands.items():
if instruction not in obj.Keys.ALL:
raise OmniGraphError(f"Unknown graph edit operation - `{instruction}` not in {obj.Keys.ALL}")
# Delete first because we may be creating nodes with the same names
with suppress(KeyError):
obj._process_delete_nodes( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.DELETE_NODES]),
edit_args=shared_kwargs,
)
# Variables next, so they exist when nodes are created
with suppress(KeyError):
obj._process_create_variable( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.CREATE_VARIABLES]),
edit_args=shared_kwargs,
)
# Create nodes next since connect and set may need them
nodes_constructed = []
with suppress(KeyError):
nodes_constructed = obj._process_create_nodes( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.CREATE_NODES]),
edit_args=shared_kwargs,
)
# Prims next as they may be used in connections
with suppress(KeyError):
prims_constructed = obj._process_create_prims( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.CREATE_PRIMS]),
edit_args=shared_kwargs,
)
# Exposure of a raw prim to OmniGraph through one of the prim interface nodes
with suppress(KeyError):
nodes_constructed += obj._process_expose_prims( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.EXPOSE_PRIMS]),
edit_args=shared_kwargs,
)
# Connections next as setting values may override their data
with suppress(KeyError):
obj._process_connections( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.CONNECT]),
breaking_connections=False,
edit_args=shared_kwargs,
)
# Disconnections may have been created by the connections list so they're next, though that's unlikely
with suppress(KeyError):
obj._process_connections( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.DISCONNECT]),
breaking_connections=True,
edit_args=shared_kwargs,
)
# Disconnections of all attributes is last for connection changes as it will read existing connections
with suppress(KeyError):
obj._process_disconnect_all( # noqa: PLW0212
obj,
_get_as_list(edit_commands[obj.Keys.DISCONNECT_ALL]),
edit_args=shared_kwargs,
)
# Now that everything is in place it is safe to set the values
# TODO: Setting values has two parameters (on_gpu, and update_usd) that are not accounted for here.
# Extra information should be provided to allow for them. Until then the defaults will be used.
with suppress(KeyError):
obj._process_set_values( # noqa: PLW0212
obj, _get_as_list(edit_commands[obj.Keys.SET_VALUES]), edit_args=shared_kwargs
)
finally:
# Really important that this always gets reset
graph.set_disabled(graph_was_disabled)
return (graph, nodes_constructed, prims_constructed, path_to_object_map)
# Put every operation into a single undo umbrella. They will handle queueing undoable operations internally.
if undoable:
with undo.group():
return __do_the_edits()
return __do_the_edits()
| 50,301 |
Python
| 47.320845 | 120 | 0.584024 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/registration.py
|
"""Utilities for managing OmniGraph Python node registration"""
from contextlib import suppress
from pathlib import Path
from types import ModuleType
import omni.graph.tools as ogt
from .register_ogn_nodes import register_ogn_nodes
# ================================================================================
class PythonNodeRegistration:
"""Scoped object to register and deregister Python nodes as their extension is started up and shut down.
This will be created and destroyed automatically by OmniGraph and does not need to be explicitly managed.
"""
def __init__(self, module_to_register: ModuleType, module_name: str):
"""Save the information required to deregister the nodes when the module is shut down"""
import_location = module_to_register.__file__
if import_location is None:
with suppress(AttributeError, KeyError):
import_location = module_to_register.__path__._path[0]
ogt.dbg_reg("Remembering registration for nodes in {} imported as {}", import_location, module_name)
if import_location is not None:
import_location = Path(import_location)
if import_location.is_file():
import_location = import_location.parent
import_location = import_location / "ogn"
self.__deregistration_methods = register_ogn_nodes(str(import_location), module_name)
else:
ogt.dbg_reg("Failed to find module location")
def __del__(self):
"""Deregister all of the remembered nodes"""
with suppress(AttributeError):
for method in self.__deregistration_methods:
ogt.dbg_reg("Calling deregistration method {}", str(method))
method()
| 1,761 |
Python
| 44.179486 | 109 | 0.637138 |
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/data_view.py
|
"""Helper class to access data values from the graph. Is also encapsulated in the all-purpose og.Helper class."""
from contextlib import contextmanager
from typing import Any, Dict, List, Optional
import omni.graph.core as og
from .attribute_values import AttributeDataValueHelper, AttributeValueHelper, WrappedArrayType
from .errors import OmniGraphError
from .object_lookup import ObjectLookup
from .typing import AttributeWithValue_t
from .utils import ValueToSet_t, _flatten_arguments, _Unspecified, is_in_compute
# ==============================================================================================================
class DataView:
"""Helper class for getting and setting attribute data values. The setting operation is undoable.
Interfaces:
force_usd_update
get
get_array_size
gpu_ptr_kind
set
All of the interface functions can either be called from an instantiation of this object or from a class method
of the same name with an added attribute parameter that tells where to get and set values.
"""
__ALWAYS_UPDATE_USD = False
"""Global override to indicate that all calls to set() should force the update to USD"""
# --------------------------------------------------------------------------------------------------------------
# Context manager to temporarily enable forcing of USD updates, used as follows:
# with og.DataView.force_usd_update(True):
# do_something_requiring_usd_update()
@classmethod
@contextmanager
def force_usd_update(cls, force_update: bool = True):
original_update = cls.__ALWAYS_UPDATE_USD
try:
cls.__ALWAYS_UPDATE_USD = force_update
yield
finally:
cls.__ALWAYS_UPDATE_USD = original_update
# --------------------------------------------------------------------------------------------------------------
@classmethod
def __get_value_helper(cls, attribute: AttributeWithValue_t) -> AttributeDataValueHelper: # noqa: PLW0238
"""Returns a value manipulation helper that can get and set values on the given attribute or attributeData"""
if isinstance(attribute, og.AttributeData):
return AttributeDataValueHelper(attribute)
return AttributeValueHelper(ObjectLookup.attribute(attribute))
# --------------------------------------------------------------------------------------------------------------
def __init__(self, *args, **kwargs):
"""Initializes the data view class to prepare it for evaluting or setting an attribute value,
The arguments are flexible so that you can either construct an object that will persist its settings across
all method calls, or you can pass in overrides to the method calls to use instead. In the case of classmethod
calls the values passed in will be the only ones used.
The "attribute" value can be used by keyword or positionally. All other arguments must specify their keyword.
.. code-block:: python
og.Controller(update_usd=True) # Good
og.Controller("inputs:attr") # Good
og.Controller(update_usd=True, attribute="inputs:attr") # Good
og.Controller("inputs:attr", True) # Bad
Args:
attribute: (AttributeWithValue_t) Description of an attribute object with data that can be accessed
update_usd: (bool) Should the modification to the value immediately update the USD? Defaults to True
undoable: (bool) Is the modification to the value undoable? Defaults to True
on_gpu: (bool) Is the data being modified on the GPU? Defaults to True
gpu_ptr_kind: (og.PtrToPtrKind) How should GPU array data be returned? Defaults to True
"""
(self.__attribute, self.__update_usd, self.__undoable, self.__on_gpu, self.__gpu_ptr_kind) = _flatten_arguments(
optional=[
("attribute", None),
("update_usd", self.__ALWAYS_UPDATE_USD),
("undoable", True),
("on_gpu", False),
("gpu_ptr_kind", og.PtrToPtrKind.GPU),
],
args=args,
kwargs=kwargs,
)
# Dual function methods that can be called either from an object or directly from the class
self.get = self.__get_obj
self.get_array_size = self.__get_array_size_obj
self.set = self.__set_obj
# ----------------------------------------------------------------------------------------------------
@property
def gpu_ptr_kind(self) -> og.PtrToPtrKind:
"""Returns the location of pointers to GPU arrays"""
return self.__gpu_ptr_kind
@gpu_ptr_kind.setter
def gpu_ptr_kind(self, new_ptr_kind: og.PtrToPtrKind):
"""Sets the location of pointers to GPU arrays"""
self.__gpu_ptr_kind = new_ptr_kind
# ----------------------------------------------------------------------
@classmethod
def get(obj, *args, **kwargs) -> Any: # noqa: N804,PLC0202,PLE0202
"""Returns the current value on the owned attribute.
This function can be called either from the class or using an instantiated object. The first argument is
mandatory, being either the class or object. All others are by keyword or by position and optional, defaulting
to the value set in the constructor in the object context and the function defaults in the class context.
Args:
obj: Either cls or self depending on how the function was called
attribute: Attribute whose value is to be retrieved. If used in an object context and a value was provided
in the constructor then this value overrides that value. It's mandatory, so if it was not
provided in the constructor or here then an error is raised.
on_gpu: Is the value stored on the GPU?
reserved_element_count: For array attributes, if not None then the array will pre-reserve this many elements
return_type: For array attributes this specifies how the return data is to be wrapped.
gpu_ptr_kind: Type of data to return for GPU arrays (only used if on_gpu=True)
Raises:
OmniGraphError: If the current attribute is not valid or its value could not be retrieved
"""
return obj.__get(obj, args=args, kwargs=kwargs)
def __get_obj(self, *args, **kwargs) -> Any:
"""Implements :py:meth:`.DataView.get` when called as an object method"""
return self.__get(
self,
attribute=self.__attribute,
on_gpu=self.__on_gpu,
gpu_ptr_kind=self.__gpu_ptr_kind,
args=args,
kwargs=kwargs,
)
@staticmethod
def __get(
obj,
attribute: AttributeWithValue_t = _Unspecified,
on_gpu: bool = False,
reserved_element_count: Optional[int] = None,
return_type: Optional[WrappedArrayType] = None,
gpu_ptr_kind: Optional[og.PtrToPtrKind] = None,
args: List[str] = None,
kwargs: Dict[str, Any] = None,
) -> Any:
"""Implements :py:meth:`.DataView.get`"""
(attribute, on_gpu, reserved_element_count, return_type, gpu_ptr_kind) = _flatten_arguments(
mandatory=[("attribute", attribute)],
optional=[
("on_gpu", on_gpu),
("reserved_element_count", reserved_element_count),
("return_type", return_type),
("gpu_ptr_kind", gpu_ptr_kind),
],
args=args,
kwargs=kwargs,
)
helper = obj.__get_value_helper(attribute) # noqa: PLW0212
if helper is None:
raise OmniGraphError(f"Could not retrieve a value helper class for attribute {attribute}")
if gpu_ptr_kind is not None:
helper.gpu_ptr_kind = gpu_ptr_kind
return helper.get(on_gpu=on_gpu, reserved_element_count=reserved_element_count, return_type=return_type)
# ----------------------------------------------------------------------
@classmethod
def get_array_size(obj, *args, **kwargs) -> int: # noqa: N804,PLC0202,PLE0202
"""Returns the current number of array elements on the owned attribute.
This function can be called either from the class or using an instantiated object. The first argument is
positional, being either the class or object. All others are by keyword and optional, defaulting to the value
set in the constructor in the object context and the function defaults in the class context.
Args:
obj: Either cls or self depending on how get_array_size() was called
attribute: Attribute whose size is to be retrieved. If used in an object context and a value was provided
in the constructor then this value overrides that value. It's mandatory, so if it was not
provided in the constructor or here then an error is raised.
Raises:
OmniGraphError: If the current attribute is not valid or is not an array type
"""
return obj.__get_array_size(obj, args=args, kwargs=kwargs)
def __get_array_size_obj(self, *args, **kwargs) -> Any:
"""Implements :py:meth:`.DataView.get_array_size` when called as an object method"""
return self.__get_array_size(self, attribute=self.__attribute, args=args, kwargs=kwargs)
@staticmethod
def __get_array_size(
obj,
attribute: AttributeWithValue_t = None,
args: List[str] = None,
kwargs: Dict[str, Any] = None,
) -> int:
"""Implements :py:meth:`.DataView.get_array_size`"""
(attribute,) = _flatten_arguments(
optional=[("attribute", attribute)],
args=args,
kwargs=kwargs,
)
helper = obj.__get_value_helper(attribute) # noqa: PLW0212
if helper is None:
raise OmniGraphError(f"Could not retrieve a value helper class for attribute {attribute}")
return helper.get_array_size()
# --------------------------------------------------------------------------------------------------------------
@classmethod # noqa: A003
def set(obj, *args, **kwargs) -> bool: # noqa: N804,PLE0202,PLC0202
"""Sets the current value on the owned attribute. This is an undoable action.
This function can be called either from the class or using an instantiated object. Both the attribute and
value argument are mandatory and will raise an error if omitted. The attribute value may optionally be set
through the constructor instead, if this function is called from an object context. These arguments may be set
positionally or by keyword. The remaining arguments are optional but must be specified by keyword only. In an
object context the defaults will be taken from the constructor, else they will use the function defaults.
.. code-block:: python
og.Controller.set("inputs:attr", new_value) # Good
og.Controller("inputs:attr").set(new_value) # Good
og.Controller.set("inputs:attr") # Bad - missing value
og.Controller.set("inputs:attr", new_value, undoable=False) # Good
og.Controller("inputs:attr", undoable=False).set(new_value) # Good
Args:
obj: Either cls or self depending on how the function was called
attribute: Attribute whose value is to be set. If used in an object context and a value was provided
in the constructor then this value overrides that value. It's mandatory, so if it was not
provided in the constructor or here then an error is raised.
value: The new value for the attribute. It's mandatory, so if it was not provided in the constructor or
here then an error is raised.
on_gpu: Is the value stored on the GPU?
update_usd: Should the value immediately propagate to USD?
undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten
gpu_ptr_kind: Type of data to expect for GPU arrays (only used if on_gpu=True)
Returns:
(bool) True if the value was set successfully
Raises:
OmniGraphError: If the current attribute is not valid or could not be set to the given value
"""
return obj.__set(obj, args=args, kwargs=kwargs)
def __set_obj(self, *args, **kwargs) -> bool:
"""Implements :py:meth:`.DataView.set` when called as an object method"""
# Handle the special case of an args list that omits the attribute when it was constructed with an
# existing attribute.
if self.__attribute is not None and args and not isinstance(args[0], og.Attribute):
args = [self.__attribute, *args]
return self.__set(
self,
attribute=self.__attribute,
on_gpu=self.__on_gpu,
update_usd=self.__update_usd,
gpu_ptr_kind=self.__gpu_ptr_kind,
undoable=self.__undoable,
args=args,
kwargs=kwargs,
)
@staticmethod
def __set(
obj,
attribute: AttributeWithValue_t = _Unspecified,
value: ValueToSet_t = _Unspecified,
on_gpu: bool = False,
update_usd: bool = False,
gpu_ptr_kind: Optional[og.PtrToPtrKind] = None,
undoable: bool = True,
args: List[str] = None,
kwargs: Dict[str, Any] = None,
) -> bool:
"""Implements :py:meth:`DataView.set`"""
(attribute, value, on_gpu, update_usd, gpu_ptr_kind, undoable) = _flatten_arguments(
mandatory=[("attribute", attribute), ("value", value)],
optional=[
("on_gpu", on_gpu),
("update_usd", update_usd),
("gpu_ptr_kind", gpu_ptr_kind),
("undoable", undoable),
],
args=args,
kwargs=kwargs,
)
if not isinstance(attribute, og.AttributeData):
attribute = og.ObjectLookup.attribute(attribute)
if is_in_compute() or not undoable:
if isinstance(attribute, og.Attribute):
og.cmds.imm.SetAttr(attribute, value, on_gpu, update_usd)
else:
og.cmds.imm.SetAttrData(attribute, value, on_gpu)
success = True
elif isinstance(attribute, og.Attribute):
(success, _) = og.cmds.SetAttr(attr=attribute, value=value, on_gpu=on_gpu, update_usd=update_usd)
else:
(success, _) = og.cmds.SetAttrData(attribute_data=attribute, value=value, on_gpu=on_gpu)
if not success:
raise OmniGraphError(f"Failed to set value of '{value}' on attribute data '{attribute.get_name()}'")
return success
| 15,027 |
Python
| 47.792208 | 120 | 0.593332 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.