file_path
stringlengths
20
202
content
stringlengths
9
3.85M
size
int64
9
3.85M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
8
993
alphanum_fraction
float64
0.26
0.93
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/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/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/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/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/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/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
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/deprecate.py
r"""This module has moved to omni.graph.tools.deprecate. This file is only here for backward compatibility. _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ """ from omni.graph.tools import DeprecatedClass # noqa from omni.graph.tools import DeprecatedImport # noqa from omni.graph.tools import DeprecateMessage # noqa from omni.graph.tools import RenamedClass # noqa from omni.graph.tools import deprecated_function # noqa DeprecateMessage.deprecated("omni.graph.core.deprecate is deprecated. Use omni.graph.tools.deprecate instead.")
975
Python
59.999996
111
0.406154
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/database.py
# pylint: disable=too-many-lines """ Implementation of the support for the generated node database, which provides access tailored to the specific configuration of a node. """ from __future__ import annotations import inspect from contextlib import suppress from dataclasses import dataclass from functools import partial from typing import Any, Callable, Dict, List, Optional, Tuple import omni.graph.core as og import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn from carb import log_error as carb_error from carb import log_info as carb_info from carb import log_warn as carb_warn # Type definition for the generated data that will contain attribute definition data AttributeDescriptionType = List[Tuple[str, str, str, str, Dict, bool, Any]] # Mapping from the extended type reported in the interface data and the one used by attributes EXTENDED_TYPES = { ogn.EXTENDED_TYPE_REGULAR: og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, ogn.EXTENDED_TYPE_UNION: og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, ogn.EXTENDED_TYPE_ANY: og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, } # Mapping of a port type to the namespace it uses PORT_TO_NS = { og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: ogn.INPUT_NS, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: ogn.OUTPUT_NS, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: ogn.STATE_NS, } # These are all this module is intended to export. Anything else is internal implementation details. __all__ = [ "Database", "DynamicAttributeAccess", "DynamicAttributeInterface", ] # ================================================================================ def get_caller_info(depth: int = 1) -> Tuple[str, str, int, str]: """Retrieves the information from the caller at the given stack depth Args: depth: Stack depth, where 1 is the caller of this function Returns: (CALLER_FILE_PATH, CALLER_LINE_NUMBER, CALLER_FUNCTION) """ try: caller_frame = inspect.stack()[depth] return caller_frame.filename, caller_frame.lineno, caller_frame.function except Exception: # noqa: PLW0703 return "Unknown", -1, "Unknown" # ===================================================================== class _PropertyOrDefault: """Helper class for attribute properties, returning the default if a property did not exist, its value if it does. This facilitates creation of parallel structures for attribute hierarchies so that you can access the information like this: db.inputs.myAttr db.roles.inputs.myAttr db.attributes.inputs.myAttr """ def __init__(self, default_value): """Set up the default for any properties that do not exist""" self.__default = default_value def __getattr__(self, name): """Override of property accessor, returning the default instead of AttributeError when it does not exist""" try: return self.__dict__[name] except KeyError: return self.__default # ============================================================================================================== class _DynamicAttributeInfo: """Helper class to manage dynamic attribute additions and removals. This assumes the data is managed in the standard tree X.inputs.Y, X.outputs.Y, X.state.Y and adds and removes dynamic attribute data from the correct location. The method per_attribute_data() should be overridden to provide the data that is stored at the leaf level of this tree (i.e. the "Y" value) """ __slots__ = ["inputs", "outputs", "state"] def __init__(self): self.inputs = [] self.outputs = [] self.state = [] # ---------------------------------------------------------------------- def __get_port_information(self, port_type: og.AttributePortType) -> _PropertyOrDefault: """Return the container for role information on the given port type""" if port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: return self.inputs if port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: return self.outputs if port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: return self.state return None # ---------------------------------------------------------------------- def __property_name(self, attribute: og.Attribute) -> str: """Returns the name of the property on this class to set for the given attribute""" return attribute.get_name().replace(f"{PORT_TO_NS[attribute.get_port_type()]}:", "") # ---------------------------------------------------------------------- def add_attribute(self, new_attribute: og.Attribute): """Add in the information for a newly created attribute.""" property_name = self.__property_name(new_attribute) port_data = self.__get_port_information(new_attribute.get_port_type()) if property_name in dir(port_data): raise og.OmniGraphError(f"Tried to add the same dynamic attribute '{new_attribute.get_name()}' twice") setattr(port_data, property_name, self.per_attribute_data(new_attribute)) # ---------------------------------------------------------------------- def remove_attribute(self, old_attribute: og.Attribute): """Remove the information for a newly deleted attribute""" property_name = self.__property_name(old_attribute) port_data = self.__get_port_information(old_attribute.get_port_type()) if property_name not in dir(port_data): raise og.OmniGraphError(f"Tried to remove unknown dynamic attribute '{old_attribute.get_name()}'") delattr(port_data, property_name) # ---------------------------------------------------------------------- def per_attribute_data(self, attribute: og.Attribute) -> Any: """Override this to store the correct dynamic attribute data on this instance of the object""" raise og.OmniGraphError("Tried to store per-attribute data of unknown type") # ===================================================================== class _Role(_DynamicAttributeInfo): """ Helper class that allows roles to be accessed by using a syntax similar to attribute values. The attribute value for input attribute X would be accessed with "db.inputs.X". This class allows the role to be accessed with "db.roles.inputs.X", returning None if the attribute has no assigned role. All that's required of the derived class is for it to set members who have roles using the normal syntax: db.role.inputs.X = db.ROLE_COLOR """ def __init__(self): """Set up attributes for role discovery""" super().__init__() self.inputs = _PropertyOrDefault(None) self.outputs = _PropertyOrDefault(None) self.state = _PropertyOrDefault(None) def per_attribute_data(self, attribute: og.Attribute) -> Any: """Returns the per-attribute data added for this type by dynamic attributes""" return attribute.get_resolved_type().role # ===================================================================== @dataclass class _AttributeData: """-------- FOR GENERATED CODE USE ONLY -------- Simple class holding information used to define attributes """ name: str data_type: str extended_type_index: int metadata: Dict is_required: bool default_value: Any is_deprecated: bool deprecation_msg: str def base_name(self) -> str: """Returns the attribute name with the leading namespace removed and colons replaced by underscores""" return ogn.attribute_name_as_python_property(self.name) def extended_type(self) -> og.ExtendedAttributeType: """Returns the extended type of this attribute definition, converted from the int index value""" return EXTENDED_TYPES[self.extended_type_index] # ===================================================================== class _AttributeCache: """-------- FOR GENERATED CODE USE ONLY -------- Handler for OGN attribute definitions that create simple accessors for them. This is for use by the generated code, to manage automatic registration of attributes with the node type, and to provide a common location for unchanging attribute data as found in _AttributeData. Attribute-specific members will be added by the generated code by their names. In the typical configuration, this class will be instantiated three times in the database under an umbrella "INTERFACE" static object, as "inputs", "outputs", and "state". That way the code can do things like access the definition information for the input attribute named "usb" through OgnMyDatabase.INTERFACE.inputs.usb. """ def add_to_node_type(self, node_type_method: Callable, extended_node_type_method: Callable): """Adds all attributes that are members of this class to the node type using the passed-in method. This will only be called by the generated code when it is setting up the definition of a node type. Args: node_type_method: Function to call that will add the attributes to a specific INodeType definition """ for property_name in vars(self): member = getattr(self, property_name) if isinstance(member, _AttributeData): if member.extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: node_type_method(member.name, member.data_type, member.is_required, member.default_value) else: extended_node_type_method(member.name, member.data_type, member.is_required, member.extended_type()) # ===================================================================== class _AllAttributeDefinitions: def __init__(self, descriptions: AttributeDescriptionType): """Create an attribute definition cache using the information parsed from the descriptions list. Args: descriptions: List of attribute definition tuples (name, data_type, uiName, description, metadata, is_required, default_value, is_deprecated, deprecation_msg) Raises: og.OmniGraphError: Raised if there was some problem with the attribute definition """ self.inputs = _AttributeCache() self.outputs = _AttributeCache() self.state = _AttributeCache() for ( name, data_type, extended_type, ui_name, description, metadata, required, default_value, *extra, ) in descriptions: # From omni.graph 1.35 onward, there are two additional parameters in the description. if len(extra) == 2: (deprecated, deprecation_msg) = extra else: deprecated = False deprecation_msg = "" if ui_name is not None: metadata[ogn.MetadataKeys.UI_NAME] = ui_name if description is not None: metadata[ogn.MetadataKeys.DESCRIPTION] = description attribute_data = _AttributeData( name, data_type, extended_type, metadata, required, default_value, deprecated, deprecation_msg ) # Output Bundles are represented as prims and cannot have embedded namespace separators if (ogn.is_output_name(name) or ogn.is_state_name(name)) and data_type == "bundle": attribute_data.name = name.replace(":", "_") property_name = attribute_data.base_name() if ogn.is_input_name(name): setattr(self.inputs, property_name, attribute_data) elif ogn.is_output_name(name): setattr(self.outputs, property_name, attribute_data) elif ogn.is_state_name(name): setattr(self.state, property_name, attribute_data) else: raise og.OmniGraphError(f"Namespace for attribute '{name}' is unknown") def add_to_node_type(self, node_type: og.NodeType): """Take all of the attribute definitions parsed by this class and add them to the given node type Args: node_type: Object containing the instantiataion of an INodeType definition """ self.inputs.add_to_node_type(node_type.add_input, node_type.add_extended_input) self.outputs.add_to_node_type(node_type.add_output, node_type.add_extended_output) self.state.add_to_node_type(node_type.add_state, node_type.add_extended_state) # ===================================================================== class _AttributeContainer(_DynamicAttributeInfo): """-------- FOR GENERATED CODE USE ONLY -------- Handler for maintaining local copies of the og.Attribute values for a node in a structure that provides more natural access to them. For example the attribute "inputs:enterprise" would be accessible through the container member inputs.enterprise and would be of type og.Attribute. """ def __parse_cache(self, cache: _AttributeCache): """Returns an object that contains the parsed structure in the cache""" structure = type("", (), {}) for property_name in vars(cache): member = getattr(cache, property_name) if isinstance(member, _AttributeData): attribute = self.node.get_attribute(member.name) if not attribute.is_valid(): raise og.OmniGraphError(f"Could not find node's attribute '{member.name}'") if member.metadata: for key, value in member.metadata.items(): # Metadata is only str:str for now so convert non-strings into strings for later parsing if isinstance(value, list): value = ",".join(value) elif not isinstance(value, str): value = f"'{value}'" attribute.set_metadata(key, value) if member.is_deprecated: og._internal.deprecate_attribute(attribute, member.deprecation_msg) # noqa: PLW0212 attribute.is_optional_for_compute = not member.is_required setattr(structure, member.base_name(), attribute) return structure def __init__(self, node: og.Node, definitions: _AllAttributeDefinitions): """Create the structure containing the attribute objects as class members""" super().__init__() self.node = node self.inputs = self.__parse_cache(definitions.inputs) self.outputs = self.__parse_cache(definitions.outputs) self.state = self.__parse_cache(definitions.state) def per_attribute_data(self, attribute: og.Attribute) -> Any: """Returns the per-attribute data added for this type by dynamic attributes""" return attribute # ===================================================================== class PerNodeKeys: """Set of key values for per-node data. This is data that belongs to a node, but which is only valid for Python node implementations. Any data that belongs to all node types should be implemented through the ABI. """ ATTRIBUTES = "attributes" # Definitions of the attribute objects on the node ROLE = "role" # Role object built to provide a parallel method of accessing attribute role data NODE_CALLBACK = "node_callback" # Callback subscription for the node event stream INTERNAL_STATE = "internal_state" # Data stored as internal state information by the user DYNAMIC_ATTRIBUTES = "dynamic_attributes" # Accessor for dynamic attributes on the node ERRORS = "errors" # String list containing the unique errors encountered during evaluation # ===================================================================== class DynamicAttributeInterface: """Class providing a container for dynamic attribute access interfaces. One of these objects is created per-node, per-port, to contain getter and setter properties on dynamic attributes for their node and port type. These classes persist in the per-node data and their property members are updated based on the addition and removal of dynamic attributes from their node. The base class implementation for the attribute accessors, DynamicAttributeAccess, uses this to determine whether an attribute access request was made on a static or dynamic attribute. The per-node data on the database will contain one of these objects per port-type. When the database is created it will be attached to the primary attribute access classes via the base class below, DynamicAttributeAccess. Args: _port_type: Type of port managed by this class (only one allowed per instance). Single underscore only so that the base class of the attribute information can access it. _element_counts: Dictionary of str:int values which maps the names of dynamic output array attributes to the of pending elements to allocate for their array data (required since Fabric takes the element counter as an argument to the data retrieval so it can't be set ahead of time). It is set when a size is set, reset when a value is set, and read from Fabric when it's value is requested. The key values will be the special attribute name that has "_size" appended to it (until such time as the attribute value can support size access itself). _interfaces: Dictionary of str:og.Attribute values which maps the names of a dynamic attribute to the actual attribute on the node. _on_gpu: If True then values are requested from the GPU memory, else the CPU memory _gpu_ptr_kind: Ignored for CPU memory. For GPU memory specifies whether attribute data will be returned as a GPU pointer to the GPU memory, or a CPU pointer to the GPU memory. """ def __init__(self, port_type: og.AttributePortType): """Initialize the namespace used for attributes managed here""" self._port_type: og.AttributePortType = port_type self._interfaces: dict[str, og.Attribute] = {} self._element_counts: dict[str, int] = {} self._on_gpu: bool = False self._gpu_ptr_kind = og.PtrToPtrKind.NA # ---------------------------------------------------------------------- def __property_name(self, attribute: og.Attribute) -> str: """Returns the name of the property on this class to set for the given attribute""" return attribute.get_name().replace(f"{PORT_TO_NS[self._port_type]}:", "") # ---------------------------------------------------------------------- def has_attribute(self, property_name: str) -> bool: """Returns True if the given property name is a known dynamic attribute on this object""" return property_name in self._interfaces # ---------------------------------------------------------------------- def set_default_memory_location(self, on_gpu: bool, gpu_ptr_kind: og.PtrToPtrKind = og.PtrToPtrKind.NA): """Set the default memory location from which dynamic attribute values will be retrieved. This is what will be used if you access dynamic attribute values in the same way you access regular attribute values - e.g. value = db.inputs.dyn_attr. The settings of the two flags will determine the type of memory returned for array attributes, such as float[], double[3][], and matrixd[4][], and non-array attributes such as int[4], uint, and bool. Array attributes +----------------------+----------------------------+----------------------------+ | | on_gpu=True | on_gpu=False | +======================+============================+============================+ | og.PtrToPtrKind.CPU | CPU Pointers to GPU arrays | CPU Pointers to CPU arrays | +----------------------+----------------------------+----------------------------+ | og.PtrToPtrKind.GPU | GPU Pointers to GPU arrays | CPU Pointers to CPU arrays | +----------------------+----------------------------+----------------------------+ | og.PtrToPtrKind.NA | GPU Pointers to GPU arrays | CPU Pointers to CPU arrays | +----------------------+----------------------------+----------------------------+ Non-Array attributes are always returned as CPU values. There is currently no supported way of overriding these access methods. If not specified they will default to everything being on the CPU. Args: on_gpu: If true then array attributes will be returned from GPU memory, else from CPU memory gpu_ptr_kind: Determines if there is a CPU memory wrapper around the GPU allocated memory, as above. """ self._on_gpu = on_gpu self._gpu_ptr_kind = gpu_ptr_kind # ---------------------------------------------------------------------- def get(self, property_name: str, context_helper: Any = None) -> Any: """Returns the value of the named attribute Args: property_name: Name of the property within the namespace of this object's port type context_helper: Deprecated Raises: og.OmniGraphError: If the attribute is unknown """ if context_helper is not None: ogt.DeprecateMessage.deprecated("context_helper is no longer an argument of get. Please remove.") try: attribute = self._interfaces[property_name] except KeyError as error: raise og.OmniGraphError(f"Tried to get the value of unknown dynamic attribute '{property_name}'") from error # For the special syntax "x = db.inputs.array_size" retrieve the element count for the attribute "inputs:array" # Non-arrays will not have an entry in self._element_counts so this will be skipped for them. if property_name in self._element_counts: if self._element_counts[property_name] is None: self._element_counts[property_name] = og.DataView(attribute=attribute).get_array_size() return self._element_counts[property_name] # Retrieve the attribute value from Fabric on_gpu = self._on_gpu and (attribute.get_resolved_type().array_depth == 1) pending_element_count = self._element_counts.get(f"{property_name}_size", None) return og.DataView( attribute=attribute, on_gpu=on_gpu, gpu_ptr_kind=self._gpu_ptr_kind, ).get(reserved_element_count=pending_element_count) # ---------------------------------------------------------------------- def set( # noqa: A003 self, property_name: str, context_helper: Any = None, locked: bool = False, new_value: Any = None ) -> bool: """Sets the value of the named attribute Args: property_name: Name of the property within the namespace of this object's port type context_helper: Deprecated locked: True if setting read-only values is currently locked (i.e. inside a compute) new_value: Value to be set on the attribute with the given name Raises: og.OmniGraphError: If the attribute is unknown og.ReadOnlyError: If writing is locked and the attribute is read-only Returns: True if the value was set """ if context_helper is not None: ogt.DeprecateMessage.deprecated("context_helper is no longer an argument of set. Please remove.") # For the special syntax "db.outputs.array_size = x" set the element count for the attribute "outputs:array" # Non-arrays will not have an entry in self._element_counts so this will be skipped for them. The value of # the element count will be used when getting the actual array at a later time. if property_name in self._element_counts: self._element_counts[property_name] = new_value return True try: attribute = self._interfaces[property_name] except KeyError as error: raise og.OmniGraphError(f"Tried to set the value of unknown dynamic attribute '{property_name}'") from error if (self._port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) and locked: raise og.ReadOnlyError(attribute) on_gpu = self._on_gpu and (attribute.get_resolved_type().array_depth == 1) # If this was an array attribute being set then reset the array size so that it can be read again from Fabric # the next time it is requested. (It could also be set after the og.DataView.set() call but this delays that # extra call until it's actually requested.) element_count_name = f"{property_name}_size" if element_count_name in self._element_counts: self._element_counts[element_count_name] = None return og.DataView(attribute=attribute, on_gpu=on_gpu, gpu_ptr_kind=self._gpu_ptr_kind).set(new_value) # ---------------------------------------------------------------------- def add_attribute(self, new_attribute: og.Attribute): """Add in the interface for a newly created attribute. This creates a new attribute on this object named for the new attribute. The value of that attribute is a pair of functions that will get and set the value for that attribute. Args: new_attribute: Attribute that was just added Raises: og.OmniGraphError: If the attribute has a mismatched port type """ if new_attribute.get_port_type() != self._port_type: raise og.OmniGraphError( f"Adding attribute {new_attribute.get_name()} onto the wrong port type {self._port_type}" ) property_name = self.__property_name(new_attribute) if property_name in self._interfaces: raise og.OmniGraphError(f"Tried to add the same dynamic attribute '{new_attribute.get_name()}' twice") self._interfaces[property_name] = new_attribute if new_attribute.get_resolved_type().array_depth > 0: self._element_counts[f"{property_name}_size"] = 0 # ---------------------------------------------------------------------- def remove_attribute(self, old_attribute: og.Attribute): """Remove the interface for a newly deleted attribute Args: old_attribute: Attribute that is about to be removed Raises: og.OmniGraphError: If the attribute has a mismatched port type, or the property didn't exist """ if old_attribute.get_port_type() != self._port_type: raise og.OmniGraphError( f"Removing attribute {old_attribute.get_name()} from the wrong port type {self._port_type}" ) property_name = self.__property_name(old_attribute) with suppress(KeyError): del self._element_counts[f"{property_name}_size"] try: del self._interfaces[property_name] except KeyError as error: raise og.OmniGraphError( f"Tried to remove non-existent dynamic attribute {old_attribute.get_name()}" ) from error # ===================================================================== class DynamicAttributeAccess: """Base class for the generated classes that contain the access properties for all attributes. Each of the port containers, db.inputs/db.outputs/db.state, houses the attribute data access properties. These containers are constructed when the database is created, with hardcoded properties for all statically defined attributes. This class intercepts getattr/setattr/delattr calls to check to see if the property being requested is a dynamic attribute, and if so then it uses the properties stored in the per-node data as the access points. So the lookup sequence goes: db -> og.Database .inputs -> ValuesForInput(DynamicAttributeAccess) .myAttribute -> DynamicAttributeAccess.__getattr__ -> ValuesForInput.__getattr__ (if the above fails) It makes the bold assumption that the attributes are all set up nicely; no duplicate names, invalid types, missing configuration, etc. Attributes use leading underscores to minimize name collisions with the dynamically added attributes. (Double underscores would have been preferable but would have made access from the derived classes problematic.) Members: _context: Graph context used for evaluating this node _node: The OmniGraph node to which this data belongs _attributes: The set of attributes on this object's port _dynamic_attributes: Container holding the per-node specification of dynamic attributes, not visible to derived classes """ def __init__( self, context_id: og.GraphContext, node: og.Node, attributes, dynamic_attributes: DynamicAttributeInterface, ): """Initialize common data used for all attribute port types""" if isinstance(context_id, og.GraphContext): super().__setattr__("_context", context_id) else: # V1_5_0 compatibility super().__setattr__("_context", context_id.context) super().__setattr__("_node", node) super().__setattr__("_attributes", attributes) super().__setattr__("_dynamic_attributes", dynamic_attributes) # Inputs are the only ones with the lock. It's only on during compute so initialize to False here if dynamic_attributes._port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: super().__setattr__("_setting_locked", False) # ---------------------------------------------------------------------- def __str__(self) -> str: """Debug visualization of the important information in this class""" table = [] members = [] for member_class in [self.__class__, self._dynamic_attributes.__class__]: class_members = inspect.getmembers(member_class) members.append( [member_class, [a[0] for a in class_members if not (a[0].startswith("__") and a[0].endswith("__"))]] ) for member_class, member_list in members: for member in member_list: as_property = getattr(member_class, member) if isinstance(as_property, property): value = member if as_property.fget is not None: value += " + getter" if as_property.fset is not None: value += " + setter" if as_property.fdel is not None: value += " + deleter" table.append(value) return str(table) # ---------------------------------------------------------------------- def get_dynamic_attributes(self) -> DynamicAttributeInterface: """Returns the dynamic attributes managed by this class, avoiding the __getattr__ override""" return super().__getattribute__("_dynamic_attributes") # ---------------------------------------------------------------------- def __getattr__(self, item: str) -> Any: """Intercept requests for attribute information that wasn't pre-generated, to support dynamic attributes""" dynamic_attributes = self.get_dynamic_attributes() if dynamic_attributes.has_attribute(item) or dynamic_attributes.has_attribute(item[:-5]): return dynamic_attributes.get(item, None) return super().__getattribute__(item) # ---------------------------------------------------------------------- def __setattr__(self, item: str, new_value: Any): """Intercept requests for attribute information that wasn't pre-generated, to support dynamic attributes""" dynamic_attributes = self.get_dynamic_attributes() if dynamic_attributes.has_attribute(item) or dynamic_attributes.has_attribute(item[:-5]): setting_locked = ( dynamic_attributes._port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ) and self._setting_locked dynamic_attributes.set(item, None, setting_locked, new_value) else: super().__setattr__(item, new_value) # ---------------------------------------------------------------------- def __delattr__(self, item: str) -> Any: """Intercept requests for removing attribute information that wasn't pre-generated, to support dynamic attributes""" dynamic_attributes = self.get_dynamic_attributes() if dynamic_attributes.has_attribute(item) or dynamic_attributes.has_attribute(item[:-5]): raise og.OmniGraphError( f"Deletion of dynamic attribute '{item}' interface can only be done by" " removing the attribute from the node" ) return super().__delattr__(item) # ===================================================================== class Database: """Base class for the generated database class for .ogn nodes (Python and C++ implementations) Defines some common functionality that is the same for nodes of all types, to help cut down on the amount of redundant generated code. Like the C++ equivalent, you can access the ABI data types normally passed to the compute as: db.abi_node db.abi_context Derived classes will have these class member variables instantiated, which are manipulated here in order to keep the amount of generated code to a minimum: - **INTERFACE**: Attribute interface definition - things that don't change between nodes of the same type - **PER_NODE_DATA**: Dictionary for data that is different on every node of the same type. """ INTERFACE = {} PER_NODE_DATA = {} # ---------------------------------------------------------------------- @staticmethod def _get_interface(descriptions: AttributeDescriptionType) -> _AllAttributeDefinitions: """Returns per-class data containing an attribute cache constructed from the descriptions.""" return _AllAttributeDefinitions(descriptions) # ---------------------------------------------------------------------- @classmethod def _populate_role_data(cls) -> _Role: """Returns the role structure corresponding to the node type's attributes. While this could be calculated directly it's more efficient to let the generated code do it, as there will usually not be many roles to add. Thie method can safely return an empty _Role() object because it has been designed to provide correct default values for missing properties. """ return _Role() # ---------------------------------------------------------------------- @classmethod def dynamic_attribute_data(cls, node: og.Node, port_type: og.AttributePortType) -> DynamicAttributeInterface: """Returns the dynamic attribute data class stored on each node for a given port type""" try: dynamic_information = cls.per_node_data(node)[PerNodeKeys.DYNAMIC_ATTRIBUTES] except KeyError as error: raise og.OmniGraphError(f"No per-node dynamic attribute information for {node.get_prim_path}") from error try: return dynamic_information[port_type] except KeyError as error: raise og.OmniGraphError(f"No dynamic port information on {node.get_prim_path()} for {port_type}") from error # ---------------------------------------------------------------------- @classmethod def __per_node_roles(cls, node: og.Node) -> Optional[_Role]: """Returns the dynamic attribute role class stored on each node for a given port type""" try: role_information = cls.per_node_data(node)[PerNodeKeys.ROLE] except KeyError as error: raise og.OmniGraphError(f"No per-node role information for {node.get_prim_path}") from error return role_information # ---------------------------------------------------------------------- @classmethod def __per_node_attributes(cls, node: og.Node) -> Optional[_AttributeContainer]: """Returns the dynamic attribute container class stored on each node for a given port type""" try: attribute_information = cls.per_node_data(node)[PerNodeKeys.ATTRIBUTES] except KeyError as error: raise og.OmniGraphError(f"No per-node attribute information for {node.get_prim_path}") from error return attribute_information # ---------------------------------------------------------------------- @classmethod def __on_attribute_created(cls, node: og.Node, attribute: og.Attribute): """Callback run when an event was received from the node that it created a new dynamic attribute""" cls.dynamic_attribute_data(node, attribute.get_port_type()).add_attribute(attribute) cls.__per_node_roles(node).add_attribute(attribute) cls.__per_node_attributes(node).add_attribute(attribute) # ---------------------------------------------------------------------- @classmethod def __on_attribute_removed(cls, node: og.Node, attribute: og.Attribute): """Callback run when an event was received from the node that it removed an existing dynamic attribute""" cls.dynamic_attribute_data(node, attribute.get_port_type()).remove_attribute(attribute) cls.__per_node_roles(node).remove_attribute(attribute) cls.__per_node_attributes(node).remove_attribute(attribute) # ---------------------------------------------------------------------- @classmethod def __on_node_event(cls, node: og.Node, event): """Callback run when the generated node sends off an event""" if event.type == int(og.NodeEvent.CREATE_ATTRIBUTE): cls.__on_attribute_created(node, node.get_attribute(event.payload["attribute"])) elif event.type == int(og.NodeEvent.REMOVE_ATTRIBUTE): cls.__on_attribute_removed(node, node.get_attribute(event.payload["attribute"])) # ---------------------------------------------------------------------- @classmethod def _initialize_per_node_data(cls, node: og.Node): """Sets up the per-node dictionary of data to cache for faster lookup""" per_node_data = { PerNodeKeys.ATTRIBUTES: _AttributeContainer(node, cls.INTERFACE), PerNodeKeys.DYNAMIC_ATTRIBUTES: { og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: DynamicAttributeInterface( og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: DynamicAttributeInterface( og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ), og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: DynamicAttributeInterface( og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE ), }, PerNodeKeys.ROLE: cls._populate_role_data(), PerNodeKeys.NODE_CALLBACK: node.get_event_stream().create_subscription_to_pop( partial(cls.__on_node_event, node), name=f"{node.get_prim_path()} Event" ), PerNodeKeys.ERRORS: [], } # If the node has implemented the internal_state() method then it will be managing per-node state information. try: get_data_fn = getattr(cls.NODE_TYPE_CLASS, PerNodeKeys.INTERNAL_STATE) except AttributeError: get_data_fn = None # Process this after exception handling in case the instantiation itself raises an exception. if get_data_fn: per_node_data[PerNodeKeys.INTERNAL_STATE] = get_data_fn() cls.PER_NODE_DATA[node.node_id()] = per_node_data for attribute in node.get_attributes(): if not attribute.is_dynamic(): continue cls.__on_attribute_created(node, attribute) # ---------------------------------------------------------------------- @classmethod def _release_per_node_data(cls, node: og.Node): """Release the dictionary entry for this node's data, if any""" with suppress(KeyError): cls.PER_NODE_DATA.pop(node.node_id()) # ---------------------------------------------------------------------- @classmethod def per_node_data(cls, node: og.Node) -> Dict[str, Any]: """Returns the per-node data for the given node Args: node: OmniGraph node for which the data is to be retrieved Raises: og.OmniGraphError: If the per-node data is missing, most likely because the node is not initialized """ try: return cls.PER_NODE_DATA[node.node_id()] except AttributeError as error: raise og.OmniGraphError( f"Database class {cls.__name__} not initialized. No per-node data available" ) from error except KeyError as error: raise og.OmniGraphError( f"Database class {cls.__name__} does not contain per-node data for '{node.get_prim_path()}'" ) from error # ---------------------------------------------------------------------- # Role definitions, for comparison to find role-based attributes ROLE_BUNDLE = "bundle" ROLE_COLOR = "color" ROLE_EXECUTION = "execution" ROLE_FRAME = "frame" ROLE_MATRIX = "matrix" ROLE_NORMAL = "normal" ROLE_OBJECT_ID = "objectId" ROLE_PATH = "path" ROLE_POINT = "point" ROLE_QUATERNION = "quaternion" ROLE_TEXCOORD = "texcoord" ROLE_TIMECODE = "timecode" ROLE_TRANSFORM = "transform" ROLE_VECTOR = "vector" # ---------------------------------------------------------------------- def __init__(self, node: og.Node, context_helper: Optional[Any] = None): """Initialize the helper classes for roles and sizes - attribute values are defined in the derived classes""" if context_helper is not None: ogt.DeprecateMessage().deprecated("context_helper is no longer an initializer parameter. Please remove.") self.node = node self.context = node.get_graph().get_default_graph_context() try: per_node_data = self.PER_NODE_DATA[node.node_id()] except KeyError: self._initialize_per_node_data(node) per_node_data = self.PER_NODE_DATA[node.node_id()] # Set up properties that let the database access the per-node data as though it belonged to it for per_node_data_type, per_node_data_value in per_node_data.items(): setattr(self, per_node_data_type, per_node_data_value) # ---------------------------------------------------------------------- def get_metadata(self, metadata_key: str, attribute: Optional[og.Attribute] = None) -> Optional[str]: """Get metadata related to this node. To get the metadata on the node type: ui_name = db.get_metadata(ogn.MetadataKeys.UI_NAME) To get the metadata from a specific attribute: input_x_ui_name = db.get_metadata(ogn.MetadataKeys.UI_NAME, db.attribute.inputs.x) Args: metadata_key: Name of the metadata value to return attribute: Attribute on which the metadata lives. If None then look at the node type's metadata Returns: Metadata value string, or None if the named metadata key did not exist """ if attribute is None: return self.node.get_node_type().get_metadata(metadata_key) return attribute.get_metadata(metadata_key) # ---------------------------------------------------------------------- @property def abi_node(self) -> og.Node: """Returns the node to which this database belongs""" return self.node # ---------------------------------------------------------------------- @property def abi_context(self) -> og.GraphContext: """Returns the graph context to which this database belongs""" return self.context # ---------------------------------------------------------------------- @ogt.deprecated_function("Move does not exists anymore. This function will perform copy instead") def move(self, dst: og.Attribute, src: og.Attribute): """ Deprecated function. Will perform a copy instead of moving """ dst.get_attribute_data().copy_data(src.get_attribute_data()) # ---------------------------------------------------------------------- @staticmethod def __formatted_message(message: str, severity: str) -> str: """Return the commonly formatted error message to report for OmniGraph failures""" # Depth of 3 to ignore this one, and the log_XX method that called it to get the real reporter (file_path, line_number, function_name) = get_caller_info(3) intro = f"OmniGraph {severity}: " indent = " " * len(intro) return f"{intro}{message}\n{indent}(from {function_name}() at line {line_number} in {file_path})" # ---------------------------------------------------------------------- def log_error(self, message: str, add_context: bool = True): """Log an error message from a compute method, for when the compute data is inconsistent or unexpected""" if add_context: message = self.__formatted_message(message, "Error") try: self.abi_node.log_compute_message(og.Severity.ERROR, message) except AttributeError: # Older extensions may not have access to the node message logging ABI. error_list = self.per_node_errors(self.abi_node) if message not in error_list: error_list.append(message) carb_error(message) # ---------------------------------------------------------------------- def log_warn(self, message: str): """Log a warning message from a compute method, when the compute is consistent but produced no results. This method is identical to log_warning; both exist because there are different conventions in other code about which name to use, so to avoid wasted developer time fixing unimportant incorrect guesses both are implemented. """ message = self.__formatted_message(message, "Warning") try: self.abi_node.log_compute_message(og.Severity.WARNING, message) except AttributeError: # Older extensions may not have access to the node message logging ABI. error_list = self.per_node_errors(self.abi_node) if message not in error_list: error_list.append(message) carb_warn(message) # ---------------------------------------------------------------------- def log_warning(self, message: str): """Log a warning message from a compute method, when the compute is consistent but produced no results. This method is identical to log_warn; both exist because there are different conventions in other code about which name to use, so to avoid wasted developer time fixing unimportant incorrect guesses both are implemented. """ message = self.__formatted_message(message, "Warning") try: self.abi_node.log_compute_message(og.Severity.WARNING, message) except AttributeError: # Older extensions may not have access to the node message logging ABI. error_list = self.per_node_errors(self.abi_node) if message not in error_list: error_list.append(message) carb_warn(message) # ---------------------------------------------------------------------- def log_info(self, message: str): """Log an information message from a compute method, when status information is required about the compute. Usually the compute will be successful, the information is for debugging or analysis. """ message = self.__formatted_message(message, "Info") try: self.abi_node.log_compute_message(og.Severity.INFO, message) except AttributeError: # Older extensions may not have access to the node message logging ABI. error_list = self.per_node_errors(self.abi_node) if message not in error_list: error_list.append(message) carb_info(message) # ---------------------------------------------------------------------- @classmethod def per_node_internal_state(cls, node: og.Node): """Returns the internal state information on the node, or None if it does not exist""" return cls.per_node_data(node).get(PerNodeKeys.INTERNAL_STATE, None) # ---------------------------------------------------------------------- @classmethod def per_node_errors(cls, node: og.Node): """Returns the compute errors on the node, or [] if it does not exist""" try: return cls.per_node_data(node)[PerNodeKeys.ERRORS] except KeyError: cls.per_node_data(node)[PerNodeKeys.ERRORS] = [] return cls.per_node_data(node)[PerNodeKeys.ERRORS] # ---------------------------------------------------------------------- def get_variable(self, name: str): """Get the value of a variable with a given name. Returns None if the variable does not exist on the graph. """ graph = self.node.get_graph() var = graph.find_variable(name) if not var: return None if var.type.array_depth >= 1: return var.get_array(self.context) return var.get(self.context) # ---------------------------------------------------------------------- def set_variable(self, name: str, value): """Set the value of a variable. og.OmniGraphError will be raised if the variable does not exist on the graph, or if there is type mismatch""" graph = self.node.get_graph() var = graph.find_variable(name) if not var: raise og.OmniGraphError(f"Could not find variable {name}") if not var.set(self.context, value): raise og.OmniGraphError( f"Could not set variable {name} to {value}. Is {value} the proper type ({var.type})?" ) # ---------------------------------------------------------------------- def set_dynamic_attribute_memory_location(self, on_gpu: bool, gpu_ptr_kind: og.PtrToPtrKind = og.PtrToPtrKind.NA): """Set the memory location from which dynamic attribute values will be retrieved Args: on_gpu: If true the data will be returned from GPU memory, else from CPU memory gpu_ptr_kind: Ignored for CPU memory. For GPU memory specifies whether attribute data will be returned as a GPU pointer to the GPU memory, or a CPU pointer to the GPU memory. """ try: attribute_accessors = self.per_node_data(self.node)[PerNodeKeys.DYNAMIC_ATTRIBUTES] except KeyError as error: raise og.OmniGraphError(f"Dynamic attribute accessors not found for {self.node.get_prim_path()}") from error for interface in attribute_accessors.values(): interface.set_default_memory_location(on_gpu, gpu_ptr_kind)
52,069
Python
49.067308
120
0.593751
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/commands.py
""" Expose the public interface for all commands that work with OmniGraph. All of the available commands are packaged up into a single "cmds" object with any redundant "Command" suffix removed. This is how you would access any of the OmniGraph commands: .. code-block:: python import omni.graph.core as og og.cmds.CreateNode(graph=my_graph, node_path=my_node_path, node_type=my_node_type, create_usd=True) You can list all available commands by inspecting the cmds object: .. code-block:: python [cmd for cmd in dir(og.cmds) if not cmd.startswith("_")] """ from omni.kit.commands import register_all_commands_in_module as _register_commands __all__ = ["cmds"] from .instancing_commands import ApplyOmniGraphAPICommand # noqa: F401 from .instancing_commands import RemoveOmniGraphAPICommand # noqa: F401 # ============================================================================================================== # 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 .topology_commands import ConnectAttrsCommand # noqa: F401 from .topology_commands import ConnectPrimCommand # noqa: F401 from .topology_commands import CreateAttrCommand # noqa: F401 from .topology_commands import CreateGraphAsNodeCommand # noqa: F401 from .topology_commands import CreateNodeCommand # noqa: F401 from .topology_commands import CreateSubgraphCommand # noqa: F401 from .topology_commands import CreateVariableCommand # noqa: F401 from .topology_commands import DeleteNodeCommand # noqa: F401 from .topology_commands import DisconnectAllAttrsCommand # noqa: F401 from .topology_commands import DisconnectAttrsCommand # noqa: F401 from .topology_commands import DisconnectPrimCommand # noqa: F401 from .topology_commands import RemoveAttrCommand # noqa: F401 from .topology_commands import RemoveVariableCommand # noqa: F401 from .topology_commands import _OGRestoreConnectionsOnUndo # noqa: F401 from .value_commands import ChangePipelineStageCommand # noqa: F401 from .value_commands import DisableGraphCommand # noqa: F401 from .value_commands import DisableGraphUSDHandlerCommand # noqa: F401 from .value_commands import DisableNodeCommand # noqa: F401 from .value_commands import EnableGraphCommand # noqa: F401 from .value_commands import EnableGraphUSDHandlerCommand # noqa: F401 from .value_commands import EnableNodeCommand # noqa: F401 from .value_commands import RenameNodeCommand # noqa: F401 from .value_commands import RenameSubgraphCommand # noqa: F401 from .value_commands import SetAttrCommand # noqa: F401 from .value_commands import SetAttrDataCommand # noqa: F401 from .value_commands import SetEvaluationModeCommand # noqa: F401 from .value_commands import SetVariableTooltipCommand # noqa: F401 # By placing this in an internal list and exporting the list the backward compatibility code can make use of it # to allow access to the now-internal objects in a way that looks like they are still published. _HIDDEN = [ "ConnectAttrsCommand", "ConnectPrimCommand", "CreateAttrCommand", "CreateGraphAsNodeCommand", "CreateNodeCommand", "CreateSubgraphCommand", "CreateVariableCommand", "DeleteNodeCommand", "DisconnectAttrsCommand", "DisconnectAllAttrsCommand", "DisconnectPrimCommand", "RemoveAttrCommand", "RemoveVariableCommand", "_OGRestoreConnectionsOnUndo", "DisableGraphCommand", "DisableNodeCommand", "EnableGraphCommand", "EnableNodeCommand", "DisableGraphUSDHandlerCommand", "EnableGraphUSDHandlerCommand", "RenameNodeCommand", "RenameSubgraphCommand", "SetAttrCommand", "SetAttrDataCommand", "ChangePipelineStageCommand", "SetVariableTooltipCommand", "SetEvaluationModeCommand", "ApplyOmniGraphAPICommand", "RemoveOmniGraphAPICommand", ] cmds = _register_commands(__name__)
4,348
Python
43.377551
113
0.709292
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/data_typing.py
"""Contains support for wrapping Python objects around FlatCache typed data These patterns draw heavily on the interfaces used by numpy as that is what is provided when dealing with Python data on the CPU. The intent is to make the data interface pattern as similar as possible to make dealing with it more consistent, though not to try to replicate any of the numpy functionality - that is left up to the interpreter of this data. The data wrapper consists of a raw memory pointer and a set of type identification information that corresponds to the types supported by FlatCache (including those that will be supported in the foreseeable future). One major way that the data typing differs from numpy is in the shape specification. While numpy insists that its data be a matrix (i.e. a shape of (2,3) means a fully populated 2x3 matrix) this shape specification can include different index counts in each level to accommodate gathered data. To avoid ambiguity the gathered element sizes are placed in a tuple, even when it's only a single value. e.g. 4x4 matrix = shape(4, 4) Array of 5 4x4 matrixes = shape(5, 4, 4) Two gathered 4x4 matrixes = shape((2,), 4, 4) Two gathered arrays of 5 and 6 4x4 matrixes = shape((5, 6), 4, 4) Here's how the shapes correspond to the access patterns, where the values returned are either memory pointers to a particular element or another DataWrapper which access the sub-array. The indexes in the shape are from largest scope to smallest scope, so gathered size is first, then array size, then tuple size. The index operator can be specified by one or more index values, traversing down multiple levels of the array hierarchy. These two are equivalent, though the first is more efficient - wrapper[I, J, K], wrapper[I][J][K] These are the shape types currently supported by FlatCache, using float values as examples: None - "Item is a single value, not an array" (2,) - "An array of two elements" float[] of size 2 index[I] is the Ith element of the array float[2] index[I] is the Ith tuple member ((2,)) - "A gathered set of two items" float with 2 gathered items index[I] is the Ith gathered item (2,3) - "An array of 2 arrays with 3 elements each" float[3][] of size 2 item[I] = Ith float[3] in the array item[I, J] = Jth tuple member of the Ith float[3] in the array ((2,),3) - "An array of two arrays with 3 elements each" float[3] with 2 gathered items item[I] = Ith gathered float[3] item[I, J] = Jth tuple member of the Ith gathered float[3] ((3,4)) - "An array of 2 arrays, the first with 3 elements, the second with 4" float[] with gathered items of sizes 3 and 4 item[I] = Ith gathered array of floats item[I, J] = Jth element of the Ith gathered float[] ((2,3),3) - "An array of 2 arrays of arrays with 3 elements, the first is an array of 2 arrays, the second is an array of 3 arrays" float[3][] with 2 gathered array items of length 2 and 3 respectively item[I] = Ith gathered array of float[3]s item[I, J] = Jth element of the Ith gathered array of float[3]s item[I, J, K] = Kth tuple member of the Jth element of the Ith gathered array of float[3]s There are also special cases for arrays, which are like tuples but have two index numbers for row and column. The matrix types can only have 2, 3, or 4 as their tuple count, and must have a base data type of double. (2,2) - "A 2x2 matrix" matrixd[2] item[I] = Ith row of the matrix item[I, J] = Jth column of the Ith row of the matrix (3,2,2) - "An array of 2x2 matrixes" array of matrixd[2] with 3 gathered items item[I] = Ith matrix array element item[I, J] = Jth row of the Ith matrix array element item[I, J, K] = Kth column of the Jth row of the Ith matrix array element ((3),2,2) - "An array of 2x2 matrixes" gathered matrixd[2] with 3 gathered items item[I] = Ith gathered matrix item[I, J] = Jth row of the Ith gathered matrix item[I, J, K] = Kth column of the Jth row of the Ith gathered matrix ((2,3),2,2) - "An array of 2 arrays of 2x2 matrixes, the first with 2 elements, the second with 3 elements" gathered matrixd[2][] with 2 gathered items consisting of an array of 2 matrixes and an array of 3 matrixes respectively item[I] = Ith gathered matrix array item[I, J] = Jth element of the Ith gathered matrix array item[I, J, K] = Kth row of the Jth element of the Ith gathered matrix array item[I, J, K, L] = Lth column of the Kth row of the Jth element of the Ith gathered matrix array Note that while gathered arrays and regular arrays have the same access pattern they are conceptually different in that a gathered array represents data from N different objects which a regular array represents N different values on the same object. """ from __future__ import annotations import ctypes from typing import Tuple, Union import omni.graph.core as og from .dtypes import Dtype # These supported shape types correspond to the ones described above DataWrapperShapeTypes = Union[ None, int, Tuple[int, int], Tuple[Tuple[int, int]], Tuple[Tuple[int, int], int], Tuple[int, int, int], Tuple[int, int, Tuple[int, int]], ] # ============================================================================================================== class Device: """Device type for memory location of the data types""" def __init__(self, device_name: str): """Initialize the device with the given name""" self.__cpu = device_name.lower().find("cpu") == 0 self.__cuda = device_name.lower().find("cuda") == 0 def __str__(self) -> str: """Standardized device name""" return "cpu" if self.__cpu else "cuda" if self.__cuda else "unknown" @property def cpu(self) -> bool: """Is the device a CPU?""" return self.__cpu @property def cuda(self) -> bool: """Is the device a GPU programmed with CUDA?""" return self.__cuda # ============================================================================================================== def data_shape_from_type(attribute_type: og.Type, is_gathered: bool = False) -> Tuple[Dtype, DataWrapperShapeTypes]: """Return the dtype,shape information that corresponds to the given attribute type. For easy testing gather sizes are set to 2 items and array sizes are set to 0 elements. e.g. a gathered bool[] would return a shape of ((0, 0)) """ dtype = None shape = None unmatched_shape = -1 # -------------------------------------------------------------------------------------------------------------- def matrix_shape(dtype_class) -> DataWrapperShapeTypes: """Get the information from a matched matrix type""" if attribute_type.tuple_count != dtype_class.tuple_count: return unmatched_shape if is_gathered: if attribute_type.array_depth == 0: shape = ((2,), dtype_class.matrix_dim, dtype_class.matrix_dim) else: shape = ((2, 2), dtype_class.matrix_dim, dtype_class.matrix_dim) else: if attribute_type.array_depth == 0: shape = (dtype_class.matrix_dim, dtype_class.matrix_dim) else: shape = (0, dtype_class.matrix_dim, dtype_class.matrix_dim) return shape # -------------------------------------------------------------------------------------------------------------- def match_simple(dtype_class) -> DataWrapperShapeTypes: """Match types that are not matrixes""" if is_gathered: if attribute_type.array_depth == 0: if attribute_type.tuple_count == 1: shape = (2,) else: shape = ((2,), dtype_class.tuple_count) else: if attribute_type.tuple_count == 1: shape = (2, 2) else: shape = ((2, 2), dtype_class.tuple_count) else: if attribute_type.array_depth == 0: if attribute_type.tuple_count == 1: shape = None else: shape = (dtype_class.tuple_count,) else: if attribute_type.tuple_count == 1: shape = (0,) else: shape = (0, dtype_class.tuple_count) return shape for dtype_class in Dtype.__subclasses__(): # This prevents double4 types from matching matrix2d types if attribute_type.is_matrix_type() != dtype_class.is_matrix_type(): continue # Simple marker for an unmatched shape, needed since "None" is a valid match matched_shape = unmatched_shape if attribute_type.is_matrix_type(): # Special case of matrix values where the tuple count is only one axis matched_shape = matrix_shape(dtype_class) elif ( dtype_class.tuple_count == attribute_type.tuple_count and dtype_class.base_type == attribute_type.base_type ): matched_shape = match_simple(dtype_class) if matched_shape != unmatched_shape: if shape is not None: raise AttributeError( f"More than one match found for {attribute_type} - {dtype}/{shape} and {dtype_class()}" ) dtype = dtype_class() shape = matched_shape return (dtype, shape) # ============================================================================================================== def get_dtype_tuple_child(parent_type: Dtype) -> Dtype: """Return the Dtype that is the tuple child of the parent_type. e.g. if you pass in Float3 you should get Float back Args: parent_type: Dtype whose child is to be found Returns: (Dtype) Type corresponding to the parent_type, but with a tuple_count of 1 Raises: AttributeError If the parent_type has no corresponding child """ try: expected_tuple_count = parent_type.matrix_dim except AttributeError: expected_tuple_count = 1 for dtype_class in Dtype.__subclasses__(): if dtype_class.base_type == parent_type.base_type and dtype_class.tuple_count == expected_tuple_count: return dtype_class() raise AttributeError( f"No matching class found with base tyhpe {parent_type.base_type} and tuple count {expected_tuple_count}" ) # ============================================================================================================== class DataWrapper: """Wrapper around typed memory data. This class provides no functionality for manipulating the data, only for inspecting it and extracting it for other code to manipulate it. e.g. you could extract CPU data as a numpy array and modify values, though you cannot change its size, or you could extract the pointer to the GPU data for passing in to a GPU-aware package like TensorFlow. External functions will perform these conversions. Attributes: memory: Address of the data in the memory space dtype: Data type information for the individual data elements shape: Array shape of the memory device: Device on which the memory is located. gpu_ptr_kind: Arrays of GPU pointers can either be on the GPU or the CPU, depending on where you want to reference them. If the shape is an array and device is cuda then this tells where 'memory' lives """ def __init__( self, memory: int, dtype: Dtype, shape: DataWrapperShapeTypes, device: Device, gpu_ptr_kind: og.PtrToPtrKind = og.PtrToPtrKind.NA, ): """Sets up the wrapper for the passed-in data. Args: memory: Integer containing the memory address of the data dtype: Data type of the referenced data shape: Array shape of the referenced data device: Device on which the memory is located. gpu_ptr_kind: Location of pointers that point to GPU arrays """ self.memory = memory self.dtype = dtype self.shape = shape self.device = device self.gpu_ptr_kind = gpu_ptr_kind # Check to see if the shape is in a valid configuration is_tuple = self.dtype.tuple_count > 1 if shape is None: if is_tuple: raise ValueError("Tuple type must at least have the tuple count in the shape") return if not isinstance(shape, tuple): raise ValueError("Shape must be a tuple type matching the array configuration of the data type") first_dimension, *other_dimensions = shape # When the first dimension is a tuple it is a gathered shape if isinstance(first_dimension, tuple): if is_tuple: if not other_dimensions: raise ValueError( f"Gathered arrays of tuple values needs the tuple count in the shape - not {shape}" ) if dtype.is_matrix_type() and len(other_dimensions) != 2: raise ValueError( f"Gathered arrays of matrix values need only row,column dimensions in the shape - not {shape}" ) if not dtype.is_matrix_type() and len(other_dimensions) > 1: raise ValueError( f"Gathered arrays of tuple values can only have one tuple dimension in the shape - not {shape}" ) else: if other_dimensions: raise ValueError(f"Gathered arrays of simple values can only have one dimension - not {shape}") elif not isinstance(first_dimension, int): raise ValueError( f"First member of shape tuple must be an array count or a gathered array size tuple - not {shape}" ) elif is_tuple: # Legal tuple shapes are (N) for simple tuples, (N, M) for tuple arrays and matrixes, # and (N, M, M) for matrix arrays if dtype.is_matrix_type(): matrix_type_invalid = False if len(other_dimensions) == 1: if (other_dimensions[-1] != first_dimension) or (first_dimension != dtype.matrix_dim): matrix_type_invalid = True elif len(other_dimensions) == 2: if (other_dimensions[-1] != other_dimensions[-2]) or (other_dimensions[-2] != dtype.matrix_dim): matrix_type_invalid = True else: matrix_type_invalid = True if matrix_type_invalid: raise ValueError( f"Matrix shape can only be (N, N) or (M, N, N) where N is the matrix dimension - not {shape}" ) else: tuple_type_invalid = False if len(other_dimensions) == 1: tuple_type_invalid = other_dimensions[-1] != dtype.tuple_count elif not other_dimensions: tuple_type_invalid = first_dimension != dtype.tuple_count else: tuple_type_invalid = True if tuple_type_invalid: raise ValueError(f"Tuple shape can only be (N) or (M, N) where N is the tuple count - not {shape}") else: if other_dimensions: raise ValueError(f"Simple value shape can only be None or (N) - not {shape}") def __delitem__(self, index: int): """Raises ValueError as deleting items from the data is not allowed""" raise ValueError("This is just a memory wrapper. Deletion of array elements is not permitted here") def __setitem__(self, index: int, new_item: DataWrapper): """Raises ValueError as settings items on the data is not allowed""" raise ValueError("This is just a memory wrapper. Setting of array elements is not permitted here") def __getitem__(self, index: int) -> DataWrapper: """Returns the data referenced at the index. This means different things depending on the shape of the object. For gathered objects the index is taken to mean "the Nth gathered value", so the result will point to ungathered data. For ungathered objects the index is taken to mean "the Nth child of the first shape depth". For an array it will be the array element, for tuples it will be the tuple element, and for matrices it will be the row first, the column second. Args: index: Index within the array of the item to find Raises: ValueError: If the object is not an array type or the index is out of range """ if isinstance(index, slice): raise ValueError("Slice indexing is not yet supported") if self.shape is None: raise ValueError("Cannot take the index of a non-array type") first_shape, *new_shape = self.shape new_shape = tuple(new_shape) # Gathered items are easier to handle as the underlying types don't change. An index into a gathered # array is the Nth array in the gathering. if isinstance(first_shape, tuple): if len(first_shape) == 1: if not 0 <= index < first_shape[0]: raise ValueError(f"DataWrapper gathered element index {index} must be in [0, {first_shape[0]}]") # Gathered array of simple values new_memory = self.memory + self.dtype.size * index else: if not 0 <= index < len(first_shape): raise ValueError(f"DataWrapper gathered element index {index} must be in [0, {len(first_shape)}]") # Gathered array of array values new_memory = self.memory + sum(size * self.dtype.size for size in first_shape[0:index]) new_shape = (first_shape[index], *new_shape) return DataWrapper(new_memory, self.dtype, new_shape or None, self.device, self.gpu_ptr_kind) # Single shape dimension - a simple tuple, or a simple array (can't be a matrix at this point) if not new_shape: if not 0 <= index < first_shape: raise ValueError(f"DataWrapper element index {index} must be in [0, {first_shape}]") if self.dtype.tuple_count > 1: new_dtype = get_dtype_tuple_child(self.dtype) new_memory = self.memory + index * (self.dtype.size / self.dtype.tuple_count) else: new_dtype = self.dtype new_memory = self.memory + index * self.dtype.size # Single matrix elif self.dtype.is_matrix_type() and len(new_shape) == 1: if not 0 <= index < first_shape: raise ValueError(f"DataWrapper matrix row index {index} must be in [0, {first_shape}]") new_dtype = get_dtype_tuple_child(self.dtype) new_memory = self.memory + index * new_dtype.size # Array of something # TODO: A CPU pointer to a GPU array will not return the right thing here but there is no way to prevent it # with the current type configuration. else: if self.dtype.tuple_count == 1: raise ValueError(f"Array depth of simple type is limited to 1 - started from {self.shape}") if not 0 <= index < first_shape: raise ValueError(f"DataWrapper array index {index} must be in [0, {first_shape}]") new_dtype = self.dtype if self.gpu_ptr_kind == og.PtrToPtrKind.GPU: new_memory = self.memory + index * self.dtype.size else: ptr_type = ctypes.POINTER(ctypes.c_size_t) ptr = ctypes.cast(self.memory, ptr_type) new_memory = ptr.contents.value + index * self.dtype.size return DataWrapper(new_memory, new_dtype, new_shape or None, self.device, self.gpu_ptr_kind) def is_array(self) -> bool: """Returns True iff the data shape indicates that it is an arbitrary sized array of some kind""" first_shape, *new_shape = self.shape new_shape = tuple(new_shape) # Tuples have a shape like ((N,),), tuple arrays are like ((N, M),) if isinstance(first_shape, tuple): return len(first_shape) > 1 # Simple arrays have a shape like (N,) if not new_shape: return self.dtype.tuple_count == 1 # Matrix values have a shape like (N, M), matrix arrays are like (N, M, K) if self.dtype.is_matrix_type() and len(new_shape) == 1: return False # Everything that is not an array has been eliminated return True def __str__(self) -> str: """Representation of the wrapper showing the contents""" gpu_type = "GPU" if (self.gpu_ptr_kind == og.PtrToPtrKind.GPU) and self.is_array() else "CPU" return f"{gpu_type} Memory: {hex(self.memory)}, type {self.dtype}, shape {self.shape}, device {self.device}"
21,839
Python
46.170626
120
0.585878
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/extension.py
"""Extension implementation required by Carbonite extension loader""" # These are used by the extension and require explicit import here import importlib import json import time from contextlib import suppress from pathlib import Path from typing import List, Set, Tuple, Union import carb import carb.profiler import omni.ext import omni.graph.core as og import omni.graph.tools as ogt from omni.kit.app import get_app_interface from omni.kit.commands import unregister_module_commands from pxr import Sdf from .v1_5_0.update_file_format import ( cb_update_to_include_schema, migrate_attribute_custom_data, remove_global_compute_graph, ) # ============================================================================================================== def register_categories(): """If the Kit location is available then use it to find category configuration files and register their contents""" try: # noqa: PLR1702 config_dir = Path(carb.tokens.get_tokens_interface().resolve("${kit}")) / "dev" / "ogn" / "config" if config_dir.is_dir(): node_categories = og.get_node_categories_interface() for config_file in config_dir.iterdir(): try: with open(config_file, "r", encoding="utf-8") as json_fd: configuration = json.load(json_fd) if "categoryDefinitions" in configuration: for category_name, category_description in configuration["categoryDefinitions"].items(): if category_name[0] == "$": continue node_categories.define_category(category_name, category_description) except json.decoder.JSONDecodeError: pass except Exception as error: # noqa: PLW0703 carb.log_warn(f"Could not find the OmniGraph configuration directory - {error}") # ============================================================================================================== class _PublicExtension(omni.ext.IExt): """Mandatory extension instantiation required by the Carbonite extension handler""" # Globally accessible timing information tracking how long it takes to register and deregister nodes in an extension REGISTRATION_TIMING = {} DEREGISTRATION_TIMING = {} def __init__(self, *args, **kwargs): self.__extension_disabled_hook = None self.__extension_enabled_hook = None self.__interface = None self.__migrate_attribute_custom_data_handle = None self.__module_registrations = {} self.__pre_del_prim_cb = None self.__pre_del_prim_cb = None self.__remove_global_graph_handle = None self.__schema_upgrade_handle = None def on_after_ext_enabled(self, ext_id: str, *_): ogt.dbg_reg("Checking for Python nodes in {}", ext_id) start_registration = time.perf_counter_ns() carb.profiler.begin(1, f"OmniGraph.PythonNode.Registration.{ext_id}") manager = get_app_interface().get_extension_manager() with suppress(KeyError): for module_info in manager.get_extension_dict(ext_id).get_dict()["python"]["module"]: module_name = module_info["name"] with suppress(ModuleNotFoundError): ogn_module = importlib.import_module(f"{module_name}.ogn") self.__module_registrations.setdefault(ext_id, []).append( og.PythonNodeRegistration(ogn_module, module_name) ) ogt.dbg_reg(" -> Registered nodes from module {}", module_name) carb.profiler.end(1) end_registration = time.perf_counter_ns() self.REGISTRATION_TIMING[ext_id] = end_registration - start_registration def on_before_ext_disabled(self, ext_id: str, *_): start_registration = time.perf_counter_ns() carb.profiler.begin(1, f"OmniGraph.PythonNode.Deregistration.{ext_id}") with suppress(KeyError): del self.__module_registrations[ext_id] ogt.dbg_reg("Deregistered Python nodes in {}", ext_id) carb.profiler.end(1) end_registration = time.perf_counter_ns() self.DEREGISTRATION_TIMING[ext_id] = end_registration - start_registration # -------------------------------------------------------------------------------------------------------------- # begin-file-format-update def on_startup(self): """Set up initial conditions for the Python part of the extension""" self.__module_registrations = {} self.__interface = og.acquire_interface() og.register_python_node() hooks = omni.kit.app.get_app_interface().get_extension_manager().get_hooks() self.__extension_enabled_hook = hooks.create_extension_state_change_hook( self.on_after_ext_enabled, omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE ) assert self.__extension_enabled_hook self.__extension_disabled_hook = hooks.create_extension_state_change_hook( self.on_before_ext_disabled, omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_DISABLE ) assert self.__extension_disabled_hook self.__remove_global_graph_handle = og.register_pre_load_file_format_upgrade_callback( remove_global_compute_graph ) self.__migrate_attribute_custom_data_handle = og.register_pre_load_file_format_upgrade_callback( migrate_attribute_custom_data ) self.__schema_upgrade_handle = og.register_pre_load_file_format_upgrade_callback(cb_update_to_include_schema) self.__pre_del_prim_cb = omni.kit.commands.register_callback( "DeletePrimsCommand", omni.kit.commands.PRE_DO_CALLBACK, self.__on_before_del_prim ) # Categories are in configuration files so they have to be added to OmniGraph here register_categories() # -------------------------------------------------------------------------------------------------------------- def on_shutdown(self): """Shutting down this part of the extension prepares it for hot reload""" omni.kit.commands.unregister_callback(self.__pre_del_prim_cb) self.__pre_del_prim_cb = None og.on_shutdown() og.release_interface(self.__interface) unregister_module_commands(og.cmds) og.cmds = None self.__extension_enabled_hook = None self.__extension_disabled_hook = None if self.__module_registrations: carb.log_warn(f"Shutting down OmniGraph with modules still registered - {self.__module_registrations}") og.deregister_pre_load_file_format_upgrade_callback(self.__remove_global_graph_handle) self.__remove_global_graph_handle = None og.deregister_pre_load_file_format_upgrade_callback(self.__migrate_attribute_custom_data_handle) self.__migrate_attribute_custom_data_handle = None og.deregister_pre_load_file_format_upgrade_callback(self.__schema_upgrade_handle) self.__schema_upgrade_handle = None # end-file-format-update # -------------------------------------------------------------------------------------------------------------- def __on_before_del_prim(self, info): # Get the command's 'paths' argument. paths: List[Union[str, Sdf.Path]] = info.get("paths", None) if not paths: return # Remove duplicates. paths = set(paths) # Find all the OG nodes which will be removed. nodes_being_removed: Set[og.Node] = set() while paths: path = paths.pop() graph = og.Controller.graph(path) if graph: # Add the subgraph's nodes. for node in graph.get_nodes(): paths.add(node.get_prim_path()) else: with suppress(og.OmniGraphValueError): node = og.Controller.node(path) nodes_being_removed.add(node) # Find any connections where the source node is being deleted # but the destination isn't. Those will result in broken connections # which the OG core won't be able to restore if the DeletePrims # command is undone. To work around that we'll add an undo task # to the command's undo block. conns_to_undo: List[Tuple[str, str]] = [] for node in nodes_being_removed: for attr in node.get_attributes(): for dest_attr in attr.get_downstream_connections(): dest_node = dest_attr.get_node() if dest_node not in nodes_being_removed: # Attribute.get_path() does not return a valid path for bundle outputs so # we must build the path from its parts. src_path = node.get_prim_path() + "." + attr.get_name() dest_path = dest_node.get_prim_path() + "." + dest_attr.get_name() conns_to_undo.append((src_path, dest_path)) if conns_to_undo: omni.kit.commands.execute("_OGRestoreConnectionsOnUndo", connections=conns_to_undo)
9,281
Python
47.093264
120
0.588514
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/instancing_commands.py
from typing import List, Optional import omni from omni.kit.usd_undo import UsdLayerUndo from pxr import OmniGraphSchema, OmniGraphSchemaTools, Sdf class ApplyOmniGraphAPICommand(omni.kit.commands.Command): def __init__( self, layer: Sdf.Layer = None, paths: Optional[List[Sdf.Path]] = None, graph_path: Sdf.Path = Sdf.Path.emptyPath ): self._usd_undo = None self._layer = layer self._paths = paths if paths is not None else [] self._graph_path = graph_path def do(self): stage = omni.usd.get_context().get_stage() if self._layer is None: self._layer = stage.GetEditTarget().GetLayer() self._usd_undo = UsdLayerUndo(self._layer) for path in self._paths: if not stage.GetPrimAtPath(path).HasAPI(OmniGraphSchema.OmniGraphAPI): self._usd_undo.reserve(path) OmniGraphSchemaTools.applyOmniGraphAPI(stage, path, self._graph_path) def undo(self): if self._usd_undo is not None: self._usd_undo.undo() class RemoveOmniGraphAPICommand(omni.kit.commands.Command): def __init__(self, layer: Sdf.Layer = None, paths: List[Sdf.Path] = None): self._usd_undo = None self._layer = layer self._paths = paths if paths is not None else [] def do(self): stage = omni.usd.get_context().get_stage() if self._layer is None: self._layer = stage.GetEditTarget().GetLayer() self._usd_undo = UsdLayerUndo(self._layer) for path in self._paths: if stage.GetPrimAtPath(path).HasAPI(OmniGraphSchema.OmniGraphAPI): self._usd_undo.reserve(path) OmniGraphSchemaTools.removeOmniGraphAPI(stage, path) def undo(self): if self._usd_undo is not None: self._usd_undo.undo() omni.kit.commands.register(ApplyOmniGraphAPICommand) omni.kit.commands.register(RemoveOmniGraphAPICommand)
1,959
Python
34.636363
120
0.639102
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/register_ogn_nodes.py
""" Runtime helpers to make registration and regeneration of OGN Python files automatic """ import os import re from importlib import import_module from pathlib import Path from typing import Callable, Dict, List, Tuple import carb import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn from .settings import Settings from .versions import ( Compatibility, check_version_compatibility, get_generator_extension_version, get_target_extension_version, ) # ================================================================================ def find_import_locations(path_requesting_registration: str, import_path: str) -> str: """Returns the root directory of the import path Args: path_requesting_registration: File/directory that called this function, assumed to be in the generated directory import_path: Python module import path for the extension Returns: (import_root, generated_directory) import_root: Directory at which the import_path is rooted generated_directory: Directory containing the generated files Raises: ValueError: If the import_path was not found in the generated directory path Example: find_import_locations("C:/a/b/c/d.py", import_path="b.c") ("C:/a", "C:/a/b/c") """ if os.path.isdir(path_requesting_registration): generated_directory = os.path.realpath(path_requesting_registration) else: generated_directory = os.path.dirname(os.path.realpath(path_requesting_registration)) canonical_directory = generated_directory.replace("\\", "/") import_directory = import_path.replace(".", "/") found_import = re.match(f"(.*)/{import_directory}/.*", canonical_directory) if found_import is None: found_import = re.match(f"(.*)/{import_directory}$", canonical_directory) if found_import: return (found_import.group(1), canonical_directory) raise ValueError(f"Import path {import_directory} not found in generated directory {canonical_directory}") # ================================================================================ def regenerate_files( ogn_file_path: str, database_file_path: str, import_path: str ) -> Tuple[bool, bool, bool, bool, bool]: """Run the generation code to generate a new Python database file and test file from a (modified) .ogn file Args: ogn_file_path: Path to the .ogn file to use for regeneration database_file_path: Path to the XXDatabase.py file being generated import_path: Python import path of the file requesting the registration (e.g. omni.graph.core) Returns: (generated_python, generated_test, generated_cpp, generated_documentation, generated_usd): generated_python: Did a Python interface file get generated? generated_tests: Did a Test file get generated? generated_cpp: Did a node header file get generated? generated_documentation: Did a docs file get generated? generated_usd: Did a USD template file get generated? """ _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Generating database on {} from {}", database_file_path, ogn_file_path) generated_python = False generated_tests = False generated_cpp = False generated_documentation = False generated_usd = False try: # If the Kit location is available then use it to find configuration files try: config_dir = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent.joinpath( "_build", "ogn", "config" ) except AttributeError: config_dir = None # Parse the .ogn file with open(ogn_file_path, "r", encoding="utf-8") as ogn_fd: node_interface_wrapper = ogn.NodeInterfaceWrapper( ogn_fd, extension=import_path, config_directory=str(config_dir) ) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Generated a wrapper {}", node_interface_wrapper) try: all_supported = True node_interface_wrapper.check_support() except ogn.UnimplementedError: all_supported = False # Set up the configuration to write into the correct directories base_name, _ = os.path.splitext(os.path.basename(ogn_file_path)) configuration = ogn.GeneratorConfiguration( ogn_file_path, node_interface_wrapper.node_interface, import_path, import_path, base_name, os.path.dirname(database_file_path), ogt.OGN_REG_DEBUG, Settings.generator_settings(), ) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg("Generation configuration\n{}", configuration) # Generate the Python NODEDatabase.py file if this .ogn description allows it if node_interface_wrapper.can_generate("python"): _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " Generating the Python in {}", configuration.destination_directory ) ogn.generate_python(configuration) generated_python = True else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" ...Skipping -> File cannot generate Python database") # Generate the Python TestNODE.py file if this .ogn description allows it if node_interface_wrapper.can_generate("tests"): configuration.destination_directory = os.path.join(os.path.dirname(database_file_path), "tests") _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " Generating the tests in {}", configuration.destination_directory ) ogn.generate_tests(configuration) generated_tests = True else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" ...Skipping -> File cannot generate tests") # Generate the C++ interface file NODEDatabase.h if this .ogn description allows it if node_interface_wrapper.can_generate("c++"): configuration.destination_directory = os.path.join(os.path.dirname(database_file_path), "include") _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " Generating the C++ header file in {}", configuration.destination_directory ) ogn.generate_cpp(configuration, all_supported) generated_cpp = True else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" ...Skipping -> File cannot generate C++ interface file") # Generate the documentation file NODE.rst if this .ogn description allows it if node_interface_wrapper.can_generate("docs"): configuration.destination_directory = os.path.join(os.path.dirname(database_file_path), "docs") _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " Generating the documentation file in {}", configuration.destination_directory ) ogn.generate_documentation(configuration) generated_documentation = True else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" ...Skipping -> File cannot generate documentation file") # Generate the USD template file NODE.usda if this .ogn description allows it if node_interface_wrapper.can_generate("usd"): configuration.destination_directory = os.path.join(os.path.dirname(database_file_path), "tests", "usd") _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " Generating the USD template file in {}", configuration.destination_directory ) ogn.generate_usd(configuration) generated_usd = True else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" ...Skipping -> File cannot generate USD template file") except ogn.ParseError as error: carb.log_error(f"Node parsing of {ogn_file_path} failed with error {error}") except ogn.NodeGenerationError as error: carb.log_error(f"Node generation on {ogn_file_path} failed with error {error}") return (generated_python, generated_tests, generated_cpp, generated_documentation, generated_usd) # ================================================================================ def find_ogn_and_python_interfaces(import_directory: str) -> Tuple[Dict[str, str], List[str]]: """Scan the directory for generated database files and directories containing .ogn files Args: import_directory: Root directory to scan Returns: (database_files, ogn_directories): database_files: Dictionary of file:path to Python Database files generated from .ogn files ogn_directories: List of directories that may contain .ogn files to use for generation """ _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Scanning the import directory for .ogn and generated Python files") database_files = {} ogn_directories = [] # If the "nodes" directory was found in the ogn/ tree then it won't have to be scanned from its # normal location one level up. (The latter only being necessary when Windows permissions causes # failure of creation of the symlink to it.) found_nodes_link = False for ogn_file in os.listdir(import_directory): ogn_path = os.path.join(import_directory, ogn_file) if os.path.isfile(ogn_path): if ogn_file.endswith("Database.py"): _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Found database file {}", ogn_path) database_files[ogn_file] = ogn_path elif ogn_file == "tests": _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Found generated tests/ subdirectory") else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Found uninteresting file {}", ogn_path) elif os.path.isdir(ogn_path): if ogn_file == "tests": _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Found generated tests/ subdirectory") elif ogn_file == "__pycache__": _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Skipping __pycache__ subdirectory") else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Adding potential OGN directory {}", ogn_path) if ogn_file == "nodes": found_nodes_link = True ogn_directories.append(ogn_path) else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Skipping as neither file nor directory {}", ogn_path) # If the user is not able to create symlinks then the nodes would live above the import directory # in a directory named "nodes" (possibly with other directories below it) if not found_nodes_link: unlinked_nodes_directory = os.path.normpath(os.path.join(import_directory, "..", "nodes")) if os.path.isdir(unlinked_nodes_directory): _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " Adding scan of unlinked node directory {}", unlinked_nodes_directory ) ogn_directories.append(unlinked_nodes_directory) return (database_files, ogn_directories) # ================================================================================ def scan_directories_for_ogn_files( ogn_directories: List[str], import_root: str ) -> Tuple[Dict[str, str], List[Tuple[str, str]]]: """Scan a list of directories to find all .ogn files below them Args: ogn_directories: List of directory paths to scan import_root: Path to the root directory for Python imports (nodes will import relative to this path) Returns: (ogn_files, node_files): ogn_files: {file_name: path_name} for all .ogn files below any of the given directories node_files: List of (node_name, import_to_node) to Python node implementation files node_name: Name of the node (base file name with the extension stripped) import_to_node: Python import path relative to the import to this directory """ _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Scanning for .ogn files in {}", import_root) ogn_files = {} node_files = {} for ogn_directory in ogn_directories: # noqa: PLR1702 _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Checking OGN directory {}", ogn_directory) for root, _, files in os.walk(ogn_directory, followlinks=True): for file in files: if file.endswith(".ogn"): _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Found OGN file {}/{}", root, file) ogn_files[file] = os.path.join(root, file) # Check to see if there is also an implementation file in this same directory, the only # configuration that is automatically recognized. implementation_file = file.replace(".ogn", ".py") if os.path.isfile(os.path.join(root, implementation_file)): try: import_to_node = root.replace("\\", ".").replace("/", ".")[len(import_root) + 1 :] node_name = f"{os.path.splitext(implementation_file)[0]}" node_files[node_name] = import_to_node _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " Added file {} at {}", node_name, import_to_node ) except KeyError as error: carb.log_error( f"Could not find Python import root from {root}/{implementation_file} - {error}" ) return (ogn_files, node_files) # ================================================================================ def scan_for_generated_tests(test_directory: str) -> List[str]: """Scan a directory for files that were automatically generated as tests for .ogn files Args: test_directory: Root path of the directory containing tests Returns: List of test file root names, for use in import statements (test classes have the same name as the file) """ test_node_names = [] for file in os.listdir(test_directory): if file.startswith("Test") and file.endswith(".py"): node_name = f"{os.path.splitext(file)[0]}" test_node_names.append(node_name) return test_node_names # ================================================================================ def files_needing_regeneration( ogn_files: Dict[str, str], database_files: Dict[str, str], import_directory: str ) -> List[Tuple[str, str]]: """Look for Python Database files that are out of date compared to their corresponding .ogn file Args: ogn_files: FILE:PATH for all .ogn files found in the current directory database_files: FILE:PATH for all generated Python Database files found in the current directory import_directory: Root path of this extensions's Python import Returns: List of (ogn_path, database_path, exists) with all files that need regenerating ogn_path: Full path to the .ogn file to use for generation database_path: Destination path of the generated Python Database file exists: The destination file exists, it is just out of date """ _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Checking if {} .ogn files need regenerating", len(ogn_files)) to_be_generated = [] for ogn_file, ogn_path in ogn_files.items(): database_file = ogn_file.replace(".ogn", "Database.py") database_path = os.path.join(import_directory, database_file) regenerate_node = False file_exists = database_file in database_files if file_exists: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Checking status of {} against {}", database_file, ogn_file) database_modified_time = os.stat(database_files[database_file]).st_mtime ogn_modified_time = os.stat(ogn_path).st_mtime if database_modified_time >= ogn_modified_time: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" -> {} Up to date", ogn_file) else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" -> {} Out of date, regenerating", ogn_file) regenerate_node = True else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" {} No database file, regenerating", ogn_file) regenerate_node = True if regenerate_node: to_be_generated.append((ogn_path, database_path, file_exists)) return to_be_generated # ================================================================================ def register_existing_python_nodes( python_nodes: Dict[str, str], import_path: str, generated_directory: str ) -> List[Callable]: """Register all of the existing Python nodes with OmniGraph Args: python_nodes: Dictionary of node_name:import_root for all Python node files found node_name: Name of the node, which is the file name with the extension stripped import_root: Import path of the node within this extension import_path: Absolute Python import path to the directory above the generated ogn/ directory generated_directory: Location of the files generated from the .ogn files in this extension Returns: List of methods that will deregister all of the nodes that were registered """ _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( "Registering python nodes from {} to generated directory {}", import_path, generated_directory ) deregistration_methods = [] for (node_name, import_root) in python_nodes.items(): _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Registering python node {} from {}", node_name, import_root) try: try: node_module = import_module(f".{node_name}", import_root) except Exception as error: raise ogn.CarbLogError(f"Failed to import Python OmniGraph node {node_name}.py - {error}") try: node_class = getattr(node_module, node_name) except AttributeError as error: raise ogn.CarbLogError( f"Failed to import Python OmniGraph node {node_name}.py -" " file does not contain a class of the same name" ) from error try: database_module_name = f"{node_name}Database" database_module = import_module(f".ogn.{database_module_name}", import_path) except ModuleNotFoundError as error: raise ogn.DebugError( f" Dynamic registration of Python OmniGraph node {node_name} failed, probably no .ogn file" ) from error try: database_class = getattr(database_module, database_module_name) except AttributeError as error: raise ogn.CarbLogError( f"Python OGN interface node {database_module_name}.py has no node class of the same name" ) from error try: # The defaults are the last version prior to the versions being embedded in the generated code generator_version = getattr(database_class, "GENERATOR_VERSION", (1, 1, 1)) target_version = getattr(database_class, "TARGET_VERSION", (2, 2, 0)) compatibility = check_version_compatibility(generator_version, target_version) if compatibility == Compatibility.FullyCompatible: # noqa: SIM114 because code will be changing database_class.register(node_class) deregister_method = getattr(database_class, "deregister", None) if deregister_method is not None: deregistration_methods.append(deregister_method) elif compatibility == Compatibility.MajorVersionCompatible: # TODO: In order to regenerate we must be able to find the node from which this came. # As that's currently not possible this will just do normal registration until it is. # carb.log_warn( # f"Older version of Python node {node_class.__name__} will regenerate the node database\n" # f" Generator used {generator_version}, this one is {get_generator_extension_version()}\n" # f" Target was {target_version}, this one is {get_target_extension_version()}\n" # ) database_class.register(node_class) deregister_method = getattr(database_class, "deregister", None) if deregister_method is not None: deregistration_methods.append(deregister_method) elif compatibility == Compatibility.Incompatible: carb.log_error( f"Incompatible versions of Python node {node_class.__name__} cannot be registered\n" f" Generator used {generator_version}, this one is {get_generator_extension_version()}\n" f" Target was {target_version}, this one is {get_target_extension_version()}\n" ) except AttributeError as error: raise ogn.CarbLogError(f"File structure with Python OGN node is not compatible - {error}") # Secondary exception handling to allow simple loop continuation with reporting except ogn.CarbLogError as error: carb.log_error(str(error)) except Exception as error: # noqa: PLW0703 _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(error) carb.log_error(str(error)) return deregistration_methods # ================================================================================ @ogt.deprecated_function("Internal use only") def generate_automatic_test_imports(test_directory: str): """ Scan the test_directory for test cases and (re)generate the __init__.py file for automatic test registration. Args: test_directory: Path to the test folder. Will be created if it doesn't exist """ _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Testing for the existence of generated test files") ogn.generate_test_imports(Path(test_directory), write_file=True) # ================================================================================ def register_ogn_nodes(file_requesting_registration: str, import_path: str) -> List[Callable]: """ Scan the generated ogn/ subdirectory for files that look like nodes and import them to force registration Also regenerates the tests/__init__.py file for automatic test registration. Args: file_requesting_registration: Path to the file in the .ogn directory tree import_path: Python import path of the file requesting the registration (e.g. omni.graph.core) Returns: List of methods to deregister all of the node types (to save for extension shutdown) """ _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( "Registering OGN nodes in directory {} to path {}", file_requesting_registration, import_path ) # For converting full path names to module import specifications we need the location the import path starts (import_root, generated_directory) = find_import_locations(file_requesting_registration, import_path) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Import root {}, generated directory {}", import_root, generated_directory) # The top level contains the generated database file, __init__.py, and tests/ directory, as well as # links or subdirectories containing .ogn implementations. Gather up the database and .ogn subdirectories. (database_files, ogn_directories) = find_ogn_and_python_interfaces(generated_directory) # Find .ogn files to check for being up to date (ogn_files, node_files) = scan_directories_for_ogn_files(ogn_directories, import_root) # Check to see if the Database.py file corresponding to a .ogn file needs updating skip_file_generation = ogt.is_unwritable(generated_directory) if skip_file_generation: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg("Skipping generation in unwritable directory {}", generated_directory) else: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg("Walking the files needing regeneration in {}", generated_directory) for (ogn_path, database_path, exists) in files_needing_regeneration( ogn_files, database_files, generated_directory ): try: (new_python_file, new_test_file, new_cpp_file, new_docs_file, new_usd_file) = regenerate_files( ogn_path, database_path, import_path ) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Generated python file = {}", new_python_file) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Generated test file = {}", new_test_file) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Generated C++ file = {}", new_cpp_file) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Generated docs file = {}", new_docs_file) _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg(" Generated USD file = {}", new_usd_file) except (ogn.NodeGenerationError, PermissionError) as error: _ = ogt.OGN_REG_DEBUG and ogt.dbg_reg( " File could not be written so the existing one will be used - {}", error ) if not exists: carb.log_error(f"Generated files could not be written. Functionality may be missing - {error}") skip_file_generation = True # Take the list of existing nodes and register all Python nodes with OmniGraph deregistration_list = register_existing_python_nodes(node_files, import_path, generated_directory) if not skip_file_generation: # The tests/ subdirectory is automatically scanned when the module appears in extension.toml. # By importing all generated tests classes from there they will be automatically registered. test_directory = Path(generated_directory) / "tests" ogn.generate_test_imports(Path(test_directory), write_file=True) return deregistration_list
26,324
Python
50.516634
120
0.609216
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/topology_commands.py
# noqa: PLC0302 """ Commands that modify the topology of the OmniGraph """ import asyncio from contextlib import suppress from typing import Any, List, Optional, Tuple, Union import carb import omni.graph.core as og import omni.kit import omni.kit.commands import omni.usd from .object_lookup import ObjectLookup from .typing import Attribute_t, AttributeType_t, ExtendedAttribute_t, Node_t # ============================================================================================================== def get_attr_from_string(attr_str, create_node=False, graph=None) -> Optional[og.Attribute]: """ Args: attr_str: The full path of the attribute create_node: If True, and if the node does not exist, create an OG Prim node graph: The relevent graph, or the current graph if None """ # TODO: When og.Settings.PRIM_NODES is removed this function can be replaced by og.Controller.attribute() if og.Settings()(og.Settings.PRIM_NODES): tokens = attr_str.split(".") if len(tokens) != 2: # Output bundles are prims and so have a "/" separator, not a "." tokens = attr_str.rsplit("/", 1) if len(tokens) != 2: return None node_path = tokens[0] attr_name = tokens[1] if not graph: node = og.get_node_by_path(node_path) if node: graph = node.get_graph() while graph.get_parent_graph(): graph = graph.get_parent_graph() else: graph = og.get_current_graph() if create_node: node = graph.create_node(node_path, "omni.graph.core.Prim", True) else: node = graph.get_node(node_path) if not node.is_valid(): return None return node.get_attribute(attr_name) return og.Controller.attribute(attr_str) # ============================================================================================================== class ConnectPrimCommand(omni.kit.commands.Command): """ Connect Prim **Command**. Connects a bundle attribute to a prim. This can be both for bundle purposes or for "pure relationship" type connections where we just want a relationship that points to a prim, without the connotations associated with bundles. Args: attr: The relationship attribute. This can be specified in the form of an attribute from a node, or a string that denotes the path to the attribute in USD. prim_path: The path to the prim that is to be the target of the relationship. is_bundle_connection: Whether this connection represents a bundle connection or just a regular relationship """ def __init__(self, attr: Union[str, og.Attribute], prim_path: str, is_bundle_connection: bool): self._attr_in = attr self._attr = None self._prim_path = prim_path self._is_bundle_connection = is_bundle_connection self._modify_usd = True self._did_doit = False def do(self): if isinstance(self._attr_in, str): if len(self._attr_in.split(".")) != 2: carb.log_error("Malformed attribute string in ConnectPrimCommand " + self._attr_in) return self._attr = get_attr_from_string(self._attr_in, create_node=False) if self._attr is None or not self._attr.is_valid(): carb.log_error("Unable to retrieve attribute in ConnectPrimCommand " + self._attr_in) return else: self._attr = self._attr_in node = self._attr.get_node() if not node.is_backed_by_usd(): self._modify_usd = False if self._attr.connectPrim(self._prim_path, self._modify_usd, self._is_bundle_connection): self._did_doit = True def undo(self): if self._did_doit: self._attr.disconnectPrim(self._prim_path, self._modify_usd, self._is_bundle_connection) # ============================================================================================================== class DisconnectPrimCommand(omni.kit.commands.Command): """ Disconnect Prim **Command**. Disconnects a bundle attribute from a prim. This can be both for bundle purposes or for "pure relationship" type connections where we just want a relationship that points to a prim, without the connotations associated with bundles. Args: attr: The relationship attribute. This can be specified in the form of an attribute from a node, or a string that denotes the path to the attribute in USD. prim_path: The path to the prim that is to be the target of the relationship. is_bundle_connection: Whether this connection represents a bundle connection or just a regular relationship """ def __init__(self, attr: Union[str, og.Attribute], prim_path: str, is_bundle_connection: bool): self._attr_in = attr self._attr = None self._prim_path = prim_path self._is_bundle_connection = is_bundle_connection self._modify_usd = True self._did_doit = False def do(self): if isinstance(self._attr_in, str): if len(self._attr_in.split(".")) != 2: carb.log_error("Malformed attribute string in DisconnectPrimCommand " + self._attr_in) return self._attr = get_attr_from_string(self._attr_in, create_node=False) if self._attr is None or not self._attr.is_valid(): return else: self._attr = self._attr_in node = self._attr.get_node() if not node.is_backed_by_usd(): self._modify_usd = False if self._attr.disconnectPrim(self._prim_path, self._modify_usd, self._is_bundle_connection): self._did_doit = True def undo(self): if self._did_doit: self._attr.connectPrim(self._prim_path, self._modify_usd, self._is_bundle_connection) # ============================================================================================================== class ConnectAttrsCommand(omni.kit.commands.Command): """ Connect Attrs **Command**. Causes two attributes to be connected together in the omnigraph Args: src_attr: The source (upstream) attribute. This can be specified in the form of an attribute from a node, or a string that denotes the path to the attribute in USD. If specified as a string path, if the node happens to be a prim and the prim doesn't yet have prim node created for it, this command will create one automatically. dest_attr: The destination (downstream) attribute. This can be specified in the form of an attribute from a node, or a string that denotes the path to the attribute in USD. If specified as a string path, if the node happens to be a prim and the prim doesn't yet have prim node created for it, this command will create one automatically. modify_usd: Whether to modify the underlying usd stage with this connection connection_type: Whether this is regular connection or something ore fancy, like data only and execution only connections """ def __init__( self, src_attr: Union[str, og.Attribute], dest_attr: Union[str, og.Attribute], modify_usd: bool, connection_type: og.ConnectionType = og.ConnectionType.CONNECTION_TYPE_REGULAR, ): self._src_attr = src_attr self._dst_attr = dest_attr self._modify_usd = modify_usd self._connection_type = connection_type self._did_doit = False self._value = None # --------------------------------------------------------------------------------------------- @staticmethod def _get_from_attr_path(attr_in: Union[og.Attribute, str]) -> Optional[og.Attribute]: """Gets the attribute from the given path and will create the node if it doesn't exist""" # TODO: When og.Settings.PRIM_NODES is removed this function can be replaced by og.Controller.attribute() if isinstance(attr_in, str): attr = get_attr_from_string(attr_in, create_node=False) if not attr: # We were not able to find a valid node / attribute with the given path. Either # this is an invalid path, or it's the path to a prim for which we have not created # a node yet. We'll assume the latter here and try to create a node. If the path is # bogus, the prim node creation will fail. attr = get_attr_from_string(attr_in, create_node=True) if not attr: carb.log_error(f"Malformed attribute string in ConnectAttrsCommand: {attr_in}") return None return attr return attr_in # --------------------------------------------------------------------------------------------- @staticmethod def do_immediate( src_attr: Attribute_t, dest_attr: Attribute_t, modify_usd: bool, connection_type: og.ConnectionType = og.ConnectionType.CONNECTION_TYPE_REGULAR, return_old_value: bool = False, ): _src = src_attr _dst = dest_attr failure_return = (_src, _dst, connection_type, None, False) if return_old_value else False src_attr = ConnectAttrsCommand._get_from_attr_path(_src) dest_attr = ConnectAttrsCommand._get_from_attr_path(_dst) if not src_attr: carb.log_warn(f"Could not connect to unknown src attribute {_src}") return failure_return if not dest_attr: carb.log_warn(f"Could not connect to unknown destination attribute {_dst}") return failure_return src_node = src_attr.get_node() dest_node = dest_attr.get_node() nodes_in_usd = src_node.is_backed_by_usd() and dest_node.is_backed_by_usd() connected = src_attr.is_connected(dest_attr) value = None did_doit = False if not connected: # If there is USD backing for the destination attribute, we prefer to stash the value using the USD # mechanism because it is more robust currently. og.Controller.get() can fail if we haven't loaded the # value into Fabric yet when this connection happens. if nodes_in_usd: with suppress(og.OmniGraphError): usd_attr = og.ObjectLookup.usd_attribute(dest_attr) value = usd_attr.Get() else: value = og.Controller(attribute=dest_attr).get() connection_info = og.ConnectionInfo(dest_attr, connection_type) if src_attr.connectEx(connection_info, modify_usd): did_doit = True if return_old_value: return (src_attr.get_path(), dest_attr.get_path(), connection_type, value, did_doit) return True # --------------------------------------------------------------------------------------------- def do(self): ( self._src_attr, self._dst_attr, self._connection_type, self._value, self._did_doit, ) = ConnectAttrsCommand.do_immediate( self._src_attr, self._dst_attr, self._modify_usd, self._connection_type, return_old_value=True ) # --------------------------------------------------------------------------------------------- def undo(self): if self._did_doit: src_attr = ConnectAttrsCommand._get_from_attr_path(self._src_attr) dst_attr = ConnectAttrsCommand._get_from_attr_path(self._dst_attr) if not src_attr or not dst_attr: return src_attr.disconnect(dst_attr, self._modify_usd) if self._value is not None: src_node = src_attr.get_node() dest_node = dst_attr.get_node() nodes_in_usd = src_node.is_backed_by_usd() and dest_node.is_backed_by_usd() if nodes_in_usd: with suppress(og.OmniGraphError): usd_attr = og.ObjectLookup.usd_attribute(dst_attr) usd_attr.Set(self._value) else: og.Controller(og.Controller.attribute(self._dst_attr)).set(self._value) elif dst_attr.get_type_name() != "bundle": carb.log_warn("No value to restore after undo of ConnectAttrsCommand") self._did_doit = False # ============================================================================================================== class DisconnectAllAttrsCommand(omni.kit.commands.Command): """ Disconnect All Attrs **Command**. Breaks every connection to and from an OmniGraph attribute Args: attr: The attribute to be disconnected modify_usd: Whether to modify the underlying usd stage with this connection """ def __init__(self, attr: og.Attribute, modify_usd: bool): """Remember the command parameters""" self._attr = attr self._modify_usd = modify_usd self._disconnections = [] self._graph = attr.get_node().get_graph() self._undo_cursor = 0 # Current location in the _disconnections of the undo/redo - usually 0 or len()-1 while self._graph.get_parent_graph(): self._graph = self._graph.get_parent_graph() def __remember_disconnection(self, upstream_attribute: og.Attribute, downstream_attribute: og.Attribute): """Add enough information to the disconnection to be able to recreate it in undo. There's no guarantee the same og.Attribute object will exist after a series of operations but the paths will be the same.""" upstream_path = upstream_attribute.get_node().get_prim_path() upstream_name = upstream_attribute.get_name() downstream_path = downstream_attribute.get_node().get_prim_path() downstream_name = downstream_attribute.get_name() self._disconnections.append((upstream_path, upstream_name, downstream_path, downstream_name)) def __get_attributes_from_connection_info( self, connection_info: Tuple[str, str, str, str] ) -> Tuple[og.Attribute, og.Attribute]: """Extract the upstream and downstream attribute from the stored connection information created by the __remember_disconnection function""" upstream_path, upstream_name, downstream_path, downstream_name = connection_info upstream_attribute = self._graph.get_node(upstream_path).get_attribute(upstream_name) downstream_attribute = self._graph.get_node(downstream_path).get_attribute(downstream_name) return (upstream_attribute, downstream_attribute) @staticmethod def do_immediate(attr: og.Attribute, modify_usd: bool) -> bool: """Do the disconnections without remembering the previous connections Args: attr: Attribute to be disconnected modify_usd: Is the USD to be immediately updated after the disconnections? Returns: True if all disconnections succeeded """ status = True upstream_connections = attr.get_upstream_connections() for upstream_attribute in upstream_connections: status = upstream_attribute.disconnect(attr, modify_usd) and status downstream_connections = attr.get_downstream_connections() for downstream_attribute in downstream_connections: status = attr.disconnect(downstream_attribute, modify_usd) and status return status def do(self): """Perform the disconnections, remembering what was disconnected""" if self._attr is not None: upstream_connections = self._attr.get_upstream_connections() for upstream_attribute in upstream_connections: if upstream_attribute.disconnect(self._attr, self._modify_usd): self.__remember_disconnection(upstream_attribute, self._attr) downstream_connections = self._attr.get_downstream_connections() for downstream_attribute in downstream_connections: if self._attr.disconnect(downstream_attribute, self._modify_usd): self.__remember_disconnection(self._attr, downstream_attribute) self._undo_cursor = len(self._disconnections) # Mark the operation as being done once, to avoid accessing potentially stale data self._attr = None else: while self._undo_cursor < len(self._disconnections): upstream_attribute, downstream_attribute = self.__get_attributes_from_connection_info( self._disconnections[self._undo_cursor] ) if upstream_attribute.disconnect(downstream_attribute, self._modify_usd): self._undo_cursor += 1 else: return def undo(self): """Use the remembered disconnections to reestablish the connections""" while self._undo_cursor > 0: self._undo_cursor -= 1 upstream_attribute, downstream_attribute = self.__get_attributes_from_connection_info( self._disconnections[self._undo_cursor] ) if not upstream_attribute.connect(downstream_attribute, self._modify_usd): self._undo_cursor += 1 return # ============================================================================================================== class DisconnectAttrsCommand(omni.kit.commands.Command): """ Disconnect Attrs **Command**. Causes two attrs to be disconnected in OmniGraph Args: src_attr: The source (upstream) attribute dest_attr: The destination (downstream) attribute modify_usd: Whether to modify the underlying usd stage with this connection """ def __init__(self, src_attr: Attribute_t, dest_attr: Attribute_t, modify_usd: bool): self._src_attr = src_attr.get_path() self._dst_attr = dest_attr.get_path() self._modify_usd = modify_usd self._graph = src_attr.get_node().get_graph() self._did_doit = False while self._graph.get_parent_graph(): self._graph = self._graph.get_parent_graph() @staticmethod def do_immediate( src_attr: Attribute_t, dest_attr: Attribute_t, modify_usd: bool, ): connected = src_attr.is_connected(dest_attr) if connected: # since the dest attr is being driven, there is no need to save the state # of the driven attribute. When undo happens, it'll simply be driven again return src_attr.disconnect(dest_attr, modify_usd) carb.log_warn(f"Could not find connection between {src_attr} and {dest_attr} to remove") return False def do(self): src_attr = get_attr_from_string(self._src_attr, create_node=False, graph=self._graph) dst_attr = get_attr_from_string(self._dst_attr, create_node=False, graph=self._graph) if src_attr is None: carb.log_warn(f"Could not find source attribute {self._src_attr} to disconnect from") return if dst_attr is None: carb.log_warn(f"Could not find destination attribute {self._dst_attr} to disconnect from") return self._did_doit = DisconnectAttrsCommand.do_immediate(src_attr, dst_attr, self._modify_usd) def undo(self): if self._did_doit: src_attr = get_attr_from_string(self._src_attr, create_node=False, graph=self._graph) dst_attr = get_attr_from_string(self._dst_attr, create_node=False, graph=self._graph) src_attr.connect(dst_attr, self._modify_usd) self._did_doit = False # ============================================================================================================== class _AttributeFactory: """Helper class shared by the CreateAttr and RemoveAttr commands since both require the ability to create and remove attributes, either in do() or in undo(). It is not assumed that it is safe to hang on to PyBind objects after the __init__ call so lookup strings are saved instead. """ def __raise_error(self, msg: str): """Raise an OmniGraphError populated with common identifying information""" self._failure_pending = True raise og.OmniGraphError(f"Failed to {msg} using attribute {self._attr_name} on node {self._node_path}") def __init__(self, node: Node_t, *args): """Create attribute information either from an actual attribute or from individual create parameters""" # If one or the other operation failed then undo will attempt the opposite, which should just be skipped self._failure_pending = False if len(args) == 1: self._created = True attribute = ObjectLookup.attribute(args[0]) self._node_path = attribute.get_node().get_prim_path() self._attr_name = attribute.get_name() self._attr_type = attribute.get_attribute_data().get_type() self._attr_port = attribute.get_port_type() if attribute.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION: self._attr_extended_type = (attribute.get_extended_type, ",".join(attribute.get_union_types())) else: self._attr_extended_type = attribute.get_extended_type() # TODO: Really we should be getting the default from og.Attribute.getDefault(), but it doesn't exist self._attr_default = None elif len(args) == 5: self._created = False self._node_path = ObjectLookup.node(node).get_prim_path() self._attr_name = args[0] self._attr_type = args[1] self._attr_port = args[2] self._attr_default = args[3] self._attr_extended_type = args[4] else: raise og.OmniGraphError( "Attribute factory requires either an og.Attribute or tuple of name, type, port, default, extended_type" ) def create(self): """Create a new attribute with saved parameters, checking to make sure it hasn't already been created""" if self._failure_pending: self._failure_pending = False return if self._created: self.__raise_error("create dynamic attribute twice") omg_node = ObjectLookup.node(self._node_path) args = [self._attr_name, self._attr_type, self._attr_port, self._attr_default] if isinstance(self._attr_extended_type, Tuple): args.append(self._attr_extended_type[0]) if isinstance(self._attr_extended_type[1], list): args.append(",".join(self._attr_extended_type[1])) else: args.append(self._attr_extended_type) self._created = omg_node.create_attribute(*args) if not self._created: self._failure_pending = True self.__raise_error("add the dynamic attribute to the node") def remove(self) -> bool: """Remove an existing dynamic attribute, raising an exception if it was never created""" if self._failure_pending: self._failure_pending = False return omg_node = ObjectLookup.node(self._node_path) if not self._created or not omg_node.get_attribute_exists(self._attr_name): self.__raise_error("remove unknown dynamic attribute") self._created = not omg_node.remove_attribute(self._attr_name) if self._created: self.__raise_error("remove the dynamic attribute from the node") # ============================================================================================================== class CreateAttrCommand(omni.kit.commands.Command): """ Create Attribute **Command**. Adds a new dynamic attribute to a node. Args: node: Node on which to create the attribute (path or og.Node) attr_name: Name of the new attribute, either with or without the port namespace attr_type: Type of the new attribute, as an OGN type string or og.Type attr_port: Port type of the new attribute, default is og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT attr_default: The initial value to set on the attribute, default is None, meaning the type's default is used attr_extended_type: The extended type of the attribute, default is og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR. If the extended type is og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION then this parameter will be a 2-tuple with the second element being a list or comma-separated string of union types If there is any problem with the do/undo of the attribute creation a warning is issued and the command fails. """ def __init__( self, node: Node_t, attr_name: str, attr_type: AttributeType_t, attr_port: Optional[og.AttributePortType] = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, attr_default: Optional[Any] = None, attr_extended_type: Optional[ExtendedAttribute_t] = og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, ): """The information in here is only meant to survive until the do() function is called. After that, the do() function will store information necessary to undo and redo the operations.""" super().__init__() self._factory = _AttributeFactory( node, attr_name, ObjectLookup.attribute_type(attr_type), attr_port, attr_default, attr_extended_type ) @staticmethod def do_immediate( node: Node_t, attr_name: str, attr_type: AttributeType_t, attr_port: og.AttributePortType = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, attr_default: Any = None, attr_extended_type: ExtendedAttribute_t = og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, ): """Removes the attribute, raising og.OmniGraphError if it fails""" attr_type = ObjectLookup.attribute_type(attr_type) _AttributeFactory(node, attr_name, attr_type, attr_port, attr_default, attr_extended_type).create() def do(self): """Create the dynamic attribute with the specified parameters, raising OmniGraphError if the create failed.""" try: self._factory.create() except og.OmniGraphError as error: carb.log_warn(str(error)) return False return True def undo(self): """Remove the created attribute, raising OmniGraphError if the removal failed""" try: self._factory.remove() except og.OmniGraphError as error: carb.log_warn(str(error)) return False return True # ============================================================================================================== class RemoveAttrCommand(omni.kit.commands.Command): """ Remove Attribute **Command**. Removes an existing dynamic attribute from a node. Args: attribute: Name of the attribute to be removed If there is any problem with the do/undo of the attribute removal a warning is issue and the command fails """ def __init__( self, attribute: og.Attribute, ): """The information in here is only meant to survive until the do() function is called. After that, the do() function will store information necessary to undo and redo the operations.""" super().__init__() self._factory = _AttributeFactory(None, attribute) @staticmethod def do_immediate(attribute: og.Attribute): """Removes the dynamic attribute, raising og.OmniGraphError if the removal failed.""" try: _AttributeFactory(None, attribute).remove() except og.OmniGraphError as error: carb.log_warn(str(error)) return False return True def do(self): """Remove the dynamic attribute, raising OmniGraphError if the removal failed.""" try: self._factory.remove() except og.OmniGraphError as error: carb.log_warn(str(error)) return False return True def undo(self): """Undo the removal of the dynamic attribute, raising OmniGraphError if the creation failed""" try: self._factory.create() except og.OmniGraphError as error: carb.log_warn(str(error)) return False return True # ============================================================================================================== class CreateNodeCommand(omni.kit.commands.Command): """ Create Node **Command**. Creates a new compute node of a particular node type in OmniGraph Args: graph: The graph in which the new compute node should be created node_path: The location in the USD stage to add the new compute node node_type: The name of the type of compute node to create create_usd: Whether to also create an USD prim on the stage for this node Raises: og.OmniGraphError if a node already exists at the specified node path """ def __init__(self, graph: og.Graph, node_path: str, node_type: str, create_usd: bool): self._graph = graph self._node_path = node_path self._node_type = node_type self._modify_usd = create_usd self._did_doit = False self._node = None # Do the operation do_immediately, bypassing the command's interaction with the undo queue @staticmethod def do_immediate(graph: og.Graph, node_path: str, node_type: str, modify_usd: bool): # Don't create a node if one already exists at the specified path. node = graph.get_node(node_path) if node is not None and node.is_valid(): raise og.OmniGraphError(f"Node already exists at {node_path}. Cannot create another.") return graph.create_node(node_path, node_type, modify_usd) def do(self): try: self._node = CreateNodeCommand.do_immediate(self._graph, self._node_path, self._node_type, self._modify_usd) except og.OmniGraphError: # This should raise an exception, but for backward compatibility when executed here it will just log a # warning and then succeed carb.log_warn(f"Node already exists at {self._node_path}. Cannot create another.") node = self._node self._node = None return node self._did_doit = True return self._node def undo(self): if self._did_doit and (self._node is not None): self._graph.destroy_node(self._node_path, self._modify_usd) self._node = None self._did_doit = False # ============================================================================================================== class CreateGraphAsNodeCommand(omni.kit.commands.Command): """ Create Graph As Node **Command**. Creates a new graph wrapped by a node. Args: graph: The graph in which the new wrapper node should be created node_name: The name of the node graph_path: The path to the graph evaluator_name: The name of the evaluator to use for the graph is_global_graph: Whether this is a global graph (global level graphs have their own FC) backed_by_usd: Whether the constructs are to be backed by USD fc_backing_type: What kind of Flatcache backs this graph pipeline_stage: What pipeline stage does this graph occupy: simulation, prerender, or postrender evaluation_mode: What evaluation mode to use with this graph: Automatic, Standalone or Instanced """ def __init__( self, graph, node_name, graph_path, evaluator_name, is_global_graph, backed_by_usd, fc_backing_type, pipeline_stage, evaluation_mode=og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_AUTOMATIC, ): self._graph = graph self._node_name = node_name self._graph_path = graph_path self._evaluator_name = evaluator_name self._is_global_graph = is_global_graph self._backed_by_usd = backed_by_usd self._fc_backing_type = fc_backing_type self._pipeline_stage = pipeline_stage self._evaluation_mode = evaluation_mode self._did_doit = False self._created_node = None # Do the operation do_immediately, bypassing the command's interaction with the undo queue @staticmethod def do_immediate( graph, node_name, graph_path, evaluator_name, is_global_graph, backed_by_usd, fc_backing_type, pipeline_stage, evaluation_mode, ) -> og.Node: return graph.create_graph_as_node( node_name, graph_path, evaluator_name, is_global_graph, backed_by_usd, fc_backing_type, pipeline_stage, evaluation_mode, ) # Returns the created node wrapping the graph def do(self) -> og.Node: node = CreateGraphAsNodeCommand.do_immediate( self._graph, self._node_name, self._graph_path, self._evaluator_name, self._is_global_graph, self._backed_by_usd, self._fc_backing_type, self._pipeline_stage, self._evaluation_mode, ) if node is not None and node.is_valid(): self._did_doit = True self._created_node = node return node def undo(self): if self._did_doit and (self._created_node is not None): self._graph.destroy_node(self._created_node.get_prim_path(), self._backed_by_usd) self._created_node = None self._did_doit = False # ============================================================================================================== class CreateSubgraphCommand(omni.kit.commands.Command): """ Create Subgraph **Command**. Creates a new subgraph node in OmniGraph Args: graph: The graph in which the new compute node should be created subgraph_path: The location in the USD stage to add the new compute node """ def __init__(self, graph, subgraph_path, evaluator=None, create_usd=True): self._graph = graph self._subgraph_path = subgraph_path self._evaluator = evaluator self._create_usd = create_usd self._did_doit = False self._subgraph = None def do(self): # Don't create a subgraph if one already exists at the specified path. subgraph = self._graph.get_node(self._subgraph_path) if subgraph is None or not subgraph.is_valid(): self._subgraph = self._graph.create_subgraph(self._subgraph_path, self._evaluator, self._create_usd) self._did_doit = True return self._subgraph return subgraph def undo(self): if self._did_doit and (self._subgraph is not None): self._graph.destroy_node(self._subgraph_path, True) if self._create_usd: delete_cmd = omni.usd.commands.DeletePrimsCommand([self._subgraph_path]) delete_cmd.do() self._subgraph = None self._did_doit = False # ============================================================================================================== class DeleteNodeCommand(omni.kit.commands.Command): """ Delete Node **Command**. Delete the specified node in the graph Args: graph: The graph in which the new compute node should be created node_path: The location in the USD stage to add the new compute node modify_usd: Whether to also delete the USD prim on the stage for this node """ def __init__(self, graph: og.Graph, node_path: str, modify_usd: bool): self._graph = graph self._node_path = node_path self._node_type = None self._modify_usd = modify_usd self._did_doit = False self._upstream_connections = {} self._downstream_connections = {} # Do the operation do_immediately, bypassing the command's interaction with the undo queue @staticmethod def do_immediate(graph: og.Graph, node_path: str, modify_usd: bool): upstream_connections = {} downstream_connections = {} did_doit = False node = graph.get_node(node_path) if node is not None and node.is_valid(): attributes = node.get_attributes() for attribute in attributes: _upstream_connections = attribute.get_upstream_connections() upstream_connections[attribute.get_name()] = [ (src_attr.get_node().get_prim_path(), src_attr.get_name()) for src_attr in _upstream_connections ] for src_attr in _upstream_connections: src_attr.disconnect(attribute, modify_usd) _downstream_connections = attribute.get_downstream_connections() downstream_connections[attribute.get_name()] = [ (dst_attr.get_node().get_prim_path(), dst_attr.get_name()) for dst_attr in _downstream_connections ] for dst_attr in _downstream_connections: attribute.disconnect(dst_attr, modify_usd) node_type = node.get_type_name() if not node_type: node_type = node.get_type_name() graph.destroy_node(node_path, modify_usd) did_doit = True return (node_type, upstream_connections, downstream_connections, did_doit) return (None, {}, {}, False) def do(self): ( self._node_type, self._upstream_connections, self._downstream_connections, self._did_doit, ) = DeleteNodeCommand.do_immediate(self._graph, self._node_path, self._modify_usd) def undo(self): if self._did_doit and (self._node_type is not None): node = self._graph.create_node(self._node_path, self._node_type, self._modify_usd) for attribute_name, src_connections in self._upstream_connections.items(): attribute = node.get_attribute(attribute_name) for src_node_path, src_attr_name in src_connections: src_node = self._graph.get_node(src_node_path) src_attr = src_node.get_attribute(src_attr_name) src_attr.connect(attribute, self._modify_usd) for attribute_name, dest_connections in self._downstream_connections.items(): attribute = node.get_attribute(attribute_name) for dest_node_path, dest_attr_name in dest_connections: dest_node = self._graph.get_node(dest_node_path) dest_attr = dest_node.get_attribute(dest_attr_name) attribute.connect(dest_attr, self._modify_usd) self._node_type = None self._did_doit = False # ============================================================================================================== class CreateVariableCommand(omni.kit.commands.Command): """ Create Variable **Command**. Creates a new variable of a particular type in OmniGraph Args: graph: The graph in which the new variable should be created variable_name: The name of the new variable variable_type: The OmniGraph type of the new variable graph_context: The OmniGraph context to use when setting the initial variable value variable_value: The initial variable value """ def __init__( self, graph: og.Graph, variable_name: str, variable_type: og.Type, graph_context: og.GraphContext = None, variable_value=None, ): self._graph = graph self._variable_name = variable_name self._variable_type = variable_type self._graph_context = graph_context self._variable_value = variable_value self._created_variable = None @staticmethod def do_immediate( graph: og.Graph, variable_name: str, variable_type: og.Type, graph_context: og.GraphContext = None, variable_value=None, ): if not graph or not graph.is_valid() or not variable_name or not variable_type: return None created_variable = graph.create_variable(variable_name, variable_type) if created_variable and variable_value is not None: og.Controller.set_variable_default_value(created_variable, variable_value) return created_variable def do(self): self._created_variable = CreateVariableCommand.do_immediate( self._graph, self._variable_name, self._variable_type, self._graph_context, self._variable_value, ) return self._created_variable def undo(self): if self._created_variable is None: return self._graph.remove_variable(self._created_variable) self._created_variable = None # ============================================================================================================== class RemoveVariableCommand(omni.kit.commands.Command): """ Remove Variable **Command**. Remove the specified variable in the graph Args: graph: The graph to remove the variable from variable: The OmniGraph IVariable to be removed graph_context: The OmniGraph context to use when restoring the variable value on undo """ def __init__( self, graph: og.Graph, variable: og.IVariable, graph_context: og.GraphContext = None, ): self._graph = graph self._variable = variable self._variable_name = None self._variable_type = None self._graph_context = graph_context self._variable_value = None self._removed = False def do(self): if not self._graph or not self._graph.is_valid() or not self._variable: return self._variable_name = self._variable.name self._variable_type = self._variable.type self._variable_value = og.Controller.get_variable_default_value(self._variable) self._removed = self._graph.remove_variable(self._variable) def undo(self): if not self._removed: return self._variable = self._graph.create_variable(self._variable_name, self._variable_type) if self._variable_value is not None: og.Controller.set_variable_default_value(self._variable, self._variable_value) class _OGRestoreConnectionsOnUndo(omni.kit.commands.Command): """ Restore connections between OG nodes on undo. (Does nothing on do or redo.) This command is for internal use only. It may be changed or removed without notice. Args: connections (List[(str, str)]) The connections to be restored. Each element of the list is a tuple containing the path strings for the source and destination attributes. """ # When the source prim for a connection is deleted OG removes all traces of the # connection. If the deletion is undone OG has no way of knowing that the restored # prim had a connection which should also be restored. This command is used to # restore those connections on undo. def __init__(self, connections: List[Tuple[str, str]]): self._path_strings: List[Tuple[str, str]] = connections.copy() self.__reconnect_task = None def destroy(self): if self.__reconnect_task: if not self.__reconnect_task.done(): self.__reconnect_task.cancel() self.__reconnect_task = None def do(self): pass def undo(self): # We cannot do the reconnection yet because OG won't have created the prim's # Node yet. if self.__reconnect_task is None or self.__reconnect_task.done(): self.__reconnect_task = asyncio.ensure_future(self.__do_reconnections()) async def __do_reconnections(self): # Give OG a chance to create the prim's Node. await omni.kit.app.get_app().next_update_async() for src_attr_str, dest_attr_str in self._path_strings: src_attr: og.Attribute = og.Controller.attribute(src_attr_str) dest_attr: og.Attribute = og.Controller.attribute(dest_attr_str) if src_attr and dest_attr and src_attr not in dest_attr.get_upstream_connections(): src_attr.connect(dest_attr, modify_usd=True) self.__reconnect_task = None
45,395
Python
42.482759
120
0.591585
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/object_lookup.py
"""Accessor for objects associated with OmniGraph""" import os from typing import List, Optional, Tuple, Union import omni.graph.core as og import omni.usd from carb import log_info, log_warn from pxr import Sdf, Usd from .typing import ( AttributeSpec_t, AttributeSpecs_t, AttributeType_t, GraphSpec_t, GraphSpecs_t, Node_t, NodeSpec_t, NodeSpecs_t, NodeType_t, NodeTypes_t, Prim_t, Prims_t, Variable_t, VariableName_t, Variables_t, ) # Debugging variable that provides an efficient way of using the logging mechanism for persistent debugging. # Use the pattern "DBG and log_info(f'Hello {world}')" to prevent the string formatting when debugging is off DBG = os.getenv("OGN_DEBUG_OBJECTS") is not None # ===================================================================== class ObjectLookup: """Helper to extract OmniGraph types from various types of descriptions for them. These functions take flexible spec types that identify attributes, nodes, or graphs. In most cases the spec types can be either one of or a list of the objects being used or found by the functions. The forms each spec type can take are as follows: **GraphSpec_t** - An :py:class:`omni.graph.core.Graph` object - A string containing the path to an :py:class:`omni.graph.core.Graph` object - An :py:class:`Sdf.Path` containing the path to an :py:class:`omni.graph.core.Graph` object - A list of any of the above **NodeSpec_t** - An :py:class:`omni.graph.core.Node` object - A string containing the path to an :py:class:`omni.graph.core.Node` object - An :py:class:`Sdf.Path` containing the path to an :py:class:`omni.graph.core.Node` object - A :py:class:`Usd.Prim` or :py:class:`Usd.Typed` that is the USD backing of an :py:class:`omni.graph.core.Node` object - None, for situations in which the node itself is redundant information - A 2-tuple consisting of a string and a :py:const:`omni.graph.core.GraphSpec_t`, where the string is a relative path to the :py:class:`omni.graph.core.Node` object within the :py:class:`omni.graph.core.Graph` - A list of any of the above **AttributeSpec_t** - An omni.graph.core.Attribute object - A string containing the full path to the omni.graph.core.Attribute object on the USD stage - An :py:class:`Sdf.Path` containing the full path to the omni.graph.core.Attribute object on the USD stage - A Usd.Attribute that is the USD backing of an omni.graph.core.Attribute object - A 2-tuple consisting of a string and a NodeSpec_t, where the string is the omni.graph.core.Attribute object's name within the :py:class:`omni.graph.core.Node` - A list of any of the above **Prim_t** - A :py:class:`Usd.Prim` or :py:class:`Usd.Typed` object - A string containing the path to a :py:class:`Usd.Prim` or :py:class:`Usd.Typed` object - An :py:class:`Sdf.Path` containing the path to a :py:class:`Usd.Prim` or :py:class:`Usd.Typed` object - A NodeSpec_t, identifying a node whose USD backing :py:class:`Usd.Prim` or :py:class:`Usd.Typed` object is to be returned - A list of any of the above **Variables_t** - An omni.graph.core.IVariable object - A 2-tuple consisting of a :py:const:`omni.graph.core.GraphSpec_t` and a string, where the string is the name of the variable - A list of any of the above """ # ---------------------------------------------------------------------- @classmethod def graph(cls, graph_id: Optional[GraphSpecs_t]) -> Union[og.Graph, List[og.Graph]]: """Returns the OmniGraph graph(s) corresponding to the variable type parameter Args: graph_id: Information for the graph to find. If a list then iterate over the list Returns: Graph(s) corresponding to the description(s) in the current scene, None where there is no match Raises: og.OmniGraphError if a graph matching the identifier wasn't found """ _ = DBG and log_info(f"Looking up graph with {graph_id}") def __find_graph(graph_info: GraphSpec_t) -> Optional[og.Graph]: """Find a graph matching the type hints, or None if no such graph exists""" graph = None if isinstance(graph_info, og.Graph): graph = graph_info elif isinstance(graph_info, str): graph = og.get_graph_by_path(graph_info) elif isinstance(graph_info, Sdf.Path): graph = og.get_graph_by_path(str(graph_info.GetPrimPath())) # Invalid graph is an error if graph is not None and not graph.is_valid(): raise og.OmniGraphError(f"Graph description not a string, path or og.Graph - {graph}") return graph if isinstance(graph_id, list): return [__find_graph(graph_in_list) for graph_in_list in graph_id] return __find_graph(graph_id) # ---------------------------------------------------------------------- @classmethod def node(cls, node_id: NodeSpecs_t, graph_id: Optional[GraphSpec_t] = None) -> Union[og.Node, List[og.Node]]: """Returns the OmniGraph node(s) corresponding to the variable type parameter Args: node_id: Information for the node to find. If a list then iterate over the list graph_id: Identifier for graph to which the node belongs. Returns: Node(s) corresponding to the description(s) in the current graph, None where there is no match Raises: og.OmniGraphError: node description wasn't a recognized type or if a mismatched graph was passed in og.OmniGraphValueError: If the node description did not match a node in the graph """ _ = DBG and log_info(f"Looking up node with {node_id}, {graph_id}") graph_lookup = cls.graph(graph_id) def __verify_graph(nodes_graph: Optional[og.Graph], msg: str): """Raises og.OmniGraphError if the graph is invalid or not compatible with the one passed to the parent""" if nodes_graph is None: raise og.OmniGraphError(f"Node graph not found when looking up by {msg}") if graph_lookup is None: return if nodes_graph.get_handle() != graph_lookup.get_handle(): # TODO: This is a bug in node/graph association where on load it is associated with the root graph but # when created interactively it is associated with the nearest ancestor subgraph. if graph_lookup.get_path_to_graph().startswith(nodes_graph.get_path_to_graph()): return raise og.OmniGraphError( f"Node graph {nodes_graph.get_path_to_graph()} did not match {graph_lookup.get_path_to_graph()}" ) def __node_from_info(node: NodeSpec_t) -> og.Node: """Helper to extract a single node""" og_node = None error = None if isinstance(node, og.Node): og_node = node __verify_graph(og_node.get_graph(), "OmniGraph node") elif isinstance(node, tuple): if len(node) != 2: error = "Node tuple description must be (node_id, graph_id)" else: og_node = cls.node(node[0], node[1]) elif isinstance(node, Usd.Prim): og_node = og.get_node_by_path(str(node.GetPrimPath())) if og_node is None: error = f"Prim '{node.GetPrimPath()}' was not an OmniGraph node" else: __verify_graph(og_node.get_graph(), f"Prim '{node.GetPrimPath()}'") elif isinstance(node, Usd.Typed): og_node = og.get_node_by_path(str(node.GetPath())) if og_node is None: error = f"Schema prim '{node.GetPath()}' was not an OmniGraph node" else: __verify_graph(og_node.get_graph(), f"Prim '{node.GetPrimPath()}'") elif isinstance(node, Sdf.Path): og_node = og.get_node_by_path(str(node.GetPrimPath())) if og_node is None: error = f"Sdf path '{node.GetPrimPath()}' was not an OmniGraph node" else: __verify_graph(og_node.get_graph(), f"Sdf path '{node.GetPrimPath()}'") elif isinstance(node, str): node_path = ( node if node.startswith("/") or graph_lookup is None else f"{graph_lookup.get_path_to_graph()}/{node}" ) if node_path.find(".") >= 0: log_warn(f"Finding a node_path using an attribute path {node_path} - ignoring the attribute part") og_node = og.get_node_by_path(node_path.split(".")[0]) else: og_node = og.get_node_by_path(node_path) if og_node is None: error = f"Node path '{node_path}' was not an OmniGraph node" else: __verify_graph(og_node.get_graph(), f"String path '{node_path}'") else: error = "Unknown node specification type" if og_node is None: raise og.OmniGraphValueError(f"Could not find OmniGraph node from node description '{node}' - {error}") return og_node if isinstance(node_id, list): return [__node_from_info(node_in_list) for node_in_list in node_id] return __node_from_info(node_id) # -------------------------------------------------------------------------------------------------------------- @classmethod def node_path(cls, node_spec: NodeSpec_t) -> str: """Infers a node path from a spec where the node may or may not exist Args: node_spec: Description of a path to a node that may or may not exist Returns: The path inferred from the node spec. No assumption should be made about the validity of the path. Raises: og.OmniGraphError: If there was something inconsistent in the node spec or a path could not be inferred """ if isinstance(node_spec, str): return node_spec if isinstance(node_spec, Sdf.Path): return str(node_spec) if isinstance(node_spec, Usd.Prim): return str(node_spec.GetPrimPath()) if isinstance(node_spec, Usd.Typed): return str(node_spec.GetPath()) if isinstance(node_spec, og.Node): return node_spec.get_prim_path() if isinstance(node_spec, tuple) and len(node_spec) == 2: (node_path, graph_spec) = node_spec if isinstance(graph_spec, str): return f"{graph_spec}/{node_path}" if isinstance(graph_spec, Sdf.Path): return f"{graph_spec}/{node_path}" if isinstance(graph_spec, og.Graph): return f"{graph_spec.get_path_to_graph()}/{node_path}" raise og.OmniGraphError(f"Could not infer node path from '{node_spec}'") # -------------------------------------------------------------------------------------------------------------- @classmethod def prim_path(cls, prim_ids: Prims_t) -> Union[str, List[str]]: """Infers a prim path from a spec where the prim may or may not exist Args: prim_ids: Identifier of a prim or list of prims that may or may not exist Returns: The path(s) inferred from the prim spec(s). No assumption should be made about their validity. Raises: og.OmniGraphError: If there was something inconsistent in the prim spec or a path could not be inferred """ _ = DBG and log_info(f"Looking up prim path with {prim_ids}") def __prim_path_from_info(prim_id: Prim_t) -> str: """Infer a single path from a prim specification""" if isinstance(prim_id, str): return prim_id if isinstance(prim_id, Sdf.Path): return str(prim_id) if isinstance(prim_id, Usd.Prim): if not prim_id.IsValid(): raise og.OmniGraphError("Could not infer prim path from invalid prim") return str(prim_id.GetPrimPath()) if isinstance(prim_id, Usd.Typed): if not prim_id.IsValid(): raise og.OmniGraphError("Could not infer prim path from invalid schema") return str(prim_id.GetPath()) if isinstance(prim_id, og.Node): if not prim_id.is_valid(): raise og.OmniGraphError("Could not infer prim path from invalid node") return prim_id.get_prim_path() raise og.OmniGraphError(f"Could not infer prim path from '{prim_id}'") if isinstance(prim_ids, list): return [__prim_path_from_info(node_in_list) for node_in_list in prim_ids] return __prim_path_from_info(prim_ids) # -------------------------------------------------------------------------------------------------------------- @classmethod def attribute( cls, attribute_id: AttributeSpecs_t, node_id: Optional[Node_t] = None, graph_id: Optional[GraphSpec_t] = None ) -> Union[og.Attribute, List[og.Attribute]]: """Returns the OmniGraph attribute(s) corresponding to the variable type parameter Args: attribute_id: Information on which attribute to look for. If a list then get all of them. The attribute_id can take several forms, for maximum flexibility: - a 2-tuple consisting of the attribute name as str and a node spec. The named attribute must exist on the node - e.g. ("inputs:value", my_node) or ("inputs:value", "/Graph/MyNode"). This is equivalent to passing in the attribute and node spec as two different parameters. You'd use this form when requesting several attributes from different nodes rather than a bunch of attributes from the same node. - a str or Sdf.Path pointing directly to the attribute - e.g. "/Graph/MyNode/inputs:value" - a str that's an attribute name, iff the node_id is also specified - a Usd.Attribute pointing to the attribute's reference on the USD side node_id: Node to which the attribute belongs, when only the attribute's name is provided graph_id: Graph to which the node and attribute belong. Returns: Attribute(s) matching the description(s) - None where there is no match Raises: og.OmniGraphError if the attribute description wasn't one of the recognized types, if any of the attributes could not be found, or if there was a mismatch in node or graph and attribute. """ _ = DBG and log_info(f"Looking up attribute with {attribute_id}, {node_id}, {graph_id}") def __attribute_from_info(attribute_id: AttributeSpec_t) -> Optional[og.Attribute]: """Helper to extract a single attribute""" graph = cls.graph(graph_id) try: node = cls.node(node_id, graph) except og.OmniGraphValueError: node = None og_attribute = None try: if isinstance(attribute_id, og.Attribute): if node is not None and attribute_id.get_node().get_handle() != node.get_handle(): raise og.OmniGraphError( f"Attribute '{attribute_id.get_name()}' does not belong to node {node.get_prim_path()}" ) return attribute_id if isinstance(attribute_id, tuple): if len(attribute_id) != 2: raise og.OmniGraphError("An attribute spec must be a (name, node) tuple") return cls.attribute(attribute_id[0], attribute_id[1]) if isinstance(attribute_id, (Usd.Attribute, Sdf.Path)): attribute_id = ( attribute_id if isinstance(attribute_id, Usd.Attribute) else omni.usd.get_context().get_stage().GetAttributeAtPath(attribute_id) ) prim_node = cls.node(attribute_id.GetPrim(), graph) if attribute_id.IsValid() else None if prim_node is None: raise og.OmniGraphError("USD attribute not valid") if node is None: node = prim_node elif node.get_handle() != prim_node.get_handle(): raise og.OmniGraphError( f"USD prim node `{prim_node.get_prim_path()}` does not match node '{node.get_prim_path()}'" ) if not node.get_attribute_exists(attribute_id.GetName()): raise og.OmniGraphError( f"USD attribute '{attribute_id.GetName()}' does not refer to a legal og.Attribute" ) og_attribute = node.get_attribute(attribute_id.GetName()) if og_attribute is None: raise og.OmniGraphError( f"USD attribute {attribute_id.get_name()} not found on node {node.get_prim_path()}" ) elif isinstance(attribute_id, (Sdf.Path, str)): attribute_id = attribute_id.GetPrimPath() if isinstance(attribute_id, Sdf.Path) else attribute_id if attribute_id.find(".") >= 0: node_name, attribute_name = attribute_id.split(".") specified_node = cls.node(node_name, graph) if node is None: node = specified_node elif specified_node is None or node.get_handle() != specified_node.get_handle(): raise og.OmniGraphError("Attribute path is not a legal node/attribute combination") if node is None: raise og.OmniGraphError("Node of fully specified attribute path not found") elif node is None: # Bundle outputs do not have a "." separator so check to see if it's one of those node_name, attribute_name = attribute_id.rsplit("/", 1) node = cls.node(node_name, graph) if node is None: raise og.OmniGraphError("Node is required when only an attribute name is given") else: attribute_name = attribute_id if not node.get_attribute_exists(attribute_name): raise og.OmniGraphError( f"Attribute named '{attribute_name}' does not refer to a legal og.Attribute" ) og_attribute = node.get_attribute(attribute_name) if og_attribute is None: raise og.OmniGraphError( f"Attribute named '{attribute_name}' not found on node '{node.get_prim_path()}'" ) if og_attribute.get_node().get_handle() != node.get_handle(): raise og.OmniGraphError( f"OmniGraph attribute {og_attribute.get_name()} does not belong to" f" passed in node {node.get_prim_path()}" ) else: raise og.OmniGraphError("Unrecognized specification used to try to look up an OmniGraph attribute") except og.OmniGraphError as error: raise og.OmniGraphError( f"Failed trying to look up attribute with ({attribute_id}, node={node_id}, graph={graph_id})" ) from error return og_attribute if isinstance(attribute_id, list): return [__attribute_from_info(attribute_in_list) for attribute_in_list in attribute_id] return __attribute_from_info(attribute_id) # -------------------------------------------------------------------------------------------------------------- @classmethod def attribute_path(cls, attribute_spec: AttributeSpec_t) -> str: """Infers an attribute path from a spec where the attribute may or may not exist Args: attribute_spec: Location of where the attribute would be, if it exists Returns: Location of the attribute, if it exists Raises: og.OmniGraphError: If there was something inconsistent in the attribute spec or a path could not be inferred """ # Deduce the path from the type information provided if isinstance(attribute_spec, Sdf.Path): return str(attribute_spec) if isinstance(attribute_spec, str): return attribute_spec if isinstance(attribute_spec, Usd.Attribute): return str(attribute_spec.GetPath()) if isinstance(attribute_spec, og.Attribute): return cls.attribute_path((attribute_spec.get_name(), attribute_spec.get_node())) if isinstance(attribute_spec, tuple) and len(attribute_spec) == 2: # Assemble the two components of the path using strings instead of the Sdf.Path interface because # there is no guarantee or requirement that the path exist. (attribute_name, node_spec) = attribute_spec node_path = cls.node_path(node_spec) return f"{node_path}.{attribute_name}" raise og.OmniGraphError(f"Could not infer an attribute path from '{attribute_spec}'") # -------------------------------------------------------------------------------------------------------------- @classmethod def attribute_type(cls, type_id: Union[AttributeType_t, og.Attribute, og.AttributeData]) -> og.Type: """Returns the OmniGraph attribute type corresponding to the variable type parameter. All legal OGN types are recognized, as well as the UNKNOWN type. Args: type_id: Variable description of the attribute type object as: - An omni.graph.core.Type object - An OGN-style type description - e.g. "float[3]" - An Sdf-style type description - e.g. "float3" - An omni.graph.core.Attribute whose (resolved) type is to be retrieved - An omni.graph.core.AttributeData whose (resolved) type is to be retrieved Returns: Attribute type matching the description Raises: og.OmniGraphError if the attribute type description wasn't one of the recognized types """ _ = DBG and log_info(f"Looking up attribute type with {type_id}") if isinstance(type_id, og.Attribute): return type_id.get_resolved_type() if isinstance(type_id, og.AttributeData): return type_id.get_type() if isinstance(type_id, og.Type): if not og.AttributeType.is_legal_ogn_type(type_id) and type_id.base_type != og.BaseDataType.UNKNOWN: raise og.OmniGraphError(f"Attribute type {type_id} does not represent a legal OGN type") return type_id if isinstance(type_id, str): if type_id == "unknown": return og.Type(og.BaseDataType.UNKNOWN) attribute_type = og.AttributeType.type_from_ogn_type_name(type_id) if attribute_type.base_type == og.BaseDataType.UNKNOWN: attribute_type = og.AttributeType.type_from_sdf_type_name(type_id) if og.AttributeType.is_legal_ogn_type(attribute_type): return attribute_type raise og.OmniGraphError(f"Attribute type description '{type_id}' could not be parsed into a type") # ---------------------------------------------------------------------- @classmethod def node_type(cls, type_id: NodeTypes_t) -> Union[og.NodeType, List[og.NodeType]]: """Returns the OmniGraph node type corresponding to the variable type parameter Args: type_id: Information used to identify the omni.graph.core.NodeType object. - an omni.graph.core.NodeType object - a string that is the unique identifier of the node type - an omni.graph.core.Node whose type is to be returned - a Usd.Prim or Usd.Typed that is the USD backing of an omni.graph.core.Node whose type is to be returned - a list of any combination of the above Returns: Node type(s) matching the description Raises: og.OmniGraphError if the node type description wasn't one of the recognized types or could not be found """ _ = DBG and log_info(f"Looking up node type with {type_id}") def __node_type(node_type_id: NodeType_t) -> og.NodeType: """Look up a single node type from descriptive information""" node_type = None try: if isinstance(node_type_id, og.NodeType): node_type = node_type_id elif isinstance(node_type_id, str): node_type = og.get_node_type(node_type_id) elif isinstance(node_type_id, (og.Node, Usd.Prim, Usd.Typed)): node_type = cls.node(node_type_id).get_node_type() else: raise TypeError( "ID type must be og.NodeType, str, og.Node, Usd.Prim, or Usd.Typed -" f" {node_type_id} not recognized" ) except Exception as error: raise og.OmniGraphError(f"Failed to deduce node type from '{node_type_id}' - {error}") if node_type is None or not node_type.is_valid(): raise og.OmniGraphError(f"'{node_type_id}' is not a recognized node type") return node_type if isinstance(type_id, list): return [__node_type(one_type_id) for one_type_id in type_id] return __node_type(type_id) # ---------------------------------------------------------------------- @classmethod def prim(cls, prim_id: Prims_t) -> Union[Usd.Prim, List[Usd.Prim]]: """Returns the prim(s) corresponding to the node descriptions Args: prim_id: Information for the node to find. If a list then iterate over the list Returns: Prim(s) corresponding to the description(s) in the current graph, None where there is no match Raises: og.OmniGraphError if the node description didn't correspond to a valid prim. """ _ = DBG and log_info(f"Looking up prim with {prim_id}") stage = omni.usd.get_context().get_stage() if stage is None: raise og.OmniGraphError(f"Cannot get prim on node '{prim_id}' - there is no USD stage") def __prim_from_info(node: Prim_t): """Helper to find a single prim""" prim_to_return = None if isinstance(node, Sdf.Path): prim_to_return = stage.GetPrimAtPath(node.GetPrimPath()) elif isinstance(node, og.Node): prim_to_return = stage.GetPrimAtPath(node.get_prim_path()) if node.is_valid() else None elif isinstance(node, Usd.Prim): prim_to_return = node elif isinstance(node, Usd.Typed): prim_to_return = node.GetPrim() elif isinstance(node, str): prim_path = cls.prim_path(node) if prim_path is not None: prim_to_return = stage.GetPrimAtPath(prim_path) elif isinstance(node, tuple): omg_node = cls.node(node) prim_to_return = stage.GetPrimAtPath(omg_node.get_prim_path()) if omg_node.is_valid() else None if prim_to_return is None or not prim_to_return.IsValid(): raise og.OmniGraphError(f"Failed to get prim on node '{prim_id}'") return prim_to_return if isinstance(prim_id, list): return [__prim_from_info(node_in_list) for node_in_list in prim_id] return __prim_from_info(prim_id) # ---------------------------------------------------------------------- @classmethod def usd_attribute(cls, attribute_specs: AttributeSpecs_t) -> Union[Usd.Attribute, List[Usd.Attribute]]: """Returns the Usd.Attribute(s) corresponding to the attribute descriptions Args: attribute_specs: Location or list of locations from which to infer a matching Usd.Attribute Returns: Usd.Attribute(s) corresponding to the description(s) in the current graph Raises: og.OmniGraphError if the attribute description didn't correspond to a valid Usd.Attribute. """ _ = DBG and log_info(f"Looking up Usd.Attribute(s) with {attribute_specs}") stage = omni.usd.get_context().get_stage() if stage is None: raise og.OmniGraphError(f"Cannot get Usd.Attributes from '{attribute_specs}' - there is no USD stage") def __usd_attribute_from_info(attribute_id: AttributeSpec_t): """Helper to find a single prim""" usd_attribute = stage.GetAttributeAtPath(cls.attribute_path(attribute_id)) if usd_attribute.IsValid(): return usd_attribute raise og.OmniGraphError( f"Attribute spec '{attribute_id}' did not correspond to a valid USD attribute" f" from {cls.attribute_path(attribute_id)}" ) if isinstance(attribute_specs, list): return [__usd_attribute_from_info(attribute_spec) for attribute_spec in attribute_specs] return __usd_attribute_from_info(attribute_specs) # -------------------------------------------------------------------------------------------------------------- @classmethod def split_graph_from_node_path(cls, node_path: Union[str, Sdf.Path]) -> Tuple[og.Graph, str]: """Find the lowest level graph from a node path The path /World/Graph1/Graph2/Node1/Node2 would return the og.Graph at /World/Graph1/Graph2 and the relative node path "Node1/Node2". Args: node_path: Full path to the node from the root Returns: (graph, node_path) where graph is the lowest graph in the tree and node_path is the relative path to the node from the graph """ if isinstance(node_path, Sdf.Path): node_path = node_path.GetPrimPath() relative_path = [] graph = None while (graph is None or not graph.is_valid()) and node_path: graph = og.get_graph_by_path(node_path) if graph is None or not graph.is_valid(): try: (node_path, base) = node_path.rsplit("/", maxsplit=1) except ValueError: # No "/" in the string cannot be a legal node name - assume it's a graph name only return (node_path, None) relative_path.append(base) return (graph, "/".join(reversed(relative_path))) # -------------------------------------------------------------------------------------------------------------- @classmethod def variable(cls, variable_id: Variables_t) -> Union[og.IVariable, List[og.IVariable]]: """Returns the variables(s) corresponding to the variable description Args: variable_id: Information for the variable to find. If a list then iterate over the list Returns: Variables(s) corresponding to the description(s) in the current graph, None where there is no match Raises: og.OmniGraphError if the variable description didn't correspond to a valid variable """ _ = DBG and log_info(f"Looking up og.IVariable with {variable_id}") def var_from_info(var: Variable_t): var_to_return = None if isinstance(var, og.IVariable): var_to_return = var if isinstance(var, tuple) and len(var) == 2: (graph_spec, var_name) = var if isinstance(var_name, VariableName_t): graph = cls.graph(graph_spec) var_to_return = graph.find_variable(var_name) if var_to_return is None: raise og.OmniGraphError(f"Failed to get variable {var}") return var_to_return if isinstance(variable_id, list): return [var_from_info(x) for x in variable_id] return var_from_info(variable_id)
33,466
Python
47.856934
120
0.561107
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/runtime.py
# The information bracketed here with begin/end describes the interface that is recommended for use with runtime # attributes. The documentation uses these markers to perform a literal include of this code into the docs so that # it can be the single source of truth. Note that the interface described here is not the complete set of functions # functions available, merely the ones that make sense for the user to access when dealing with runtime attributes. # # begin-runtime-interface-description """ # A runtime attribute is one whose data type can only be determined at runtime, and which can potentially change # from one evaluation to the next. These attributes can be found either as bundle members or as the extended # attribute types "any" or "union". # # One way of getting this accessor class is by extracting a bundle member: # red_attribute = db.inputs.colorBundle.attribute_by_name(db.tokens.red) # The other way is to access the data of an extended attribute type in the same way you'd access any other attribute red_attribute = db.inputs.colorAtRuntime # The wrapper class has access to the attribute description information, specifically the name and type red_name = red_attribute.name red_type = red_attribute.type # Array attributes have a "size" property, which can also be set on output or state attributes point_array = db.inputs.mesh.attribute_by_name(db.tokens.points) deformed_point_array = db.outputs.mesh.attribute_by_name(db.tokens.points) deformed_point_array.size = point_array.size # Default value access is done through the value property, which is writable on output or state attributes red_input = db.inputs.colorBundle.attribute_by_name(db.tokens.red) red_output = db.outputs.colorBundle.attribute_by_name(db.tokens.red) red_output.value = 1.0 - red_input.value # By default the above functions operate in the same memory space as was defined by the bundle that contained the # attribute. If you wish to be more explicit about where the memory lives you can access the specific versions of # value properties that force either CPU or GPU memory space if on_gpu: call_cuda_code(red_output.gpu_value, red_input.gpu_value) else: red_output.cpu_value = 1.0 - red_input.cpu_value # Lastly, on the rare occasion you need direct access to the attribute's ABI through the underlying type # og.AttributeData you can access it through the abi property my_attribute_data = red_attribute.abi """ from __future__ import annotations from typing import Any # end-runtime-interface-description import omni.graph.core as og from .attribute_values import WrappedArrayType from .utils import non_const # ================================================================================ class RuntimeAttribute: def __init__( self, attribute_data: og.AttributeData, context: og.GraphContext, read_only: bool, on_gpu: bool = None, gpu_ptr_kind: og.PtrToPtrKind = og.PtrToPtrKind.GPU, ): """Constructs a wrapper around the raw ABI attribute data object""" self.attribute_data = attribute_data self.read_only = read_only self.helper = og.AttributeDataValueHelper(attribute_data) self._on_gpu = False if on_gpu is None else on_gpu self.helper.gpu_ptr_kind = gpu_ptr_kind # ------------------------------------------------------------------------------------------ def copy_data(self, other: RuntimeAttribute) -> bool: """Copies data from another attribute, returning True if the copy succeeded, else False""" self.attribute_data.copy_data(other.attribute_data) # ------------------------------------------------------------------------------------------ @property def abi(self) -> og.AttributeData: """Returns the ABI object representing the bundled attribute's data""" return self.attribute_data # ------------------------------------------------------------------------------------------ @property def size(self) -> int: """Return the number of elements in the attribute (1 for regular data, elementCount for arrays)""" return self.attribute_data.size() @size.setter @non_const def size(self, new_size: int) -> int: """Set the array size for the element. Raises og.OmniGraphError if the data type is not an array""" if not self.attribute_data.resize(new_size): raise og.OmniGraphError(f"Not allowed to resize data that is not an array type - '{self.type}'") # ------------------------------------------------------------------------------------------ @property def name(self) -> str: """Returns the name of the attribute data. Can only be set on creation.""" return self.attribute_data.get_name() # ------------------------------------------------------------------------------------------ @property # noqa: A003 def type(self) -> og.Type: """Returns the attribute type of the attribute data. Can only be set on creation.""" return self.attribute_data.get_type() # ------------------------------------------------------------------------------------------ @property def value(self) -> Any: """Get the value of an attributeData for reading""" wrapper_type = WrappedArrayType.RAW if self._on_gpu else WrappedArrayType.NUMPY return self.helper.get( on_gpu=self._on_gpu, return_type=wrapper_type if self.type.array_depth > 0 else None, reserved_element_count=None if self.type.array_depth == 0 else self.size, ) @value.setter @non_const def value(self, new_value: Any): """Set the value of an attributeData""" if self.read_only: raise og.ReadOnlyError(f"Not allowed to set read-only attribute data {self.attribute_data.get_name()}") self.helper.set(new_value, on_gpu=self._on_gpu) # ------------------------------------------------------------------------------------------ @property def gpu_value(self) -> Any: """Get the value of an attributeData for reading, forcing it to be on the GPU""" return self.helper.get( on_gpu=True, return_type=WrappedArrayType.RAW if self.type.array_depth > 0 else None, reserved_element_count=None if self.type.array_depth == 0 else self.size, ) @gpu_value.setter @non_const def gpu_value(self, new_value: Any): """Set the value of an attributeData, forcing it to be on the GPU""" if self.read_only: raise og.ReadOnlyError(f"Not allowed to set read-only attribute data {self.attribute_data.get_name()}") self.helper.set(new_value, on_gpu=True) # ------------------------------------------------------------------------------------------ @property def cpu_value(self) -> Any: """Get the value of an attributeData for reading, forcing it to be on the CPU""" return self.helper.get( on_gpu=False, reserved_element_count=None if self.type.array_depth == 0 else self.size, ) @cpu_value.setter @non_const def cpu_value(self, new_value: Any): """Set the value of an attributeData, forcing it to be on the CPU""" if self.read_only: raise og.ReadOnlyError(f"Not allowed to set read-only attribute data {self.attribute_data.get_name()}") self.helper.set(new_value, on_gpu=False) # ------------------------------------------------------------------------------------------ def array_value(self, *args, **kwargs) -> Any: """Set the value of an attributeData for writing, with preallocated element space. See og.AttributeDataValueHelper.get_array() for parameters. on_gpu is provided here """ return self.helper.get(*args, on_gpu=self._on_gpu, **kwargs)
7,891
Python
45.698225
116
0.608668
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/errors.py
"""Implementation details for internal OmniGraph error types""" import traceback from typing import Optional from .object_lookup import ObjectLookup from .typing import Attribute_t # ====================================================================== class OmniGraphError(Exception): """Exception to raise when there is an error in an OmniGraph operation""" SHOW_STACK_TRACE = False @classmethod def set_show_stack_trace(cls, enable_traces: bool): """Turn on or off display of stack traces when an OmniGraphError is raised""" cls.SHOW_STACK_TRACE = enable_traces def __init__(self, *args, **kwargs) -> str: """Returns the exception text, with stack trace information added if requested""" if OmniGraphError.SHOW_STACK_TRACE: self.__stack_trace = "\n" + "\n".join(traceback.format_stack(limit=5)[:-1]) else: self.__stack_trace = "" super().__init__(*args, **kwargs) def __str__(self): return f"{super().__str__()}{self.__stack_trace}" # ====================================================================== class OmniGraphValueError(OmniGraphError): """Exception to raise when an OmniGraph operation encountered an illegal value""" # ====================================================================== class ReadOnlyError(OmniGraphError): """Exception to raise when there is a write operation on a read-only attribute (i.e. an input)""" def __init__(self, attribute: Attribute_t, message: Optional[str] = None): """Set up the attribute information for the operation""" super().__init__(message) self.__attribute = ObjectLookup.attribute(attribute) self.__message = message def __str__(self) -> str: """Returns the string representing the exception""" if self.__message: return f"{self.__message} (on {self.__attribute.get_name()})" return f"{self.__attribute.get_name()}"
1,979
Python
37.076922
101
0.577564
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/utils.py
""" A collection of assorted utilities used by the OmniGraph scripts """ import os import sys from contextlib import contextmanager, suppress from dataclasses import dataclass from functools import wraps from typing import Any, Callable, Dict, List, Optional, Tuple, Union import carb import numpy as np import omni.graph.core as og from pxr import Gf, OmniGraphSchema, Sdf, Tf, Usd, Vt from .object_lookup import ObjectLookup # Moved to .settings from .settings import Settings from .typing import Attribute_t, AttributeWithValue_t, Graph_t, Nodes_t temporary_setting = Settings.temporary # noqa:F401 # Special sentinel object to indicate that an argument in the _flatten_arguments function has no specified value. # This is required because in some cases "None" is an acceptable value for such arguments so it cannot be used there. class _UnspecifiedClass: pass _Unspecified = _UnspecifiedClass() # ============================================================================================================== def _flatten_arguments( mandatory: List[Tuple[str, Any]] = None, optional: List[Tuple[str, Any]] = None, args: List[Any] = None, kwargs: Dict[str, Any] = None, ) -> List[Any]: """Takes an argument list description and a set of supplied arguments and flattens them out into an explicit position-based set of arguments. This allows overrides for the argument values in either *args or **kwargs, raising an exception if any appear in both. This is a helper function for the pattern of having two very similar functions with slightly different argument lists calling into a shared implementation function. Here's an example of a function "jump()" with a parameter of "how_high" that can be overridden in the function call, and which will have a default value in the object constructor. .. code-block:: python class Toady: def __init__(self): self.__height_default = 1 self.__height_unit = METRES self.jump = self.__jump_obj @classmethod def jump(cls, *args, **kwargs): return cls.__jump(args=args, kwargs=kwargs) def __jump_obj(self, *args, **kwargs): return self.__jump(how_high=self.__height_default, unit=self.__height_unit, args=args, kwargs=kwargs) @staticmethod def __jump(obj, how_high: int = None, unit: str = None, args=List[Any], kwargs=Dict[str, Any]): (how_high, unit) = _flatten_arguments( mandatory=[("how_high", how_high)], optional=[("unit", unit)], args=args, kwargs=kwargs ) print(f"Jumping {how_high} {unit}") # Legal calls to this function Toady.jump(how_high=123) Toady.jump(123) Toady.jump(123, unit=FEET) Toady.jump(how_high=123, unit=FEET) # The main difference in object-based calls is the ability to omit the "mandatory" parameter since # it's value will be retrieved from the object's defaults instead smithers = Toady() smithers.jump() smithers.jump(how_high=123) smithers.jump(123) smithers.jump(123, unit=FEET) smithers.jump(how_high=123, unit=FEET) smithers.jump(unit=FEET) The mandatory and optional arguments mimic Python function argument lists, where the mandatory ones have no defaults and the optional ones do. This is how a function call would translate to mandatory/optional specs: .. code-block:: python def sample(a: bool, b: str, c: int = 5) # mandatory = [("a", None), ("b", None)], optional = [("c", 5)] Here is a sequence that flattens the arguments to a function taking a mandatory argument "a" and an optional argument "b": _flatten_arguments(mandatory=[("a", None)], optional=[("b", True)], args, kwargs) # args=[], kwargs={} -> raise og.OmniGraphError(missing attribute) # args=[3], kwargs={} -> returns (3, True) Args: mandatory: List of (arg_name, default_arg_value) for every mandatory argument. The sentinel value "_Unspecified" is used as the default_arg_value to indicate that no value was provided. optional: List of (arg_name, default_arg_value) for every optional argument. The sentinel value "_Unspecified" is used as the default_arg_value to indicate that no value was provided. args: List of positional args to check kwargs: Dictionary of keyword args to check, modified in place with the net resulting argument set Raises: og.OmniGraphError if the arguments were internally redundant or inconsistent """ if mandatory is None: mandatory = [] if optional is None: optional = [] all_keywords = [name for name, _ in mandatory + optional] final_args = [value for _, value in mandatory + optional] # Walk the keyword args mandatory_found = {key: not isinstance(value, _UnspecifiedClass) for key, value in mandatory} if kwargs: index = 0 # noqa: SIM113 Index needed across two loops for name, _ in mandatory: if name in kwargs: final_args[index] = kwargs[name] mandatory_found[name] = True index += 1 for name, _ in optional: if name in kwargs: final_args[index] = kwargs[name] index += 1 # Walk the positional args, converting to the matching kwarg and checking for duplication if args: for index, arg in enumerate(args): try: keyword = all_keywords[index] if keyword in mandatory_found: mandatory_found[keyword] = True except IndexError as error: raise og.OmniGraphError( f"Argument {index} has no corresponding attribute definition - {all_keywords}" ) from error if keyword in kwargs: raise og.OmniGraphError(f"'{keyword}' cannot be specified both in both args={args} and kwargs={kwargs}") final_args[index] = arg # Report if any mandatory args were missing if not all(mandatory_found.values()): missing = [mandatory_key for mandatory_key, found in mandatory_found.items() if not found] raise og.OmniGraphError(f"Missing mandatory argument(s) {missing}") return final_args # ==================================================================================================== @dataclass class TypedValue: """Class that encapsulates an arbitrary value with an explicit data type. This can be used when the data type is ambiguous due to the limited set of native Python data types. For example it can differentiate between a float and double whereas in Python they are the same thing. """ value: Any = None type: og.Type = og.Type(og.BaseDataType.UNKNOWN) # noqa: A003 def __post_init__(self): """Ensure that type information is an og.Type""" self.type = ObjectLookup.attribute_type(self.type) def has_type(self) -> bool: """Returns True iff the data value has an explicit type (i.e. is not type UNKNOWN)""" return self.type.base_type != og.BaseDataType.UNKNOWN def __len__(self) -> int: """Returns the length of the value so that length can be taken on a value or typed value equally. The length of a None value is 0, any non-list has length 1. """ try: return len(self.value) except TypeError: return 0 if self.value is None else 1 def set(self, *args, **kwargs): # noqa: A003 """Set the data to a specific value and/or type. The regular __init__ can be passed (VALUE, TYPE) in the simplest case; this is for more flexible setting. The argument types are flexible and support the following syntax: set(): Sets the data value to None and makes it an UNKNOWN type set(Any): Sets the data value and makes it an UNKNOWN type set(Any, str|og.Type): Sets the data value and defines an explicit type set(value=Any): Sets the data value and makes it an UNKNOWN type set(value=Any, type=str|og.Type): Sets the data value and defines an explicit type No attempt is made to match the type to the value - it is assumed that if it is specified, it is correct. Raises: og.OmniGraphError if the argument combinations are not one of the above, or the type could not be parsed """ # Check to make sure the arguments are a legal combination try: if not args: if "value" not in kwargs: # Allow the edge case of "no data" to be a if not kwargs: self.value = None self.type = og.Type(og.BaseDataType.UNKNOWN) return raise og.OmniGraphError("Keyword args must at least contain 'value'") self.value = kwargs["value"] if len(kwargs) == 2: if "type" not in kwargs: raise og.OmniGraphError("'type' not found") self.type = ObjectLookup.attribute_type(kwargs["type"]) elif len(kwargs) > 2: raise og.OmniGraphError("Too many keyword arguments") elif len(args) < 3: if kwargs: raise og.OmniGraphError("Cannot use both args and kwargs together") self.value = args[0] if len(args) == 2: self.type = ObjectLookup.attribute_type(args[1]) else: raise og.OmniGraphError("Too many unnamed arguments") except og.OmniGraphError as error: raise og.OmniGraphError( "Arguments must be one of (VALUE), (VALUE, TYPE), (value=VALUE), or (value=VALUE, type=TYPE) -" f" saw ({args}, {kwargs}) ({error})" ) # ==================================================================================================== ValueToSet_t = Union[Any, TypedValue] """Typing that identifies a value that may or may not have an explicit type defined.""" AttributeValue_t = Tuple[AttributeWithValue_t, ValueToSet_t] """Typing for an Attribute/Value Pair""" AttributeValues_t = Union[AttributeValue_t, List[AttributeValue_t]] """Typing for a list of Attribute/Value Pairs""" # ==================================================================================================== # The DualMethodName trick confuses the doc generator. Detect when it's running and skip the redirection in those cases. # Checking once avoids potential problems when the user imports sphinx for some other reason. IN_SPHINX = sys.argv[0].find("sphinx") >= 0 and "sphinx" in sys.modules # ==================================================================================================== class DualMethodName(type): """ This class, when used as a metaclass, facilitates using the same method name for both class and object methods, calling different implementations internally. .. code-block:: python # To use it you first declare your class to have this one as its metaclass class MyClass(metaclass=DualMethodName): # Then you add a redirection table as a class variable, where the key is the shared method name and # the value is the name of the @classmethod that implements it. DUAL_METHODS={"edit": "_cls_edit"} # This indicates that the actual method calls will look like this: # MyClass.edit() -> _cls_edit() # MyClass().edit() -> edit() # For consistency you can choose to implement a common method with the implementation logic, or you can # handle it any other way that's appropriate @classmethod def __implement_edit(cls, some_object): pass # Implementations that illustrate the difference between the two methods being called def edit(self): return self.__implement_edit(self.some_object) @classmethod def _cls_edit(self): return cls.__implement_edit(SomeObject()) # The metaclass understands inheritance so it can be put at the lowest level of a class hierarchy and # all of the derived classes will have the chance to enhance the redirection list simply by defining the # same class variable. Any duplicate key names will be redirected to the one appropriate to the type of object. class MyOtherClass(MyClass): DUAL_METHODS={"run": "_cls_run", "stop": "_cls_stop"} """ def __getattribute__(cls, key): """Intercepts method name requests to allow the DUAL_METHODS dictionary to override the call locations""" # In docs builds we always want the actual method, or the documentation gets messed up if IN_SPHINX: return super().__getattribute__(key) # TODO: It would be nice if once the dual methods were established this was no longer necessary # and we could take a short cut that uses a try/except to immediately jump to the right place if key == "DUAL_METHODS": redirections = super().__getattribute__(key) or {} for base_class in cls.__bases__: if base_class != cls and hasattr(base_class, key): redirections.update(base_class.__getattribute__(base_class, key) or {}) return redirections if not key.startswith("_"): for shared_name, class_method in cls.DUAL_METHODS.items(): if key == shared_name: return super().__getattribute__(class_method) return super().__getattribute__(key) # ==================================================================================================== DBG_EVAL = os.getenv("OGN_DEBUG_EVAL") is not None DBG = os.getenv("OGN_DEBUG") is not None def dbg(message: str): """Print out a debugging message - use DBG and dbg() to selectively enable it""" print(f"DBG: {message}", flush=True) def dbg_eval(message: str): """Print out a debugging message if DBG_EVAL is enabled""" return DBG_EVAL and dbg(message) # ================================================================================ def list_dimensions(value) -> int: """Returns the dimension of the value type, assuming all entries have the same subdimension. 0 = single values 1 = [] and () 2 = [[]] [()] (()) ([]) etc. """ if not isinstance(value, (list, tuple)) or isinstance(value, str): return 0 return 1 + list_dimensions(value[0]) if len(value) > 0 else 1 # ================================================================================ async def load_example_file(example_file_name: str): """Load the contents of the USD example file onto the stage Loading will be effectively synchronous when called as "await load_example_file(X)". In a testing environment we need to run one test at a time since there is no guarantee that tests can run concurrently, especially when loading files. This method encapsulates the logic necessary to load a test file using the omni.kit.asyncapi method and then wait for it to complete before returning. Args: example_file_name: Name of the example file to load - if an absolute path use it as-is Raises: ValueError: test file is not a valid USD file """ # Delayed until here because the PYTHONPATH is not set the first time this file is imported import omni.usd if not Usd.Stage.IsSupportedFile(example_file_name): raise ValueError("Only USD files can be loaded with this method") if os.path.isabs(example_file_name): path_to_file = example_file_name else: path_to_file = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "data", example_file_name)) usd_context = omni.usd.get_context() usd_context.disable_save_to_recent_files() with open(path_to_file, "r", encoding="utf-8") as example_fd: first_line = example_fd.readline() if first_line.startswith("version"): raise ValueError(f"Do a 'git lfs pull' to update the contents of {path_to_file}") (result, error) = await omni.usd.get_context().open_stage_async(path_to_file) usd_context.enable_save_to_recent_files() return (result, error) # ================================================================================ def non_const(func): """Simple decorator that runs any member function only if the member is a writable type""" @wraps(func) def wrapper_non_const(self, *args, **kwargs): if self.read_only: raise og.OmniGraphError(f"{self.__class__.__name__}.{func.__name__} can only be called on writable objects") return func(self, *args, **kwargs) return wrapper_non_const # ============================================================================================================== # ---------------------------------------------------------------------------------- _usd_scaler_array_types = { # scaler array og.BaseDataType.BOOL: Vt.BoolArray, og.BaseDataType.DOUBLE: Vt.DoubleArray, og.BaseDataType.FLOAT: Vt.FloatArray, og.BaseDataType.HALF: Vt.HalfArray, og.BaseDataType.INT: Vt.IntArray, og.BaseDataType.INT64: Vt.Int64Array, og.BaseDataType.TOKEN: Vt.TokenArray, og.BaseDataType.UINT: Vt.UIntArray, og.BaseDataType.UINT64: Vt.UInt64Array, og.BaseDataType.UCHAR: Vt.UCharArray, } _usd_no_role_tuple_types = { (og.BaseDataType.DOUBLE, 2, 0): Gf.Vec2d, (og.BaseDataType.DOUBLE, 3, 0): Gf.Vec3d, (og.BaseDataType.DOUBLE, 4, 0): Gf.Vec4d, (og.BaseDataType.FLOAT, 2, 0): Gf.Vec2f, (og.BaseDataType.FLOAT, 3, 0): Gf.Vec3f, (og.BaseDataType.FLOAT, 4, 0): Gf.Vec4f, (og.BaseDataType.HALF, 2, 0): Gf.Vec2h, (og.BaseDataType.HALF, 3, 0): Gf.Vec3h, (og.BaseDataType.HALF, 4, 0): Gf.Vec4h, (og.BaseDataType.INT, 2, 0): Gf.Vec2i, (og.BaseDataType.INT, 3, 0): Gf.Vec3i, (og.BaseDataType.INT, 4, 0): Gf.Vec4i, (og.BaseDataType.DOUBLE, 2, 1): Vt.Vec2dArray, (og.BaseDataType.DOUBLE, 3, 1): Vt.Vec3dArray, (og.BaseDataType.DOUBLE, 4, 1): Vt.Vec4dArray, (og.BaseDataType.FLOAT, 2, 1): Vt.Vec2fArray, (og.BaseDataType.FLOAT, 3, 1): Vt.Vec3fArray, (og.BaseDataType.FLOAT, 4, 1): Vt.Vec4fArray, (og.BaseDataType.HALF, 2, 1): Vt.Vec2hArray, (og.BaseDataType.HALF, 3, 1): Vt.Vec3hArray, (og.BaseDataType.HALF, 4, 1): Vt.Vec4hArray, (og.BaseDataType.INT, 2, 1): Vt.Vec2iArray, (og.BaseDataType.INT, 3, 1): Vt.Vec3iArray, (og.BaseDataType.INT, 4, 1): Vt.Vec4iArray, } def attribute_value_as_usd(og_type: og.Type, value: Any, array_limit: Optional[int] = None) -> Any: """Returns the value, converted into a type suitable for setting through the USD API compatible with an attribute of the given type. It's assumed that anything passed in here has a valid USD attribute type; i.e. no extended attributes or bundles Args: og_type The OG type of the given data value The value read from the attribute array_limit Arrays larger than this value will be truncated Returns: The USD-compatible value """ is_ndarray = isinstance(value, np.ndarray) if (og_type.array_depth > 0) and (array_limit is not None) and is_ndarray and (len(value) > array_limit): value = value[0:array_limit] # Handle the special cases with odd types first if og_type.role in [og.AttributeRole.FRAME, og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM]: dim = 2 if og_type.tuple_count == 4 else 3 if og_type.tuple_count == 9 else 4 type_name = f"Matrix{dim}d" if og_type.array_depth > 0: return getattr(Vt, f"{type_name}Array").FromBuffer( np.array([np.array(element).reshape(dim, dim) for element in value]) ) return getattr(Gf, type_name)(np.array(value).reshape(dim, dim)) if og_type.role == og.AttributeRole.TIMECODE: return Sdf.TimeCode(value) if og_type.array_depth == 0 else Sdf.TimeCodeArray(len(value), value) if og_type.role == og.AttributeRole.QUATERNION: quat_type = { og.BaseDataType.DOUBLE: [Gf.Quatd, Vt.QuatdArray], og.BaseDataType.FLOAT: [Gf.Quatf, Vt.QuatfArray], og.BaseDataType.HALF: [Gf.Quath, Vt.QuathArray], } (gf_type, vt_type) = quat_type[og_type.base_type] # Quaternions appear in memory and OGN as [i, j, k, r] but the Gf.Quat constructor expects [r, i, j, k] so # do the reordering for compatibility. if is_ndarray: py_array = value.tolist() else: py_array = value if og_type.array_depth > 0: return vt_type([gf_type(item[3], item[0], item[1], item[2]) for item in py_array]) return gf_type(py_array[3], py_array[0], py_array[1], py_array[2]) with suppress(KeyError, AttributeError): if og_type.tuple_count > 1: usd_type = _usd_no_role_tuple_types[(og_type.base_type, og_type.tuple_count, og_type.array_depth)] if og_type.array_depth > 0: if is_ndarray: value = usd_type.FromBuffer(value) else: value = usd_type(value) else: if is_ndarray: value = usd_type(*value.tolist()) else: value = usd_type(*value) elif og_type.array_depth > 0: # Special case string, path vs uchar[] if (og_type.base_type == og.BaseDataType.UCHAR) and (og_type.role != og.AttributeRole.NONE): return value vt_class = _usd_scaler_array_types[og_type.base_type] # OG returns token and token arrays as python str, List[str] instead of ndarray, so we # can't use FromBuffer for those. if is_ndarray: value = vt_class.FromBuffer(value) else: value = vt_class(value) return value return value # ============================================================================================================== def python_value_as_usd(og_type: og.Type, value: Any) -> Any: """Converts the given python value to the equivalent USD value Args: og_type The OG type of the given data value The pure python value (IE not USD or numpy) Returns: The USD-compatible value """ if og_type.role in [og.AttributeRole.FRAME, og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM]: dim = 2 if og_type.tuple_count == 4 else 3 if og_type.tuple_count == 9 else 4 type_name = f"Matrix{dim}d" gf_type = getattr(Gf, type_name) if og_type.array_depth > 0: return getattr(Vt, f"{type_name}Array")([gf_type(item) for item in value]) return gf_type(value) if og_type.role == og.AttributeRole.TIMECODE: return Sdf.TimeCode(value) if og_type.array_depth == 0 else Sdf.TimeCodeArray(len(value), value) if og_type.role == og.AttributeRole.QUATERNION: quat_type = { og.BaseDataType.DOUBLE: [Gf.Quatd, Vt.QuatdArray], og.BaseDataType.FLOAT: [Gf.Quatf, Vt.QuatfArray], og.BaseDataType.HALF: [Gf.Quath, Vt.QuathArray], } (gf_type, vt_type) = quat_type[og_type.base_type] # Quaternions appear in memory and OGN as [i, j, k, r] but the Gf.Quat constructor expects [r, i, j, k] so # do the reordering for compatibility. if og_type.array_depth > 0: return vt_type([gf_type(item[3], item[0], item[1], item[2]) for item in value]) return gf_type(value[3], value[0], value[1], value[2]) with suppress(KeyError, AttributeError): if og_type.tuple_count > 1: usd_type = _usd_no_role_tuple_types[(og_type.base_type, og_type.tuple_count, og_type.array_depth)] if og_type.array_depth > 0: value = usd_type(value) else: value = usd_type(*value) elif og_type.array_depth > 0: # Special case string, path vs uchar[] if (og_type.base_type == og.BaseDataType.UCHAR) and (og_type.role != og.AttributeRole.NONE): return value vt_class = _usd_scaler_array_types[og_type.base_type] value = vt_class(value) return value return value # ============================================================================================================== def sync_to_usd(attribute: og.Attribute, value: Any): """This is necessary to update USD at the moment. Updating flatcache and USD should be a feature that can be accessed at the low level for efficiency (e.g. in the IAttributeData interface). """ # Delayed until here because the PYTHONPATH is not set the first time this file is imported import omni.usd stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(attribute.get_node().get_prim_path()) if prim.IsValid() and attribute.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: try: # The Set method wants USD types for some attribute types so do the translation first value = og.attribute_value_as_usd(og.Controller.attribute_type(attribute), value) prim.GetAttribute(attribute.get_name()).Set(value) except Tf.ErrorException as error: carb.log_warn(f"Could not sync USD on attribute {attribute.get_name()} - {error}") except TypeError as error: # TODO: This occurs when the parameters to Set() don't match what USD expects. It could be fixed # by special-casing every known mismatch but this section should be going away so it won't # be done at this time. The current known failures are the quaternion types and arrays of the # tuple-arrays (e.g. "quatd[4]", "double[3][]", "float[2][]", ...) carb.log_info(f"Could not set value on attribute {attribute.get_name()} - {error}") except Exception as error: # noqa: PLW0703 carb.log_warn(f"Unknown problem setting values - {error}") # ============================================================================================================== def remove_attributes_if( node: Nodes_t, attribute_filter_function: Optional[Callable[[og.Attribute], bool]] = None ) -> int: """Disconnects and removes the dynamic attributes on the given node which pass a given filter. Args: node: The node to remove attributes from attribute_filter_function: A function which returns True when given at prospective Attribute that should be removed. If None, all dynamic attributes will be removed. Returns: The number of attributes removed. """ nodes = ObjectLookup.node(node) if not isinstance(nodes, list): nodes = [nodes] if not attribute_filter_function: attribute_filter_function = og.Attribute.is_dynamic attrs_to_remove = [] for node_obj in nodes: attrs_to_remove += [attr for attr in node_obj.get_attributes() if attribute_filter_function(attr)] for attr in attrs_to_remove: og.cmds.DisconnectAllAttrs(attr=attr, modify_usd=True) for attr in attrs_to_remove: og.cmds.RemoveAttr(attribute=attr) return len(attrs_to_remove) # ============================================================================================================== def is_attribute_plain_data(attrib: Attribute_t) -> bool: """Is the given attribute is numeric or string data? Args: attrib: The attribute in question Returns: True if the given attribute is numeric or string data """ a = ObjectLookup.attribute(attrib) tp = a.get_resolved_type() # ignore anything that we can't usefully expose or is potentially an error if tp.role in ( og.AttributeRole.APPLIED_SCHEMA, og.AttributeRole.OBJECT_ID, og.AttributeRole.EXECUTION, og.AttributeRole.PRIM_TYPE_NAME, og.AttributeRole.UNKNOWN, ): return False if tp.base_type in ( og.BaseDataType.RELATIONSHIP, og.BaseDataType.TAG, og.BaseDataType.ASSET, og.BaseDataType.CONNECTION, og.BaseDataType.UNKNOWN, og.BaseDataType.PRIM, ): return False # Skip known special attributes name = a.get_name() if name in ("UsdPrim", "IsTerminalNode", "Mesh", "node:type", "node:typeVersion"): return False return True # ===================================================================== def graph_iterator(root: Optional[og.Graph] = None) -> Tuple[og.Graph, og.Graph]: """Generator function that provides the ability to walk through all graphs and their subgraphs in a manner similar to the os.walk function. The yield is the graph found at the current iteration step. It walks the graphs from the bottom up in a breadth-first way. Args: root: Starting graph - walk all graphs if None .. code-block:: python for graph in graph_iterator(): print(f"Walking over graph at {graph.get_path_to_graph()}") """ all_graphs = og.get_all_graphs() if root is None else [root] for root_graph in all_graphs: yield root_graph subgraphs = root_graph.get_subgraphs() if subgraphs: for subgraph in subgraphs: yield from graph_iterator(subgraph) # ============================================================================================================== @dataclass class GraphSettings: """Container for the set of settings in a graph. This is a class instead of a tuple so that future additions to the settings do not break backward compatibility """ evaluator_type: str = "push" file_format_version: Tuple[int, int] = (0, 0) fabric_backing: str = og.GraphBackingType.GRAPH_BACKING_TYPE_FLATCACHE_SHARED pipeline_stage: str = og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION evaluation_mode: str = og.GraphEvaluationMode.GRAPH_EVALUATION_MODE_STANDALONE # -------------------------------------------------------------------------------------------------------------- def get_graph_settings(graph: Graph_t) -> GraphSettings: """Return the current settings for the graph. This is just a copy of the settings. Changing it will not affect the graph's settings. To do that you must go through the graph ABI """ # Delayed until here because the PYTHONPATH is not set the first time this file is imported import omni.usd settings = GraphSettings() # The path to the settings prim is fixed if carb.settings.get_settings().get(og.USE_SCHEMA_PRIMS_SETTING): graph_prim = omni.usd.get_context().get_stage().GetPrimAtPath(graph.get_path_to_graph()) if not graph_prim.IsA(OmniGraphSchema.OmniGraph): carb.log_warn(f"Graph prim for {graph.get_path_to_graph()} not found - using default settings") else: graph_schema = OmniGraphSchema.OmniGraph(graph_prim) settings.evaluator_type = graph_schema.GetEvaluatorTypeAttr().Get() settings.file_format_version = graph_schema.GetFileFormatVersionAttr().Get() settings.fabric_backing = graph_schema.GetFabricCacheBackingAttr().Get() settings.pipeline_stage = graph_schema.GetPipelineStageAttr().Get() settings.evaluation_mode = graph_schema.GetEvaluationModeAttr().Get() else: settings_path = f"{graph.get_path_to_graph()}/computegraphSettings" settings_prim = omni.usd.get_context().get_stage().GetPrimAtPath(settings_path) if settings_prim.IsValid(): settings.evaluator_type = graph.get_evaluator_name() settings.file_format_version = settings_prim.GetAttribute("fileFormatVersion").Get() settings.fabric_backing = graph.get_graph_backing_type() settings.pipeline_stage = graph.get_pipeline_stage() settings.evaluation_mode = graph.evaluation_mode else: carb.log_warn(f"Settings for graph {graph.get_path_to_graph()} not found - using defaults") return settings _og_in_compute_count = 0 def _begin_in_compute(): """ Mark entry of OmniGraph runtime computation. Must be paired with a subsequent call to _end_in_compute() """ global _og_in_compute_count _og_in_compute_count = _og_in_compute_count + 1 def _end_in_compute(): """ Mark exit of OmniGraph runtime computation. Must be paired with a prior call to _begin_in_compute() """ global _og_in_compute_count if _og_in_compute_count > 0: _og_in_compute_count = _og_in_compute_count - 1 else: carb.log_error("undo.end_disabled() called without matching prior call to undo.begin_disabled()") @contextmanager def in_compute(): """Mark block of code executed at runtime. Optimizations can apply like setting values without undo support. This function is a context manager. Example: .. code-block:: python with omni.graph.in_compute(): exec(state._code_object) """ _begin_in_compute() try: yield finally: _end_in_compute() def is_in_compute() -> bool: """ Mark entry of OmniGraph runtime computation. """ return _og_in_compute_count > 0 # Deprecated as it was not being used and does nothing anyway # Deprecated as there is no longer the notion of a 'current' graph # ============================================================================================================== # Deprecated type information - use the values in typing.py (also in the omni.graph.core module) # (The "noqa" silences the linter's complaint that the import is unused.) from .v1_5_0.utils import ATTRIBUTE_TYPE_HINTS # noqa from .v1_5_0.utils import ATTRIBUTE_TYPE_OR_LIST # noqa from .v1_5_0.utils import ATTRIBUTE_TYPE_TYPE_HINTS # noqa from .v1_5_0.utils import ATTRIBUTE_VALUE_PAIR # noqa from .v1_5_0.utils import ATTRIBUTE_VALUE_PAIRS # noqa from .v1_5_0.utils import EXTENDED_ATTRIBUTE_TYPE_HINTS # noqa from .v1_5_0.utils import GRAPH_TYPE_HINTS # noqa from .v1_5_0.utils import GRAPH_TYPE_OR_LIST # noqa from .v1_5_0.utils import NODE_TYPE_HINTS # noqa from .v1_5_0.utils import NODE_TYPE_OR_LIST # noqa from .v1_5_0.utils import get_omnigraph # noqa from .v1_5_0.utils import l10n # noqa
34,999
Python
42.209876
120
0.604503
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/generate_ogn.py
"""Support for generating .ogn content from existing nodes""" import json from pathlib import Path from typing import Any, Dict, List, Tuple, Union import omni.graph.core as og import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn # ============================================================================================================== def __get_scheduling_hints(scheduling_hints: og.ISchedulingHints) -> Dict[str, Any]: """Returns the subsections of the node definition that define scheduling hints. Only non-defaults are included""" scheduling = [] if og.eThreadSafety.E_SAFE == scheduling_hints.thread_safety: scheduling.append(ogn.SchedulingHints.THREADSAFE) global_access = scheduling_hints.get_data_access(og.eAccessLocation.E_GLOBAL) if global_access == og.eAccessType.E_READ: scheduling.append(ogn.SchedulingHints.GLOBAL_DATA_READ) elif global_access == og.eAccessType.E_WRITE: scheduling.append(ogn.SchedulingHints.GLOBAL_DATA_WRITE) elif global_access == og.eAccessType.E_READ_WRITE: scheduling.append(ogn.SchedulingHints.GLOBAL_DATA) static_access = scheduling_hints.get_data_access(og.eAccessLocation.E_STATIC) if static_access == og.eAccessType.E_READ: scheduling.append(ogn.SchedulingHints.STATIC_DATA_READ) elif static_access == og.eAccessType.E_WRITE: scheduling.append(ogn.SchedulingHints.STATIC_DATA_WRITE) elif static_access == og.eAccessType.E_READ_WRITE: scheduling.append(ogn.SchedulingHints.STATIC_DATA) topology_access = scheduling_hints.get_data_access(og.eAccessLocation.E_TOPOLOGY) if topology_access == og.eAccessType.E_READ: scheduling.append(ogn.SchedulingHints.TOPOLOGY_DATA_READ) elif topology_access == og.eAccessType.E_WRITE: scheduling.append(ogn.SchedulingHints.TOPOLOGY_DATA_WRITE) elif topology_access == og.eAccessType.E_READ_WRITE: scheduling.append(ogn.SchedulingHints.TOPOLOGY_DATA) usd_access = scheduling_hints.get_data_access(og.eAccessLocation.E_USD) if usd_access == og.eAccessType.E_READ: scheduling.append(ogn.SchedulingHints.USD_DATA_READ) elif usd_access == og.eAccessType.E_WRITE: scheduling.append(ogn.SchedulingHints.USD_DATA_WRITE) elif usd_access == og.eAccessType.E_READ_WRITE: scheduling.append(ogn.SchedulingHints.USD_DATA) compute_rule = scheduling_hints.compute_rule if compute_rule == og.eComputeRule.E_ON_REQUEST: scheduling.append(ogn.SchedulingHints.COMPUTERULE_ON_REQUEST) return {ogn.NodeTypeKeys.SCHEDULING: scheduling} if scheduling else {} # ============================================================================================================== def __get_node_type_metadata(node_type: og.NodeType) -> Dict[str, Any]: """Returns the subsections of the node definition that come from its metadata""" full_data = {} metadata = {} icon_data = {} for key, value in node_type.get_all_metadata().items(): # Ignore internal metadata as it comes from other keywords if key.startswith("__"): continue # Description, tags, and UI Name are promoted to top level keys if key == ogn.MetadataKeys.DESCRIPTION: full_data[ogn.NodeTypeKeys.DESCRIPTION] = ogt.shorten_string_lines_to(value, 100) elif key == ogn.MetadataKeys.TAGS: full_data[ogn.NodeTypeKeys.TAGS] = value elif key == ogn.MetadataKeys.UI_NAME: full_data[ogn.NodeTypeKeys.UI_NAME] = value # Extension is part of the generated metadata and should not be in the file elif key == ogn.MetadataKeys.EXTENSION: pass # Language is only output if it is not the default C++ elif key == ogn.MetadataKeys.LANGUAGE: if value != ogn.LanguageTypeValues.CPP: full_data[ogn.NodeTypeKeys.LANGUAGE] = value # Icon metadata is added hierarchically elif key == ogn.MetadataKeys.ICON_BACKGROUND_COLOR: icon_data[ogn.IconKeys.BACKGROUND_COLOR] = value elif key == ogn.MetadataKeys.ICON_BORDER_COLOR: icon_data[ogn.IconKeys.BORDER_COLOR] = value elif key == ogn.MetadataKeys.ICON_COLOR: icon_data[ogn.IconKeys.COLOR] = value elif key == ogn.MetadataKeys.ICON_PATH: # Prune the path by assuming that it is in the same directory as the .ogn file icon_path = Path(value) icon_data[ogn.IconKeys.PATH] = f"{icon_path.stem.split('.')[-1]}{icon_path.suffix}" elif key == ogn.MetadataKeys.TOKENS: full_data[ogn.NodeTypeKeys.TOKENS] = json.loads(value) elif key == ogn.MetadataKeys.LANGUAGE: full_data[ogn.NodeTypeKeys.LANGUAGE] = value elif key == ogn.MetadataKeys.EXCLUSIONS: full_data[ogn.NodeTypeKeys.EXCLUDE] = value.split(",") elif key == ogn.MetadataKeys.MEMORY_TYPE: full_data[ogn.NodeTypeKeys.MEMORY_TYPE] = value # Anything else is plain old generic metadata else: metadata[key] = value # Insert the hierarchical metadata assembled from the list if metadata: full_data[ogn.NodeTypeKeys.METADATA] = metadata if icon_data: full_data[ogn.NodeTypeKeys.ICON] = icon_data return full_data # ============================================================================================================== def __get_attribute_metadata(attribute: og.Attribute) -> Dict[str, Any]: """Returns the subsections of the attribute definition that come from its metadata""" full_data = {} metadata = {} for key, value in attribute.get_all_metadata().items(): # Ignore internal metadata as it comes from other keywords if key.startswith("__"): continue # Description, tags, and UI Name are promoted to top level keys if key == ogn.MetadataKeys.DESCRIPTION: full_data[ogn.AttributeKeys.DESCRIPTION] = ogt.shorten_string_lines_to(value, 100) elif key == ogn.MetadataKeys.ALLOWED_TOKENS: # This is handled using the raw token data, to account for lists and dictionaries pass elif key == ogn.MetadataKeys.ALLOWED_TOKENS_RAW: metadata[ogn.AttributeKeys.ALLOWED_TOKENS] = json.loads(value) elif key == ogn.MetadataKeys.UI_NAME: full_data[ogn.AttributeKeys.UI_NAME] = value elif key == ogn.MetadataKeys.MEMORY_TYPE: full_data[ogn.AttributeKeys.MEMORY_TYPE] = value elif key == ogn.MetadataKeys.DEFAULT: full_data[ogn.AttributeKeys.DEFAULT] = json.loads(value) # Anything else is plain old generic metadata else: metadata[key] = value # Insert the hierarchical metadata assembled from the list if metadata: full_data[ogn.AttributeKeys.METADATA] = metadata return full_data # ============================================================================================================== def __get_attribute_type_information(attribute: og.Attribute) -> Union[str, List[str]]: """Returns the description of the attribute's type information required by OGN""" if attribute.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY: return "any" if attribute.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION: return attribute.get_union_types() return attribute.get_resolved_type().get_ogn_type_name() # ============================================================================================================== def __get_attribute_configuration(node: og.Node) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]: """Returns the three subsections describing the attributes in the list""" inputs = {} outputs = {} state = {} for attribute in node.get_attributes(): attribute_name = ogt.attribute_name_without_port(attribute.get_name()) # Ignore the schema attributes if attribute_name in ["node:type", "node:typeVersion"]: continue # Skip the automatically generated output bundle if attribute_name == node.get_prim_path().split("/")[-1]: continue port = attribute.get_port_type() if port == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT: attributes = inputs elif port == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT: attributes = outputs elif port == og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE: attributes = state else: # Non-standard attributes are not part of OGN continue attribute_detail = {ogn.AttributeKeys.TYPE: __get_attribute_type_information(attribute)} attribute_detail.update(__get_attribute_metadata(attribute)) if attribute.is_optional_for_compute: attribute_detail[ogn.AttributeKeys.OPTIONAL] = True attributes.update({attribute_name: attribute_detail}) return (inputs, outputs, state) # ============================================================================================================== def generate_ogn_from_node(node: og.Node) -> Dict[str, Any]: """Return a .ogn dictionary that implements the node type information contained in the given node""" ogn_data = {} # OM-41093 prevents using node_type.get_node_type() to extract the name from the ABI. Fortunately the # type is preserved in the node attributes. node_type = node.get_node_type() if node_type is None: raise ValueError(f"Node {node.get_prim_path()} did not have a recognized node type") node_type_name = node.get_attribute("node:type").get() ogn_data[ogn.NodeTypeKeys.VERSION] = og.GraphRegistry().get_node_type_version(node_type_name) ogn_data.update(__get_node_type_metadata(node_type)) ogn_data.update(__get_scheduling_hints(node_type.get_scheduling_hints())) (inputs, outputs, state) = __get_attribute_configuration(node) if inputs: ogn_data.update({ogn.NodeTypeKeys.INPUTS: inputs}) if outputs: ogn_data.update({ogn.NodeTypeKeys.OUTPUTS: outputs}) if state or node_type.has_state(): ogn_data.update({ogn.NodeTypeKeys.STATE: state}) return {node_type_name: ogn_data}
10,361
Python
46.315068
117
0.63131
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/node_controller.py
"""Helpers for modifying the contents of a node""" from typing import Any, Dict, List, Optional import omni.graph.core as og from .object_lookup import ObjectLookup from .typing import Attribute_t, AttributeType_t, ExtendedAttribute_t, Node_t from .utils import _flatten_arguments, _Unspecified # ============================================================================================================== class NodeController: """Helper class that provides a simple interface to modifying the contents of a node""" # -------------------------------------------------------------------------------------------------------------- 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. The argument is optional and there may be other arguments present that will be ignored Args: undoable (bool): If True the operations performed with this instance of the class are to be added to the undo queue, else they are done immediately and forgotten """ (self.__undoable,) = _flatten_arguments( optional=[("undoable", None)], args=args, kwargs=kwargs, ) # Dual function methods that can be called either from an object or directly from the class self.create_attribute = self.__create_attribute_obj self.remove_attribute = self.__remove_attribute_obj # ---------------------------------------------------------------------- # begin-create-attribute-function @classmethod def create_attribute(obj, *args, **kwargs) -> Optional[og.Attribute]: # noqa: N804, PLE0202, PLC0202 """Create a new dynamic attribute on the node 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: Node on which to create the attribute (path or og.Node) attr_name: Name of the new attribute, either with or without the port namespace attr_type: Type of the new attribute, as an OGN type string or og.Type attr_port: Port type of the new attribute, default is og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT attr_default: The initial value to set on the attribute, default is None which means use the type's default attr_extended_type: The extended type of the attribute, default is og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR. If the extended type is og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION then this parameter will be a 2-tuple with the second element being a list or comma-separated string of union types undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten Returns: The newly created attribute, None if there was a problem creating it """ # end-create-attribute-function return obj.__create_attribute(obj, args=args, kwargs=kwargs) def __create_attribute_obj(self, *args, **kwargs) -> Optional[og.Attribute]: """Implements :py:meth:`.NodeController.create_attribute` when called as an object method""" return self.__create_attribute(self, undoable=self.__undoable, args=args, kwargs=kwargs) @staticmethod def __create_attribute( obj, node: Node_t = _Unspecified, attr_name: str = _Unspecified, attr_type: AttributeType_t = _Unspecified, attr_port: Optional[og.AttributePortType] = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, attr_default: Optional[Any] = None, attr_extended_type: Optional[ExtendedAttribute_t] = og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, undoable: bool = True, args: List[Any] = None, kwargs: Dict[str, Any] = None, ) -> Optional[og.Attribute]: """Implements :py:meth:`.NodeController.create_attribute`""" (node, attr_name, attr_type, attr_port, attr_default, attr_extended_type, undoable) = _flatten_arguments( mandatory=[("node", node), ("attr_name", attr_name), ("attr_type", attr_type)], optional=[ ("attr_port", attr_port), ("attr_default", attr_default), ("attr_extended_type", attr_extended_type), ("undoable", undoable), ], args=args, kwargs=kwargs, ) omg_node = ObjectLookup.node(node) omg_attr_type = ObjectLookup.attribute_type(attr_type) if undoable: (success, _) = og.cmds.CreateAttr( node=omg_node, attr_name=attr_name, attr_type=omg_attr_type, attr_port=attr_port, attr_default=attr_default, attr_extended_type=attr_extended_type, ) else: success = True og.cmds.imm.CreateAttr( node=omg_node, attr_name=attr_name, attr_type=omg_attr_type, attr_port=attr_port, attr_default=attr_default, attr_extended_type=attr_extended_type, ) if not success: return None # The command didn't return the new attribute so it has to be looked up in the node namespace = og.get_port_type_namespace(attr_port) if not attr_name.startswith(namespace): if ( omg_attr_type.get_ogn_type_name() == "bundle" and attr_port != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ): separator = "_" else: separator = ":" attr_name = f"{namespace}{separator}{attr_name}" return omg_node.get_attribute(attr_name) # ---------------------------------------------------------------------- # begin-remove-attribute-function @classmethod def remove_attribute(obj, *args, **kwargs) -> bool: # noqa: N804,PLC0202,PLE0202 """Removes an existing dynamic attribute from a node. 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: Reference to the attribute to be removed node: If the attribute reference is a string the node is used to find the attribute to be removed undoable: If True the operation is added to the undo queue, else it is done immediately and forgotten Returns: True if the attribute was successfully removed, else False (including when the attribute wasn't found) """ # end-remove-attribute-function return obj.__remove_attribute(obj, args=args, kwargs=kwargs) def __remove_attribute_obj(self, *args, **kwargs) -> og.Graph: """Implements :py:meth:`.NodeController.remove_attribute` when called as an object method""" return self.__remove_attribute(self, undoable=self.__undoable, args=args, kwargs=kwargs) @staticmethod def __remove_attribute( obj, attribute: Attribute_t = _Unspecified, node: Node_t = None, undoable: bool = True, args: List[Any] = None, kwargs: Dict[str, Any] = None, ) -> bool: """Implements :py:meth:`.NodeController.remove_attribute`""" (attribute, node, undoable) = _flatten_arguments( mandatory=[("attribute", attribute)], optional=[("node", node), ("undoable", undoable)], args=args, kwargs=kwargs, ) omg_attribute = ObjectLookup.attribute(attribute, node) if undoable: (success, result) = og.cmds.RemoveAttr(attribute=omg_attribute) success = success and result else: success = True og.cmds.imm.RemoveAttr(attribute=omg_attribute) return success # ---------------------------------------------------------------------- @classmethod def safe_node_name(cls, node_type_name: str, abbreviated: bool = False) -> str: """Returns a USD-safe node name derived from the node_type_name Args: node_type_name: Fully namespaced name of the node type (e.g. omni.graph.nodes.Clamp) abbreviated: If True then remove the namespace, else just make the separators into underscores Returns: A safe node name that roughly corresponds to the given node type name """ if abbreviated: last_namespace = node_type_name.rfind(".") if last_namespace < 0: return node_type_name return node_type_name[last_namespace + 1 :] return node_type_name.replace(".", "_")
9,556
Python
46.785
119
0.59324
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/attribute_values.py
"""Getting and setting values for og.Attribute and og.AttributeData""" from enum import Enum, auto from typing import Any, Optional, Tuple import numpy as np import omni.graph.core as og import omni.graph.tools as ogt from .attribute_types import extract_attribute_type_information from .data_typing import DataWrapper, Device, data_shape_from_type from .typing import AttributeType_t, AttributeWithValue_t from .utils import ValueToSet_t, sync_to_usd # ============================================================================================================== class WrappedArrayType(Enum): """Enum for the type of array data returned from the get methods""" NUMPY = auto() # Wrapped in numpy.ndarray RAW = auto() # Wrapped in og.DataWrapper # ============================================================================================================== class AttributeDataValueHelper: """Class to manage getting and setting of og.AttributeData values. Note that this helper sets values directly and is not generally advised for use as it has no undo support. Instead you probably want to use og.Controller or og.DataView Internal Attributes: _data: The interface to the attribute data _type: The attribute type of the data (delay loaded to allow for extended types needing resolution) """ def __init__(self, data: AttributeWithValue_t): """Initialize the evaluation information for the AttributeData. Raises: TypeError if 'data' did not reference a correct attribute type """ if isinstance(data, og.Attribute): self._data = data.get_attribute_data() else: if not isinstance(data, og.AttributeData): raise TypeError("Only og.Attribute and og.AttributeData can be passed in") self._data = data self._type = None # ---------------------------------------------------------------------------------------------------- @property def is_valid(self) -> bool: """Returns whether the underlying API object is valid or not""" return self._data is not None and self._data.is_valid() # ---------------------------------------------------------------------------------------------------- @property def is_resolved(self) -> bool: """Returns whether the underlying API object has a resolved type.""" # Without attribute information we have to assume the type has been resolved return True # ---------------------------------------------------------------------------------------------------- def check_validity(self): """Raises an og.OmniGraphError exception if the data about to be accessed is invalid""" if not self.is_valid: if self.is_resolved: raise og.OmniGraphError("Attempted to access an invalid object") raise og.OmniGraphError("Tried to get the value from an unresolved attribute") # ---------------------------------------------------------------------------------------------------- @property def gpu_ptr_kind(self) -> og.PtrToPtrKind: """Returns the location of pointers to GPU arrays""" return self._data.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._data.gpu_ptr_kind = new_ptr_kind # ---------------------------------------------------------------------------------------------------- @property # noqa: A003 def type(self) -> og.Type: """Returns the attribute type, extracting it from the data if it hasn't already been done""" if self._type is None: self._type = extract_attribute_type_information(self._data) return self._type # ---------------------------------------------------------------------------------------------------- @property def attribute_data(self) -> og.AttributeData: """Returns the attribute data this helper is wrapping""" return self._data # ---------------------------------------------------------------------------------------------------- def set(self, new_value: ValueToSet_t, on_gpu: bool = False): # noqa: A003 """ Set the value of AttributeData Args: new_value: New value to be set on the attribute on_gpu: Should the value be stored on the GPU? Raises: TypeError: Raised if the data type of the attribute is not yet supported """ self.check_validity() _ = ogt.OGN_DEBUG and ogt.dbg(f"{self.__class__}.set({self._data.get_name()} = {new_value} GPU({on_gpu}))") if self.type.array_depth > 0 and isinstance(new_value, (list, np.ndarray)): self.reserve_element_count(len(new_value)) if len(new_value) == 0: return self._data.set(new_value, on_gpu=on_gpu) # ---------------------------------------------------------------------------------------------------- def get( self, on_gpu: bool = False, reserved_element_count: Optional[int] = None, return_type: Optional[WrappedArrayType] = None, ) -> Any: """ Get the value of this attribute data. Args: 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 Returns: Value of the attribute data Raises: AttributeError: If reserved_element_count or return_type are defined but the attribute is not an array type TypeError: Raised if the data type is not yet supported or the attribute type is not resolved """ self.check_validity() _ = ogt.OGN_DEBUG and ogt.dbg( f"AttributeDataValueHelper.get({self._data.get_name()} GPU({on_gpu})" f" RESERVED({reserved_element_count}) TYPE({return_type}))" ) if self.type.array_depth > 0: writing = reserved_element_count is not None and reserved_element_count > 0 raw_data = self._data.get_array( on_gpu=on_gpu, get_for_write=writing, reserved_element_count=reserved_element_count if writing else 0, ) if return_type is None: return_type = WrappedArrayType.RAW if on_gpu else WrappedArrayType.NUMPY if return_type == WrappedArrayType.NUMPY: if on_gpu: raise TypeError("numpy data cannot be returned for GPU data") return raw_data if not on_gpu: raise TypeError("Only numpy data can be returned for CPU data") (memory_location, element_count) = raw_data (dtype, shape) = data_shape_from_type(self.type) # The array size was a placeholder; put the real size in _, *shape_info = shape shape = (element_count, *shape_info) return DataWrapper(memory_location, dtype, shape, Device("cuda"), self.gpu_ptr_kind) # While we could recover from these bad parameters we don't want to encourage their incorrect use if reserved_element_count is not None: raise AttributeError( f"Specified a reserved element count of {reserved_element_count} on" f" non-array attribute {self._data.get_name()}" ) if return_type is not None: raise AttributeError( f"Return types like {return_type} are not legal on non-array attribute {self._data.get_name()}" ) raw_data = self._data.get(on_gpu=on_gpu) if on_gpu: (dtype, shape) = data_shape_from_type(self.type) return DataWrapper(raw_data, dtype, shape, Device("cuda"), self.gpu_ptr_kind) return raw_data # ---------------------------------------------------------------------------------------------------- def get_array_size(self) -> int: """ Get the length of this attribute data's array. Returns: Length of the data array in FlatCache Raises: AttributeError: If the array is not an array type """ self.check_validity() _ = ogt.OGN_DEBUG and ogt.dbg(f"AttributeDataValueHelper.get_array_size({self._data.get_name()}") if self.type.array_depth == 0: raise AttributeError(f"Attempted to get array size of non-array attribute {self._data.get_name()}") return self._data.size() # ---------------------------------------------------------------------------------------------------- def reserve_element_count(self, new_element_count: int): """ Set the length of this attribute data's array. It doesn't matter whether the data will be on the GPU or CPU, all this does is reserve the size number. When retrieving the data you will specify where it lives. Args: new_element_count: Number of array elements to reserve for the array Raises: AttributeError: If the array is not an array type """ self.check_validity() _ = ogt.OGN_DEBUG and ogt.dbg(f"AttributeDataValueHelper.reserve_element_count({self._data.get_name()}") if self.type.array_depth == 0: raise AttributeError(f"Attempted to set array size of non-array attribute {self._data.get_name()}") self._data.resize(new_element_count) # ---------------------------------------------------------------------------------------------------- @ogt.deprecated_function("After version 1.5.0 use get() instead") def get_array( self, get_for_write: bool, reserved_element_count: int = 0, on_gpu: bool = False, return_type: Optional[WrappedArrayType] = None, ) -> Any: """Deprecated - use get()""" coded_count = reserved_element_count if get_for_write else None return self.get(on_gpu=on_gpu, reserved_element_count=coded_count, return_type=return_type) # ==================================================================================================== class AttributeValueHelper(AttributeDataValueHelper): """Class to manage getting and setting of og.Attribute values. You can also just use AttributeDataValueHelper directly. """ def __init__(self, attribute: og.Attribute): """Initialize the evaluation information for the Attribute""" super().__init__(attribute) self.__attribute = attribute # ---------------------------------------------------------------------------------------------------- @property def attribute(self) -> og.Attribute: """Returns the attribute this helper is wrapping""" return self.__attribute # ---------------------------------------------------------------------------------------------------- @property def is_resolved(self) -> bool: """Returns whether the underlying attribute has a resolved type.""" return ( self.__attribute is not None and self.__attribute.is_valid() and self.__attribute.get_resolved_type().base_type != og.BaseDataType.UNKNOWN ) # ---------------------------------------------------------------------------------------------------- @property def is_valid(self) -> bool: """Returns whether the underlying API object is valid or not""" return self.__attribute is not None and self.__attribute.is_valid() and super().is_valid # ---------------------------------------------------------------------------------------------------- @property # noqa: A003 def type(self) -> og.Type: """Returns the attribute type, extracting it from the data if it hasn't already been done""" if self._type is None: self._type = extract_attribute_type_information(self.__attribute) return self._type # ---------------------------------------------------------------------------------------------------- def resolve_type(self, type_id: AttributeType_t): """Resolves the attribute type, usually before setting an explicit value. Args: type: Attribute type to which the attribute will be resolved. Raises: og.OmniGraphError: If the attribute could not (or should not) be resolved """ if self.__attribute.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: raise og.OmniGraphError( f"Attempted to resolve non-extended attribute {self.__attribute.get_name()} to {type_id}" ) value_type = og.ObjectLookup.attribute_type(type_id) resolved_type = self.__attribute.get_resolved_type() # No need to do anything if the resolved type is already the desired one if value_type != resolved_type: # Unresolve first to ensure the new type resolution happens properly self.__attribute.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN)) self.__attribute.set_resolved_type(value_type) # Resolving the type changes the data information so fix it up self._type = None self._data = self.__attribute.get_attribute_data() # ---------------------------------------------------------------------------------------------------- def set(self, new_value: ValueToSet_t, on_gpu: bool = False, update_usd: bool = False): # noqa: A003 """ Set the value of the attribute. This is overridden so that it can include an explicit type for the data, which can be used to resolve the attribute type (only valid for extended types) Args: new_value: New value to be set on the attribute on_gpu: Should the value be stored on the GPU? update_usd: Should the value be immediately propagated to USD? Raises: TypeError: Raised if the data type of the attribute is not yet supported """ _ = ogt.OGN_DEBUG and ogt.dbg(f"AttributeValueHelper.set({self._data.get_name()} = {new_value} GPU({on_gpu}))") def __get_type_and_value(value_information: ValueToSet_t) -> Optional[Tuple[Any, str]]: """Extracts type and value information from the data, or None if it's just a value with no type. Raises og.OmniGraphError if the dictionary or tuple types were not legal. Returns None if the value had no type encoding. """ if isinstance(value_information, dict): if len(value_information) != 2 or "type" not in value_information or "value" not in value_information: raise og.OmniGraphError( f"Explicit type dictionary must contain 'type' and 'value' only - get {value_information}" ) return (value_information["value"], value_information["type"]) if isinstance(value_information, og.TypedValue): return (value_information.value, value_information.type) return None # First set the resolved type, if setting a type was requested try: encoded_value = __get_type_and_value(new_value) if encoded_value is not None: (new_value, value_type_id) = encoded_value self.resolve_type(value_type_id) except og.OmniGraphError as error: raise TypeError() from error # This could have also called the parent class set() but that doesn't send out notifications to the graph # so it must handle it. self.check_validity() if self.type.array_depth > 0 and isinstance(new_value, (list, np.ndarray)): self.reserve_element_count(len(new_value)) if len(new_value) == 0: return self.__attribute.set(new_value, on_gpu=on_gpu) if update_usd and self.__attribute.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: # TODO: This is necessary to update USD at the moment. It would be more efficient if this were handled # at the fabric level, or at least at the Attribute or AttributeData level. sync_to_usd(self.__attribute, new_value)
16,578
Python
45.052778
120
0.544698
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/versions.py
"""Management of version compatibility information for the extensions (where not handled by the extension manager)""" from enum import Enum, auto from typing import Tuple import carb import omni.kit.app # Version information returned from the extension manager VersionType = Tuple[int, int, int, str, str] class Compatibility(Enum): """Potential types of version compatibility""" Incompatible = auto() FullyCompatible = auto() MajorVersionCompatible = auto() # Cached values for the current generator and target versions __CURRENT_GENERATOR_VERSION = None __CURRENT_TARGET_VERSION = None # ================================================================================ def get_generator_extension_version() -> VersionType: """Returns the current version of the extension omni.graph.tools, raising AttributeError if it could not be found since the fact that this script is running dictates that there should be a valid enabled version of this extension. """ global __CURRENT_GENERATOR_VERSION if __CURRENT_GENERATOR_VERSION is None: enabled_version = None mgr = omni.kit.app.get_app().get_extension_manager() for version in mgr.fetch_extension_versions("omni.graph.tools"): if version["enabled"]: enabled_version = version["version"] if enabled_version is None: carb.log_error("Failed to get the generator extension version") __CURRENT_GENERATOR_VERSION = (0, 0, 0, "", "Unknown") else: __CURRENT_GENERATOR_VERSION = enabled_version return __CURRENT_GENERATOR_VERSION # ================================================================================ def get_target_extension_version() -> VersionType: """Returns the current version of the extension omni.graph.core, raising AttributeError if it could not be found since the fact that this script is running dictates that there should be a valid enabled version of this extension. """ global __CURRENT_TARGET_VERSION if __CURRENT_TARGET_VERSION is None: enabled_version = None mgr = omni.kit.app.get_app().get_extension_manager() for version in mgr.fetch_extension_versions("omni.graph.core"): if version["enabled"]: enabled_version = version["version"] if enabled_version is None: carb.log_error("Failed to get the target extension version") __CURRENT_TARGET_VERSION = (0, 0, 0, "", "Unknown") else: __CURRENT_TARGET_VERSION = enabled_version return __CURRENT_TARGET_VERSION # ============================================================================================================== def check_version_compatibility(generator_version: VersionType, target_version: VersionType) -> Compatibility: """Checks to see how compatible the given versions are against the current extension versions enabled""" def __version_compatibility(actual_version: VersionType, expected_version: VersionType) -> Compatibility: """Returns the compatibility of the two versions, assumed to reference the same extension""" if actual_version[0] != expected_version[0]: return Compatibility.Incompatible if actual_version[1] != expected_version[1]: return Compatibility.MajorVersionCompatible return Compatibility.FullyCompatible # The target must at least be ABI compatible or we have real trouble if __version_compatibility(target_version, get_target_extension_version()) == Compatibility.Incompatible: return Compatibility.Incompatible # After that the generator is the one that determines what to do next with the generated file return __version_compatibility(generator_version, get_generator_extension_version())
3,826
Python
44.023529
119
0.651856
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/extension_information.py
"""Helper to manage information about nodes, node types and their extensions""" import json import os from collections import defaultdict from typing import Dict, List, Tuple import omni.ext import omni.graph.core as og import omni.kit import omni.usd class ExtensionInformation: """Class that manages information about the relationships between nodes and node types, and extensions Public Interface: get_node_types_by_extension() get_nodes_by_extension() """ # The extension name used when a node type cannot be found in the known extension list KEY_UNKNOWN_EXTENSION = "Unknown" def __init__(self): """Initialize the caches to be empty""" self.__known_extensions = None # If any extension configurations change the answers change so invalidate the locally cached results # when that happens. hooks = omni.kit.app.get_app_interface().get_extension_manager().get_hooks() self.__extension_enabled_hook = hooks.create_extension_state_change_hook( self.__reset_internal_cache, omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE ) assert self.__extension_enabled_hook self.__extension_disabled_hook = hooks.create_extension_state_change_hook( self.__reset_internal_cache, omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_DISABLE ) assert self.__extension_disabled_hook # ---------------------------------------------------------------------- def __reset_internal_cache(self, ext_id: str, *_): """Reset the internal cache so that it can be rebuilt later on demand""" self.__known_extensions = None # ---------------------------------------------------------------------- def __get_extensions_matching_node_types(self) -> Dict[str, Dict]: """Extract the set of node names per extension from the OGN data stored in the extension. The data will be in the file ogn/nodes.json in the root extension directory. It contains various information about the nodes in the extension as follows: { "nodes": [ { "name": FULL_NAME_OF_NODE, "version": VERSION_NUMBER_OF_NODE, "description": FULL_DESCRIPTION_OF_NODE } ] } The returned information is a combination of node_type:extension and extension:node_type dictionaries, with a special entry in the latter to indicate whether the extension is currently enabled or not. { "extensions": { "omni.graph.nodes": { "enabled": true, "nodes": ["omni.graph.node.A", "omni.graph.node.B"] } }, "nodes": { "omni.graph.node.A": "omni.graph.nodes", "omni.graph.node.B": "omni.graph.nodes" } } """ if self.__known_extensions is None: # noqa: PLR1702 extension_per_node_type = {} self.__known_extensions = defaultdict(dict) manager = omni.kit.app.get_app_interface().get_extension_manager() for extension in manager.get_extensions(): node_types_per_extension = [] # If the generated node information exists, use it node_information = os.path.join(extension["path"], "ogn", "nodes.json") if os.path.isfile(node_information): with open(node_information, "r", encoding="utf-8") as node_fd: node_data = json.load(node_fd) node_types_per_extension = list(node_data["nodes"].keys()) # If there is no generated information some nodes can still be found by searching the path elif os.path.isdir(extension["path"]): for root, dirs, _ in os.walk(extension["path"]): if "ogn" in dirs: ogn_dir = os.path.join(root, "ogn") for ogn_root, _, ogn_files in os.walk(ogn_dir, followlinks=True): for file_name in ogn_files: _, ext = os.path.splitext(file_name) if ext == ".ogn": ogn_file = os.path.join(ogn_root, file_name) with open(ogn_file, "r", encoding="utf-8") as ogn_fd: ogn_json = json.load(ogn_fd) node_name = list(ogn_json.keys())[0] if node_name.find(".") < 0: node_name = f"{extension['name']}.{node_name}" node_types_per_extension.append(node_name) break if node_types_per_extension: self.__known_extensions["extensions"][extension["name"]] = { "enabled": extension["enabled"], "nodes": node_types_per_extension, } extension_per_node_type.update( {node_type: extension["name"] for node_type in node_types_per_extension} ) self.__known_extensions["nodes"] = extension_per_node_type # Prims may have node types attached to them that are not known to OmniGraph. They should not be in any # of the known extensions, though that will be checked just in case something wasn't created properly. prim_node_types = [] for _, node_type_name in self.__get_prims_with_node_types().items(): if node_type_name in extension_per_node_type: continue prim_node_types.append(node_type_name) if prim_node_types: self.__known_extensions["extensions"][self.KEY_UNKNOWN_EXTENSION] = { "enabled": False, "nodes": prim_node_types, } return dict(self.__known_extensions) # ---------------------------------------------------------------------- def get_node_types_by_extension(self) -> Dict[str, List[str]]: """Returns a tuple of two dictionaries. The first is the dictionary of enabled extensions to the list of nodes in the scene whose node types they implement, the second is the same thing for disabled extensions.""" mapping_information = self.__get_extensions_matching_node_types()["extensions"] return ( {extension: value["nodes"] for extension, value in mapping_information.items() if value["enabled"]}, {extension: value["nodes"] for extension, value in mapping_information.items() if not value["enabled"]}, ) # ---------------------------------------------------------------------- def __get_prims_with_node_types(self) -> Dict[str, str]: """Returns a dictionary of non-OmniGraph prims that have the node:type attribute set. These occur when the extension that created them is entirely unknown, possibly because it has not been installed. """ prims_with_node_types = {} for prim in omni.usd.get_context().get_stage().TraverseAll(): prim_path = str(prim.GetPath()) node_type_attribute = prim.GetAttribute("node:type") if node_type_attribute: prims_with_node_types[prim_path] = node_type_attribute.Get() return prims_with_node_types # ---------------------------------------------------------------------- def get_nodes_by_extension(self) -> Tuple[Dict[str, List[str]], Dict[str, List[str]]]: """Returns a tuple of three dictionaries. - Map of enabled extensions to the list of nodes in the scene whose node types they implement - Map of disabled extensions to the list of nodes in the scene whose node types they implement""" mapping_information = self.__get_extensions_matching_node_types() node_type_extensions = mapping_information["nodes"] enabled_extensions = [ extension for extension, value in mapping_information["extensions"].items() if value["enabled"] ] node_extensions_enabled = defaultdict(list) node_extensions_disabled = defaultdict(list) # Next walk all of the OmniGraph graphs to find nodes known to it nodes_found = {} for graph in og.get_all_graphs(): nodes_in_graph = graph.get_nodes() for node in nodes_in_graph: node_type_name = node.get_node_type().get_node_type() if node_type_name is None: # This came from an unloaded extension, but it will still have the node type information node_type_name = og.Controller.get(og.Controller.attribute(("node:type", node))) try: extension = node_type_extensions[node_type_name] except KeyError: extension = self.KEY_UNKNOWN_EXTENSION if extension in enabled_extensions: node_extensions_enabled[extension].append(str(node.get_prim_path())) else: node_extensions_disabled[extension].append(str(node.get_prim_path())) nodes_found[str(node.get_prim_path())] = extension # If any of the prims haven't been found in the OmniGraph traversal, check them for the telltale # "node:type" attribute that is present in all OmniGraph nodes and add them to the unknown extension category for prim_path, node_type_name in self.__get_prims_with_node_types().items(): if prim_path in nodes_found: continue try: extension = mapping_information["nodes"][node_type_name] except KeyError: extension = self.KEY_UNKNOWN_EXTENSION if extension in enabled_extensions: node_extensions_enabled[extension].append(prim_path) else: node_extensions_disabled[extension].append(prim_path) return (dict(node_extensions_enabled), dict(node_extensions_disabled))
10,463
Python
50.80198
117
0.549842
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/settings.py
"""Management for the OmniGraph settings. The setting can be checked directly using this model: import omni.graph.core as og if og.Settings()(og.Settings.MY_SETTING_NAME): # the setting value is True (for a boolean setting) else: # the setting value if False You can also use the class as a context manager to temporarily modify the setting: import omni.graph.core as og while og.Settings.temporary(og.Settings.MY_SETTING_NAME, False): # Do something that needs the setting off """ from contextlib import contextmanager from dataclasses import dataclass from typing import Any import carb import omni.graph.tools as ogt @dataclass class Settings: """Class that packages up all of the OmniGraph settings handling into a common location. The settings themselves are handled through the Carbonite settings ABI, this just provides a nicer and more focused interface. Values here should also be reflected in the C++ OmniGraphSettings class. """ ALLOW_IMPLICIT_GRAPH: str = "/persistent/omnigraph/allowGlobalImplicitGraph" """Constant for the setting to selectively disable the global implicit graph""" USE_SCHEMA_PRIMS: str = "/persistent/omnigraph/useSchemaPrims" """Constant for the setting to force OmniGraph prims to follow the schema""" ENABLE_LEGACY_PRIM_CONNECTIONS: str = "/persistent/omnigraph/enableLegacyPrimConnections" """Constant for the setting to enable connections between legacy Prims and OG Nodes""" DISABLE_PRIM_NODES: str = "/persistent/omnigraph/disablePrimNodes" """Constant for the setting to enable legacy Prim nodes to exist in the scene""" VERSION: str = "/persistent/omnigraph/settingsVersion" """Version number of these settings""" DEFAULT_EVALUATOR: str = "/persistent/omnigraph/defaultEvaluator" """Default evaluator type for new graphs""" PRIM_NODES: str = "/persistent/omnigraph/createPrimNodes" """Allow creation of the deprecated Prim node type""" UPDATE_TO_USD: str = "/persistent/omnigraph/updateToUsd" """Always update changes in OmniGraph to USD (can be slow)""" UPDATE_MESH_TO_HYDRA: str = "/persistent/omnigraph/updateMeshPointsToHydra" """Update mesh points directly to Hydra""" USE_DYNAMIC_SCHEDULER: str = "/persistent/omnigraph/useDynamicScheduler" """Force use of the dynamic scheduler""" REALM_ENABLED: str = "/persistent/omnigraph/realmEnabled" """Enable use of Realm for scheduling""" CACHED_CONNECTIONS_IN_FILE: str = "/persistent/omnigraph/useCachedConnectionsForFileLoad" """Use USD metadata with connection information as a cache to speed up file load""" USE_LEGACY_PIPELINE: str = "/persistent/omnigraph/useLegacySimulationPipeline" """Use the pre-1.3 simulation pipeline rather than the orchestration graph""" ENABLE_LEGACY_GRAPH_EDITOR: str = "REMOVED" """This setting has been removed""" PLAY_COMPUTE_GRAPH: str = "/app/player/playComputegraph" """Evaluate OmniGraph when the Kit 'Play' button is pressed""" OPTIMIZE_GENERATED_PYTHON: str = "/persistent/omnigraph/generator/pyOptimize" """Optimize the Python code being output by the node generator""" ENABLE_PATH_CHANGED_CALLBACK: str = "/persistent/omnigraph/enablePathChangedCallback" """Enable the deprecated Node.pathChangedCallback. This will affect performance.""" DEPRECATIONS_ARE_ERRORS: str = "/persistent/omnigraph/deprecationsAreErrors" """Modify deprecation paths to raise errors or exceptions instead of logging warnings.""" DISABLE_INFO_NOTICE_HANDLING_IN_PLAYBACK = "/persistent/omnigraph/disableInfoNoticeHandlingInPlayback" """Disable all processing of info-only notices by OG. This is an optimization for applications which do not require any triggering of OG via USD (value_changed and path_changed callbacks, lazy-graph etc""" ENABLE_USD_IN_PRERENDER = "/persistent/omnigraph/enableUSDInPreRender" """Enable nodes that read USD data to be safely used within a pre-render graph""" # -------------------------------------------------------------------------------------------------------------- def __str__(self) -> str: """Returns a representation of all current settings""" settings = carb.settings.get_settings() return "\n".join( [ f"{name} = {settings.get(field.default)}" for name, field in self.__dataclass_fields__.items() # noqa: PLE1101 ] ) # -------------------------------------------------------------------------------------------------------------- def __call__(self, setting_name: str) -> Any: """Look up and return the current value of the passed-in setting Call as og.Settings()(og.Settings.UPDATE_TO_USD)""" return carb.settings.get_settings().get(setting_name) # -------------------------------------------------------------------------------------------------------------- @staticmethod def generator_settings() -> ogt.Settings: """Return the generator settings object corresponding to the current carb settings""" settings = ogt.Settings() carb_settings = carb.settings.get_settings() for setting_name in settings.all().keys(): if carb_settings.get(f"/persistent/omnigraph/generator/{setting_name}"): setattr(settings, setting_name, True) return settings # -------------------------------------------------------------------------------------------------------------- @staticmethod @contextmanager def temporary(setting_name: str, setting_value: Any): """Generator to temporarily use a new setting value with og.Settings.temporary(og.Settings.ALLOW_IMPLICIT_GLOBAL_GRAPH, True): do_something_that_needs_global_graph() """ settings = carb.settings.get_settings() original_setting = settings.get(setting_name) try: settings.set(setting_name, setting_value) yield finally: settings.set(setting_name, original_setting)
6,145
Python
43.215827
116
0.649797
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/typing.py
"""Houses all of the type definitions for the various interface argument types. For clarity these types are stored in a structure that gives them a unified naming: .. code-block:: python from omni.graph.core.typing import NodeSpec_t def get_node(node_spec: NodeSpec_t): pass The convention used is that X_t is a singular item and Xs_t is a union of the singular item and a list of them. """ from typing import Any, Dict, List, Tuple, Union import omni.graph.core as og from pxr import Sdf, Usd # ====================================================================== # Values for type hints on methods that take a variety of convertible types as parameters Graph_t = Union[str, Sdf.Path, og.Graph] """Typing that identifies an existing omni.graph.core.Graph object""" Graphs_t = Union[Graph_t, List[Graph_t]] """Typing that identifies a list of existing omni.graph.core.Graph objects""" # Added specs for consistency, though for graphs no extra information is currently needed to identify them GraphSpec_t = Graph_t """Typing that identifies an existing omni.graph.core.Graph object""" GraphSpecs_t = Graphs_t """Typing that identifies a list of existing omni.graph.core.Graph objects""" NewNode_t = Union[str, Sdf.Path, Tuple[str, og.Graph]] """Typing for information required to create a new node""" Node_t = Union[str, og.Node, Sdf.Path, Usd.Prim, Usd.Typed] """Typing that identifies an existing omni.graph.core.Node object""" Nodes_t = Union[Node_t, List[Node_t]] """Typing that identifies a list of existing omni.graph.core.Node objects""" NodeSpec_t = Union[Node_t, Tuple[str, GraphSpec_t]] """Typing that identifies an existing omni.graph.core.Node object, with optional graph for disambiguation""" NodeSpecs_t = Union[NodeSpec_t, List[NodeSpec_t]] """Typing that identifies a list of existing omni.graph.core.Node objects, with optional graph for disambiguation""" NodeType_t = Union[str, og.NodeType, og.Node, Usd.Prim, Usd.Typed] """Typing that identifies an existing omni.graph.core.NodeType object""" NodeTypes_t = Union[NodeType_t, List[NodeType_t]] """Typing that identifies a list of existing omni.graph.core.NodeType objects""" Attribute_t = Union[str, Sdf.Path, og.Attribute, Usd.Attribute] """Typing that identifies an existing omni.graph.core.Attribute object""" Attributes_t = Union[Attribute_t, List[Attribute_t]] """Typing that identifies a list of existing omni.graph.core.Attribute objects""" AttributeWithValue_t = Union[Attribute_t, og.AttributeData] """Typing for an attribute-like object that references a value in FlatCache""" AttributesWithValues_t = Union[AttributeWithValue_t, List[AttributeWithValue_t]] """Typing for a list of attribute-like objects that reference values in FlatCache""" AttributeType_t = Union[str, og.Type] """Typing that identifies an existing omni.graph.core.Type definition""" ExtendedAttribute_t = Union[og.AttributePortType, Tuple[og.AttributePortType, Union[str, List[str]]]] """Typing for an extended attribute type description""" Path_t = Union[str, Sdf.Path] """Typing for a path in the USD stage""" Prim_t = Union[str, Sdf.Path, og.Node, Usd.Prim, Usd.Typed] """Typing for an existing USD prim""" Prims_t = Union[Prim_t, List[Prim_t]] """Typing for a list of existing USD prims""" PrimAttrs_t = Dict[str, Tuple[Union[str, og.Type], Any]] """Typing for a description of attribute values for a prim - a dictionary of name:(type,value)""" CreatePrim_t = Tuple[Path_t, PrimAttrs_t] """Typing for information required to create a prim with a predefined set of values""" CreatePrimst_t = Union[CreatePrim_t, List[CreatePrim_t]] """Typing for information required to create a list of prims with a predefined set of values""" # An attribute that is either unique by itself or which has optional node and graph parts to help look it up. # This would be passed in as arguments to a function that needs to uniquely identify an existing attribute. # It differs from a regular attribute in allowing a relative path to the attribute within the node/graph AttributeSpec_t = Union[og.Attribute, str, Sdf.Path, Tuple[str, Node_t], Tuple[str, Node_t, Graph_t]] """Typing for information required to identify an existing og.Attribute""" AttributeSpecs_t = Union[AttributeSpec_t, List[AttributeSpec_t]] """Typing for information required to identify a list of existing og.Attributes""" VariableName_t = str """Typing information required to specify a variable name""" VariableType_t = Union[str, og.Type] """Typing information required to specify a variable type""" Variable_t = Union[og.IVariable, Tuple[GraphSpec_t, VariableName_t]] """Typing information required to specify a variable""" Variables_t = Union[Variable_t, List[Variable_t]] """Typing information required to specify a list of variable"""
4,786
Python
48.350515
116
0.744672
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/dtypes.py
"""This file contains the implementation for the dtype information describing Python data types. It's mostly a repackaging of the information understood by OGN and FlatCache of the supported data types. They can be passed around to provide identification of data whose type is not explicit, or ambiguous. (e.g. a Python int is used to represent all of the integer and unsigned integer types so these types can disambiguate) The dtype information is analagous to the dtype information in numpy, just tuned to our particular data types. All of these types are exported into the omni.graph.core namespace so type names are generic. Typical usage is: import omni.graph.core as og my_float3_type = og.Float3 """ import ctypes from dataclasses import dataclass from typing import Optional import omni.graph.core as og # ============================================================================================================== @dataclass class Dtype: """Common base type for dtypes, defining the members each needs to populate tuple_count (int): The number of atomic elements in this type size (int): The total size in bytes of this type base_type (og.BaseDataType): The base data type of this type ctype (object): The ctypes representation used by this data type in FlatCache """ tuple_count: Optional[int] = None size: Optional[int] = None base_type: Optional[int] = None ctype: Optional[object] = None @classmethod def is_matrix_type(cls) -> bool: """Returns true if the dtype is a matrix. Uses derived class knowledge to keep it simple""" return hasattr(cls, "matrix_dim") # ============================================================================================================== @dataclass class Bool(Dtype): tuple_count: int = 1 size: int = 1 base_type: og.BaseDataType = og.BaseDataType.BOOL ctype: object = ctypes.c_bool # ============================================================================================================== # TODO: Really the bundle should have an identifying role as well so that it can be more easily identified. # Neither RELATIONSHIP nor PRIM speak to what the intended type is. @dataclass class BundleInput(Dtype): tuple_count: int = 1 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.RELATIONSHIP ctype: object = ctypes.c_uint64 # ============================================================================================================== @dataclass class BundleOutput(Dtype): tuple_count: int = 1 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.PRIM ctype: object = ctypes.c_uint64 # ============================================================================================================== @dataclass class Double(Dtype): tuple_count: int = 1 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.DOUBLE ctype: object = ctypes.c_double # -------------------------------------------------------------------------------------------------------------- @dataclass class Double2(Dtype): tuple_count: int = 2 size: int = 16 base_type: og.BaseDataType = og.BaseDataType.DOUBLE ctype: object = ctypes.c_double # -------------------------------------------------------------------------------------------------------------- @dataclass class Double3(Dtype): tuple_count: int = 3 size: int = 24 base_type: og.BaseDataType = og.BaseDataType.DOUBLE ctype: object = ctypes.c_double # -------------------------------------------------------------------------------------------------------------- @dataclass class Double4(Dtype): tuple_count: int = 4 size: int = 32 base_type: og.BaseDataType = og.BaseDataType.DOUBLE ctype: object = ctypes.c_double # ============================================================================================================== @dataclass class Float(Dtype): tuple_count: int = 1 size: int = 4 base_type: og.BaseDataType = og.BaseDataType.FLOAT ctype: object = ctypes.c_float # -------------------------------------------------------------------------------------------------------------- @dataclass class Float2(Dtype): tuple_count: int = 2 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.FLOAT ctype: object = ctypes.c_float # -------------------------------------------------------------------------------------------------------------- @dataclass class Float3(Dtype): tuple_count: int = 3 size: int = 12 base_type: og.BaseDataType = og.BaseDataType.FLOAT ctype: object = ctypes.c_float # -------------------------------------------------------------------------------------------------------------- @dataclass class Float4(Dtype): tuple_count: int = 4 size: int = 16 base_type: og.BaseDataType = og.BaseDataType.FLOAT ctype: object = ctypes.c_float # ============================================================================================================== @dataclass class Half(Dtype): tuple_count: int = 1 size: int = 2 # Physically this is a 2-byte int, but the size implication is the same for a 2-byte float base_type: og.BaseDataType = og.BaseDataType.HALF ctype: object = ctypes.c_ushort # -------------------------------------------------------------------------------------------------------------- @dataclass class Half2(Dtype): tuple_count: int = 2 size: int = 4 base_type: og.BaseDataType = og.BaseDataType.HALF ctype: object = ctypes.c_ushort # -------------------------------------------------------------------------------------------------------------- @dataclass class Half3(Dtype): tuple_count: int = 3 size: int = 6 base_type: og.BaseDataType = og.BaseDataType.HALF ctype: object = ctypes.c_ushort # -------------------------------------------------------------------------------------------------------------- @dataclass class Half4(Dtype): tuple_count: int = 4 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.HALF ctype: object = ctypes.c_ushort # ============================================================================================================== @dataclass class Int(Dtype): tuple_count: int = 1 size: int = 4 base_type: og.BaseDataType = og.BaseDataType.INT ctype: object = ctypes.c_int # -------------------------------------------------------------------------------------------------------------- @dataclass class Int2(Dtype): tuple_count: int = 2 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.INT ctype: object = ctypes.c_int # -------------------------------------------------------------------------------------------------------------- @dataclass class Int3(Dtype): tuple_count: int = 3 size: int = 12 base_type: og.BaseDataType = og.BaseDataType.INT ctype: object = ctypes.c_int # -------------------------------------------------------------------------------------------------------------- @dataclass class Int4(Dtype): tuple_count: int = 4 size: int = 16 base_type: og.BaseDataType = og.BaseDataType.INT ctype: object = ctypes.c_int # -------------------------------------------------------------------------------------------------------------- @dataclass class Int64(Dtype): tuple_count: int = 1 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.INT64 ctype: object = ctypes.c_longlong # ============================================================================================================== @dataclass class Matrix2d(Dtype): tuple_count: int = 4 size: int = 32 base_type: og.BaseDataType = og.BaseDataType.DOUBLE ctype: object = ctypes.c_double matrix_dim: int = 2 # -------------------------------------------------------------------------------------------------------------- @dataclass class Matrix3d(Dtype): tuple_count: int = 9 size: int = 72 base_type: og.BaseDataType = og.BaseDataType.DOUBLE ctype: object = ctypes.c_double matrix_dim: int = 3 # -------------------------------------------------------------------------------------------------------------- @dataclass class Matrix4d(Dtype): tuple_count: int = 16 size: int = 128 base_type: og.BaseDataType = og.BaseDataType.DOUBLE ctype: object = ctypes.c_double matrix_dim: int = 4 # ============================================================================================================== @dataclass class Token(Dtype): tuple_count: int = 1 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.TOKEN ctype: object = ctypes.c_uint64 # ============================================================================================================== @dataclass class UChar(Dtype): tuple_count: int = 1 size: int = 1 base_type: og.BaseDataType = og.BaseDataType.UCHAR ctype: object = ctypes.c_ubyte # -------------------------------------------------------------------------------------------------------------- @dataclass class UInt(Dtype): tuple_count: int = 1 size: int = 4 base_type: og.BaseDataType = og.BaseDataType.UINT ctype: object = ctypes.c_uint32 # -------------------------------------------------------------------------------------------------------------- @dataclass class UInt64(Dtype): tuple_count: int = 1 size: int = 8 base_type: og.BaseDataType = og.BaseDataType.UINT64 ctype: object = ctypes.c_uint64
9,585
Python
32.16955
116
0.460198
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/bundles.py
# The information bracketed here with begin/end describes the interface that is recommended for use with bundled # attributes. The documentation uses these markers to perform a literal include of this code into the docs so that # it can be the single source of truth. Note that the interface described here is not the complete set of functions # functions available, merely the ones that make sense for the user to access when dealing with bundles. # # begin-bundle-interface-description """ # A bundle can be described as an opaque collection of attributes that travel together through the graph, whose # contents and types can be introspected in order to determine how to deal with them. This section describes how # the typical node will interface with the bundle content access. Use of the attributes within the bundles is the # same as for the extended type attributes, described with their access methods. # # An important note regarding GPU bundles is that the bundle itself always lives on the CPU, specifying a memory # space of "GPU/CUDA" for the bundle actually means that the default location of the attributes it contains will # be on the GPU. # # The main bundle is extracted the same as any other attribute, by referencing its generated database location. # For this example the bundle will be called "color" and it will have members that could either be the set # ("r", "g", "b", "a") or the set ("c", "m", "y", "k") with the obvious implications of implied color space. # As with other attribute types the bundle attribute functions are available through an accessor color_bundle = db.inputs.color # The accessor can determine if it points to valid data through a property valid_color = color_bundle.valid # If you want to call the underlying Bundle ABI directly you can access the og.Bundle object bundle_object = color_bundle.bundle # It can be queried for the number of attributes it holds bundle_attribute_count = color_bundle.size # It can have its contents iterated over, where each element in the iteration is an accessor of the bundled attribute for (bundled_attribute in color_bundle.attributes) pass # It can be queried for an attribute in it with a specific name bundled_attribute = color_bundle.attribute_by_name(db.tokens.red) # You can get naming information to identify where the bundle is stored you can also get a path bundle_path = color_bundle.path # *** The rest of these methods are for output bundles only, as they change the makeup of the bundle # It can have its contents (i.e. attribute membership) cleared computed_color_bundle.clear() # It can be assigned to an output bundle, which merely transfers ownership of the bundle. # The property setter for the bundle member is the mechanism for this. color_bundle.bundle = some_other_bundle # This is accomplished with the insert utility function, which can insert a number of different types of objects # into a bundle. (The type of data it is passed determines what will be inserted.) # # The above function uses this variation, which inserts the bundle members into an existing bundle computed_color_bundle.insert(color_bundle) # It can have a single attribute from another bundle inserted into its current list, like if you don't want # the transparency value in your output color computed_color_bundle.clear() computed_color_bundle.insert(color_bundle.attribute_by_name(db.tokens.red)) computed_color_bundle.insert(color_bundle.attribute_by_name(db.tokens.green)) computed_color_bundle.insert(color_bundle.attribute_by_name(db.tokens.blue)) # Optionally, the attribute can be renamed when adding to the bundle by passing the attribute and name as a 2-tuple red_attribute = color_bundle.attribute_by_name(db.tokens.red) computed_color_bundle.insert((red_attribute, db.tokens.scarlett)) # It can also add a brand new attribute with a specific type and name as a 2-tuple og.Type FLOAT_TYPE(og.BaseDataType.FLOAT) computed_color_bundle.insert((FLOAT_TYPE, db.tokens.opacity) # *** When attributes are extracted from a bundle they will also be enclosed in a wrapper class og.RuntimeAttribute # The wrapper class has access to the attribute description information, specifically the name and type red_name = red_attribute.name red_type = red_attribute.type # Array attributes have a "size" property, which can also be set on output or state attributes point_array = db.inputs.mesh.attribute_by_name(db.tokens.points) deformed_point_array = db.outputs.mesh.attribute_by_name(db.tokens.points) deformed_point_array.size = point_array.size # Default value access is done through the value property, which is writable on output or state attributes red_input = db.inputs.color.attribute_by_name(db.tokens.red) red_output = db.outputs.color.attribute_by_name(db.tokens.red) red_output.value = 1.0 - red_input.value # By default the above functions operate in the same memory space as was defined by the bundled that contained the # attribute. If you wish to be more explicit about where the memory lives you can access the specific versions of # value properties that force either CPU or GPU memory space if on_gpu: call_cuda_code(red_output.gpu_value, red_input.gpu_value) else: red_output.cpu_value = 1.0 - red_input.cpu_value # Lastly, on the rare occasion you need direct access to the attribute's ABI through the underlying type # og.AttributeData you can access it through the abi property my_attribute_data = red_attribute.abi """ # end-bundle-interface-description from __future__ import annotations from contextlib import suppress from typing import Any, Dict, List, Optional, Set, Tuple, Union import omni.graph.core as og import omni.graph.tools.ogn as ogn from carb import log_warn from .autonode.type_definitions import AutoNodeTypeConversion from .runtime import RuntimeAttribute from .utils import non_const # Information required to create a new bundled attribute from scratch AttributeDescription = Tuple[og.Type, str] # ================================================================================ class BundleContents: """Manage the allowed types of attributes, providing a static set of convenience values Internal Attributes: __bundle: The bundle attached to the attribute __gpu_by_default: Are the bundle members on the GPU by default? Properties: context: Evaluation context from which this bundle was extracted read_only: Is the bundle data read-only? """ def __init__( self, context: og.GraphContext, node: og.Node, attribute_name: str, read_only: bool, gpu_by_default: bool, gpu_ptr_kind: og.PtrToPtrKind = og.PtrToPtrKind.NA, ): """Initialize the access points for the bundle attribute Args: context: Evaluation context from which this bundle was extracted node: Node owning the bundle attribute_name: Name of the bundle attribute read_only: Is the bundle data read-only? gpu_by_default: Are the bundle members on the GPU by default? gpu_ptr_kind: On which device to pointers to GPU bundles live? """ self.context = context self.read_only = read_only self.__gpu_by_default = gpu_by_default self.__gpu_ptr_kind = gpu_ptr_kind if read_only: self.__bundle = context.get_input_bundle(node, attribute_name) else: self.__bundle = context.get_output_bundle(node, attribute_name) # ------------------------------------------------------------------------------------------ @property def size(self) -> int: """Returns the number of attributes within this bundle, 0 if the bundle is not valid""" return self.__bundle.get_attribute_data_count() if self.__bundle.is_valid() else 0 # ------------------------------------------------------------------------------------------ @property def valid(self) -> bool: """Returns true if the underlying bundle is valid, else false""" return self.__bundle.is_valid() # ------------------------------------------------------------------------------------------ @non_const def clear(self): """Empties out the bundle contents Raises: og.OmniGraphError if the bundle is not writable """ # Silently accept that clearing an invalid bundle is a null operation if self.__bundle.is_valid(): self.__bundle.clear() # ------------------------------------------------------------------------------------------ @non_const def add_attributes(self, types: List[og.Type], names: List[str]): """Add attributes to the bundle Args: types: Vector of types names: The names of each attribute Note it is required that size(types) == size(names) Returns: nope """ if not self.__bundle.is_valid: log_warn("Attempting to insert something into an invalid bundle") return if len(types) != len(names): log_warn("mismatched size of types and names") return self.__bundle.add_attributes(types, names) # ------------------------------------------------------------------------------------------ @non_const def remove_attributes(self, names: List[str]): """Remove attributes from the bundle Args: names: The names of each attribute to be removed Note it is required that size(types) == size(names) Returns: nope """ if not self.__bundle.is_valid: log_warn("Attempting to remove something from an invalid bundle") return self.__bundle.remove_attributes(names) # ------------------------------------------------------------------------------------------ @non_const def insert( self, to_insert: Union[BundleContents, RuntimeAttribute, Tuple[RuntimeAttribute, str], AttributeDescription] ) -> RuntimeAttribute: """Insert new content in the existing bundle Args: to_insert: Object to insert. It can be one of three different types of object: Bundle: Another bundle, whose contents are entirely copied into this one RuntimeAttribute: A single attribute from another bundle to be copied with the same name (RuntimeAttribute, str): A single attribute from another bundle and the name to use for the copy AttributeDescription: Information required to create a brand new typed attribute Returns: RuntimeAttribute of the new attribute if inserting an attribute, else None """ if not self.__bundle.is_valid: log_warn("Attempting to insert something into an invalid bundle") return None if isinstance(to_insert, BundleContents): self.__bundle.insert_bundle(to_insert.__bundle) # noqa: PLW0212 return None if isinstance(to_insert, RuntimeAttribute): new_attribute = self.__bundle.insert_attribute(to_insert.attribute_data, to_insert.name) return RuntimeAttribute( new_attribute, self.context, self.read_only, self.__gpu_by_default, self.__gpu_ptr_kind ) if isinstance(to_insert, tuple): if isinstance(to_insert[0], og.Type): new_attribute = self.__bundle.add_attribute(to_insert[0], to_insert[1]) return RuntimeAttribute( new_attribute, self.context, self.read_only, self.__gpu_by_default, self.__gpu_ptr_kind ) with suppress(AttributeError): new_attribute = self.__bundle.insert_attribute(to_insert[0].attribute_data, to_insert[1]) return RuntimeAttribute( new_attribute, self.context, self.read_only, self.__gpu_by_default, self.__gpu_ptr_kind ) raise og.OmniGraphError(f"Unknown type of object being inserted into a bundle ({to_insert})") # ------------------------------------------------------------------------------------------ def attribute_by_name(self, attribute_name: str) -> Optional[RuntimeAttribute]: """Returns the named attribute within the bundle, or None if no such attribute exists in the bundle""" all_attributes = self.__bundle.get_attribute_data(not self.read_only) if self.__bundle.is_valid() else [] for attribute in all_attributes: if attribute.get_name() == attribute_name: return RuntimeAttribute( attribute, self.context, self.read_only, self.__gpu_by_default, self.__gpu_ptr_kind ) return None # ------------------------------------------------------------------------------------------ def remove(self, attribute_name: str): """Removes the attribute with the given name from the bundle, silently succeeding if it is not in the bundle""" if not self.__bundle.is_valid(): log_warn(f"Attempted to remove attribute {attribute_name} from an invalid bundle") else: self.__bundle.remove_attribute(attribute_name) # ------------------------------------------------------------------------------------------ @property def bundle(self) -> og.Bundle: """Returns the bundle being wrapped by this object""" return self.__bundle @bundle.setter @non_const def bundle(self, bundle_to_assign: BundleContents): """Copies the contents of the bundle into this one, clearing first. Use insert() to add to the contents of a bundle without clearing. Good for assigning the entire contents of an input bundle to an output bundle before performing operations: db.outputs.transformedBundle = db.inputs.bundle """ if self.__bundle.is_valid() and bundle_to_assign.bundle.is_valid(): self.clear() self.insert(bundle_to_assign) else: log_warn("Attempting to assign a bundle to an invalid bundle") # ------------------------------------------------------------------------------------------ @property def attributes(self) -> List[RuntimeAttribute]: """Returns the list of interface objects corresponding to the attributes contained within the bundle""" all_attributes = self.__bundle.get_attribute_data(not self.read_only) if self.__bundle.is_valid() else [] return [ RuntimeAttribute(attribute, self.context, self.read_only, self.__gpu_by_default, self.__gpu_ptr_kind) for attribute in all_attributes ] @attributes.setter @non_const def attributes(self, attributes_to_assign: List[RuntimeAttribute]): """Populate the bundle with the list of attributes, clearing before assignment. Good for assigning a subset of the contents of another bundle's attributes to this one: db.outputs.filteredBundle = db.inputs.bundle.attributes[0:3] """ if not self.__bundle.is_valid(): log_warn("Attempted to assign attributes to invalid bundle") return self.clear() raise og.OmniGraphError("TODO: Assigning list of attributes to a bundle not implemented") # ------------------------------------------------------------------------------------------ @property def path(self) -> str: """Returns the path where this bundle's data is stored""" return self.__bundle.get_prim_path() # ================================================================================ class BundleContainer: """-------- FOR GENERATED CODE USE ONLY -------- Simple container to manage the set of bundle objects used during a compute function by a node. This is initialized alongside attribute data in order to minimize the generated code. It will house a set of BundleContents objects, one per attribute that is a bundle type, with properties named after the attributes they represent Args: context: Evaluation context for these bundles node: Owner of these bundles attributes: Subset of node attributes to check for being bundles gpu_bundles: Subset of bundle attributes whose memory lives on the GPU read_only: True if these attributes are read-only """ # TODO: gpu_bundles is a hacky way of passing the information "is the bundle on the GPU by default". # It's probably better in the long run to make this a property of the attribute. # The gpu_ptr_kinds is an even hackier way of deciding if the GPU bundle returns pointers on the CPU or not, # but it was a tradeoff between that and creating a new version of this container class. def __init__( self, context: og.GraphContext, node: og.Node, attributes, gpu_bundles: List[str], read_only: bool = False, gpu_ptr_kinds: Optional[Dict[str, og.PtrToPtrKind]] = None, ): """Set up the list of members based on the list of node attributes. These will usually be a subset, e.g. just the inputs, to keep the higher level access simple Args: context: Evaluation context for which the bundles are valid node: OmniGraph node owning the bundles attributes: Object containing the attributes as properties read_only: If True then the bundles cannot be modified """ for property_name in vars(attributes): attribute = getattr(attributes, property_name) if not isinstance(attribute, og.Attribute): continue if attribute.get_type_name() == "bundle": attribute_name = attribute.get_name() gpu_by_default = attribute_name in gpu_bundles gpu_ptr_kind = og.PtrToPtrKind.GPU if gpu_by_default else og.PtrToPtrKind.NA if gpu_ptr_kinds is not None and attribute_name in gpu_ptr_kinds: gpu_ptr_kind = gpu_ptr_kinds[attribute_name] full_name = attribute_name setattr( self, ogn.attribute_name_as_python_property(full_name), BundleContents(context, node, full_name, read_only, gpu_by_default, gpu_ptr_kind), ) # ================================================================================ class Bundle: """Deferred implementation of the bundle concept""" def __init__(self, attribute_name: str, read_only: bool): """Initialize the access points for the bundle attribute Args: attribute_name: the bundle's name. This name will only be used if the bundle is nested. read_only: Is the bundle data read-only? """ self.__buffer: Dict[str, Union[Bundle, OmniAttribute]] = {} self.__delete_buffer: Set[str] = set() self._bundle_contents = None self._attribute_name = attribute_name self.read_only = read_only # ------------------------------------------------------------------------------------------ @staticmethod def commit_to_graph_bundle_contents(source: Bundle, bundle_contents: BundleContents): """-------- FOR GENERATED CODE USE ONLY -------- Copy all attributes from the buffer to the runtime BundleContents class. Args: source: the Bundle object to be copied bundle_contents: the BundleContets object to be copied into into """ for attr_name in source.attribute_names: # optimization only create attributes that have been touched if attr_name in source._Bundle__buffer: # noqa: PLW0212 attr = source.attribute_by_name(attr_name) if attr.is_dirty: bundle_contents.insert((attr.og_type, attr.name)).value = attr.value else: bundle_contents.insert(attr.runtime_accessor) else: # copy untouched attributes bundle_contents.insert(source.runtime_accessor.attribute_by_name(attr_name)) # ------------------------------------------------------------------------------------------ @classmethod def from_accessor(cls, bundle_contents: BundleContents): """-------- FOR GENERATED CODE USE ONLY -------- Convert a BundleContents object to a python Bundle. Args: bundle_contents: the graph object representing the bundle """ bundle = cls("bundle", False) if bundle_contents.valid: bundle._bundle_contents = bundle_contents return bundle # ------------------------------------------------------------------------------------------ @property def runtime_accessor(self) -> BundleContents: """exposes the runtime bundle accessor. Returns: the BundleContents object if it exists, None otherwise. """ return self._bundle_contents # ------------------------------------------------------------------------------------------ def create_attribute(self, name: str, type_desc: type) -> OmniAttribute: """Create an attribute inside the buffered bundle data structure Args: name: name of the attribute to create type_desc: python type object of the attribute to create. Accepts all Omnigraph types. Will attempt to convert non-omnigraph types, but raise an error if it fails. Returns: the OmniAttribute it created. Raises: OmniGraphError if no type conversion was found. """ attr = OmniAttribute(name, type_desc) self.insert(attr) return attr # ------------------------------------------------------------------------------------------ @property def is_runtime_resident(self): return self._bundle_contents is not None and self._bundle_contents.valid # ------------------------------------------------------------------------------------------ @property def size(self) -> int: """Returns the number of attributes within this bundle, 0 if the bundle is not valid""" return len(self.attribute_names) # ------------------------------------------------------------------------------------------ @property def valid(self) -> Optional[bool]: """Returns: True if the underlying bundle is valid, False if the underlying bundle is not valid, None if the """ if self.is_runtime_resident: return self._bundle_contents.valid return None # ------------------------------------------------------------------------------------------ @non_const def clear(self): """Empties out the bundle contents Raises: og.OmniGraphError if the bundle is not writable """ # Silently accept that clearing an invalid bundle is a null operation if self.is_runtime_resident: for attr in self._bundle_contents.attributes: self.__delete_buffer.add(attr) else: self.__buffer.clear() # ------------------------------------------------------------------------------------------ @non_const def insert(self, to_insert: Union[Bundle, OmniAttribute, Tuple[OmniAttribute, str], AttributeDescription]): """Insert new content in the existing bundle Args: to_insert: Object to insert. It can be one of three different types of object: Bundle: Another bundle, whose contents are entirely copied into this one RuntimeAttribute: A single attribute from another bundle to be copied with the same name (RuntimeAttribute, str): A single attribute from another bundle and the name to use for the copy AttributeDescription: Information required to create a brand new typed attribute Returns: Attribute object of the new attribute if inserting an attribute, else None """ name = to_insert.name if isinstance(to_insert, Bundle): self.__buffer[to_insert.attribute_name] = to_insert self.__delete_buffer.discard(name) return to_insert if isinstance(to_insert, OmniAttribute): self.__buffer[to_insert.name] = to_insert self.__delete_buffer.discard(name) return to_insert raise og.OmniGraphError(f"Unknown type of object being inserted into a bundle ({to_insert})") # ------------------------------------------------------------------------------------------ def attribute_by_name(self, attribute_name: str) -> Optional[RuntimeAttribute]: """ Get an attribute by name from the underlying buffer or the buffer masking it. Args: attribute_name: the attribute being queried. Returns: the named attribute within the bundle, or None if no such attribute exists in the bundle""" if attribute_name in self.__delete_buffer: return None if attribute_name in self.__buffer: return self.__buffer.get(attribute_name, None) if self.is_runtime_resident: attr = self._bundle_contents.attribute_by_name(attribute_name) if attr is None: return None wrapped_attr = OmniAttribute.from_accessor(attr) self.__buffer[attribute_name] = wrapped_attr return wrapped_attr return None # ------------------------------------------------------------------------------------------ def remove(self, attribute_name: str): """Removes the attribute with the given name from the bundle, silently succeeding if it is not in the bundle. Args: attribute_name: attribute to be deleted. """ if self.is_runtime_resident: self.__delete_buffer.add(attribute_name) else: self.__buffer.pop(attribute_name, None) # -------------------------------------------------------------------------------------------- @property def name(self): """The bundle's name""" return self._attribute_name # ------------------------------------------------------------------------------------------ @property def attribute_names(self) -> List[OmniAttribute]: """Returns the list of interface objects corresponding to the attributes contained within the bundle""" attributes = set(self.__buffer) if self.is_runtime_resident: attributes.update(attr.name for attr in self._bundle_contents.attributes) for name in self.__delete_buffer: attributes.discard(name) return list(attributes) # ================================================================================ class OmniAttribute: """Simple attribute type to use for python bundles""" def __init__(self, name: str, type_desc: type, read_only: bool = False, required: bool = True): self.__name = name self.__value = None self.__type_desc = type_desc self.__metadata = {} self._runtime_attr = None self.required = required self.read_only = read_only # ------------------------------------------------------------------------------------------ @property def name(self): """The attribute's name""" return self.__name # ------------------------------------------------------------------------------------------ @classmethod def from_accessor(cls, attr: RuntimeAttribute): # Runtime attributes come as og.Type type_name = attr.type.get_ogn_type_name() conversion = AutoNodeTypeConversion.from_ogn_type(type_name) if not conversion: raise og.OmniGraphError(f"Can't find an appropriate type conversion for {attr.type_name}") new_attr = cls(attr.name, conversion.type) new_attr._runtime_attr = attr return new_attr # ------------------------------------------------------------------------------------------ @property def is_runtime_resident(self) -> bool: """Property indidcating whether the attribute represents a concrete graph/fastcache attribtue.""" return self._runtime_attr is not None # ------------------------------------------------------------------------------------------ @property def runtime_accessor(self) -> RuntimeAttribute: return self._runtime_attr # ------------------------------------------------------------------------------------------ @property def is_dirty(self) -> bool: """Whether the python representation of this value needs to update the graph representation""" return not self.is_runtime_resident and self.__value is not None # ------------------------------------------------------------------------------------------ @property def metadata(self): return self.__metadata # ------------------------------------------------------------------------------------------ @property # noqa: A003 def type(self): return self.__type_desc # ------------------------------------------------------------------------------------------ @property def og_type(self): # HACK (OS): Converts an OG type to a string if isinstance(self.type, og.Type): return self.type conversion = AutoNodeTypeConversion.from_type(self.type) if conversion is None: raise og.OmniGraphError(f"No conversions found from type {self.type}") type_str = conversion.og_type return og.AttributeType.type_from_ogn_type_name(type_str) # ------------------------------------------------------------------------------------------ @property def value(self): """Get the local value, if it masks the underlying context representation value. Otherwise get the value from the context representation. """ if self.is_runtime_resident: return self.__value or self._runtime_attr.value return self.__value # ------------------------------------------------------------------------------------------ @value.setter def value(self, val: Any): self.__value = val # ================================================================================ AutoNodeTypeConversion.register_type_conversion( python_type=Bundle, ogn_typename="bundle", ogn_to_python=Bundle.from_accessor, ogn_to_python_method=AutoNodeTypeConversion.Method.ASSIGN, python_to_ogn=Bundle.commit_to_graph_bundle_contents, python_to_ogn_method=AutoNodeTypeConversion.Method.MODIFY, default=None, )
31,002
Python
43.29
119
0.581221
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/performance.py
"""Helpers for running performance tests on OmniGraph objects.""" import re from contextlib import suppress from typing import Dict, List import carb import carb.profiler import omni.graph.core as og # Regular expression matching event descriptions for node compute timing RE_COMPUTE_EVENT = re.compile(r"(Py)?Compute\s+(.*)") class OmniGraphPerformance: """Provides simple interfaces for measuring performance of OmniGraph. For simplicity, the collection is kept separate from the interpretation of the data. That way multiple collections can be made and summarized separately. Normal usage is something like this: p = og.OmniGraphPerformance() p.start_monitor() profile_task = asyncio.create_task(measure_results()) p.end_monitor() async def measure_results(): timing_task = p.measure_timing() await timing_task ids = timing_task.result() display(ids, p.average_node_evaluation_time()) Internal Members: __capture_enabled: True when the profiler capturing is running __enabled_capture_mask: Profiler mask value to enable data capture, filtered for any settings __nodes_captured: Union of all nodes in the various capture sessions; for convenience when reporting __iprofiler: Interface for the profiler to collect CPU timing __iprofiler_monitor: Interface for the profiler loading of collecting timing data __old_capture_mask: Saved capture mask when the profiler is engaged (None when not running) __results: List of dictionaries with timing results __settings: Access to profiler settings """ def __init__(self): """Set up the profiling interface objects, 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 operations might not work as expected. """ try: self.__iprofiler = carb.profiler.acquire_profiler_interface() self.__iprofiler_monitor = carb.profiler.acquire_profile_monitor_interface() self.__settings = carb.settings.get_settings() if self.__iprofiler is None: raise RuntimeError("Could not load the profiler interface") if self.__iprofiler_monitor is None: raise RuntimeError("Could not load the profiler monitor interface") except RuntimeError as error: carb.log_warn(f"RuntimeError {error} - data will not be collected") self.__results = [] self.__nodes_captured = set() self.__old_capture_mask = None self.__capture_enabled = False if self.__settings: mask = self.__settings.get_as_int("/app/profilerMask") if mask < 0: # since get_as_int() returns a signed value, and set_capture_mask() requires an unsigned value, and the # default value is all bits set (which python interprets as -1), we convert to a positive number here. mask = mask + 0x010000000000000000 self.__enabled_capture_mask = mask else: self.__enabled_capture_mask = 0x0FFFFFFFFFFFFFFFF # ---------------------------------------------------------------------- def available(self) -> bool: """Returns true if the profiling capabilities are available""" return self.__iprofiler is not None and self.__iprofiler_monitor is not None and self.__capture_enabled # ---------------------------------------------------------------------- def clear(self): """Clear out any timing data saved so far""" self.__results = [] # ---------------------------------------------------------------------- def memory_in_use(self) -> int: """Return the current number of bytes in use by FlatCache""" return og.OmniGraphInspector().memory_use(og.get_compute_graph_contexts()[0]) # ---------------------------------------------------------------------- def start_monitor(self): """Set up the profiler for capturing - must be done before measuring timing""" if not self.__capture_enabled: self.__old_capture_mask = self.__iprofiler.get_capture_mask() self.__iprofiler.set_capture_mask(self.__enabled_capture_mask) self.__capture_enabled = True else: carb.log_warn("Tried to enable capture when it was already enabled") # ---------------------------------------------------------------------- def end_monitor(self): """Set up the profiler to finish capturing""" if self.__old_capture_mask is None or not self.__capture_enabled: carb.log_warn("Tried to stop capture before starting") else: self.__iprofiler.set_capture_mask(self.__old_capture_mask) self.__old_capture_mask = None self.__capture_enabled = False # ---------------------------------------------------------------------- async def measure_timing(self, iterations: int = 1) -> List[int]: """Add a set of evaluation timing information to the current data. You can either take multiple sets of timing here by setting the iterations value, or you can call this method multiple times when you make changes. Args: iterations: Number of times to measure the timing. Returns: List of IDs for the timing(s) taken. """ if not self.available(): return [] self.clear() id_list = [] for _run in range(iterations): id_list.append(len(self.__results)) this_run = {} await og.Controller.evaluate() events = self.__iprofiler_monitor.get_last_profile_events() collected_data = events.get_profile_events(events.get_main_thread_id()) for data in collected_data: node_match = RE_COMPUTE_EVENT.match(data["name"]) if node_match: node_name = node_match.group(2) this_run[node_name] = getattr(this_run, node_name, 0.0) + data["duration"] self.__nodes_captured.add(node_name) self.__results.append(this_run) return id_list # ---------------------------------------------------------------------- def average_node_evaluation_time(self) -> Dict[str, float]: """Average out the node evaluation timing information for all runs for each node. Returns: Dictionary of NodePath:EvaluationTime for each node in the timing set. """ if not self.available(): return {} evaluation_times = {} for node_name in self.__nodes_captured: timing = 0.0 count = 0 for run in self.__results: with suppress(KeyError): timing += run[node_name] count += 1 if count > 0: evaluation_times[node_name] = timing / float(count) return evaluation_times # ---------------------------------------------------------------------- def average_event_time(self, event_regex: str) -> Dict[str, float]: """Average out the named event timing information for all runs for each node. Args: event_regex: Regular expression identifying the event specific to the type of node data being collected Returns: Dictionary of NodePath:EvaluationTime for each node in the timing set. """ if not self.available(): return {} evaluation_times = {} for node_name in self.__nodes_captured: timing = 0.0 count = 0 for run in self.__results: with suppress(KeyError): timing += run[node_name] count += 1 if count > 0: evaluation_times[node_name] = timing / float(count) return evaluation_times
8,090
Python
41.140625
119
0.566873
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/value_commands.py
""" Commands that modify values of an existing OmniGraph """ from typing import Optional import carb import omni.graph.core as og import omni.kit import omni.kit.commands import omni.usd from omni.graph.core._impl.utils import ValueToSet_t from pxr import Sdf # ============================================================================================================== class DisableNodeCommand(omni.kit.commands.Command): """ Disable Node **Command**. Causes a node to be disabled in the compute graph Args: node: The node to disable """ def __init__(self, node: og.Node): self._node = node self._did_doit = False def do(self): disabled = self._node.is_disabled() if not disabled: self._node.set_disabled(True) self._did_doit = True def undo(self): if self._did_doit: self._node.set_disabled(False) # ============================================================================================================== class EnableNodeCommand(omni.kit.commands.Command): """ Enable Node **Command**. Causes a node to be enabled in the compute graph Args: node: The node to enable """ def __init__(self, node: og.Node): self._node = node self._did_doit = False def do(self): disabled = self._node.is_disabled() if disabled: self._node.set_disabled(False) self._did_doit = True def undo(self): if self._did_doit: self._node.set_disabled(True) # ============================================================================================================== class DisableGraphCommand(omni.kit.commands.Command): """ Disable Graph **Command**. Causes a graph to be disabled Args: graph: The graph to disable """ def __init__(self, graph): self._graph = graph self._did_doit = False def do(self): disabled = self._graph.is_disabled() if not disabled: self._graph.set_disabled(True) self._did_doit = True def undo(self): if self._did_doit: self._graph.set_disabled(False) # ============================================================================================================== class EnableGraphCommand(omni.kit.commands.Command): """ Enable Graph **Command**. Causes a graph to be enabled Args: graph: The graph to enable """ def __init__(self, graph: og.Graph): self._graph = graph self._did_doit = False def do(self): disabled = self._graph.is_disabled() if disabled: self._graph.set_disabled(False) self._did_doit = True def undo(self): if self._did_doit: self._graph.set_disabled(True) # ============================================================================================================== class EnableGraphUSDHandlerCommand(omni.kit.commands.Command): """ Enable Graph USD Handler **Command**. Causes a graph's USD notice handdler to be enabled. Args: graph: The graph to enable notice handling """ def __init__(self, graph: og.Graph): self._graph = graph self._did_doit = False def do(self): enabled = self._graph.usd_notice_handling_enabled() if not enabled: self._graph.set_usd_notice_handling_enabled(True) self._did_doit = True def undo(self): if self._did_doit: self._graph.set_usd_notice_handling_enabled(False) # ============================================================================================================== class DisableGraphUSDHandlerCommand(omni.kit.commands.Command): """ Disable Graph USD Handler **Command**. Causes a graph's USD notice handdler to be disabled. Args: graph: The graph to disable enotice handling """ def __init__(self, graph: og.Graph): self._graph = graph self._did_doit = False def do(self): enabled = self._graph.usd_notice_handling_enabled() if enabled: self._graph.set_usd_notice_handling_enabled(False) self._did_doit = True def undo(self): if self._did_doit: self._graph.set_usd_notice_handling_enabled(True) # ============================================================================================================== class RenameNodeCommand(omni.kit.commands.Command): """ Rename Node **Command**. Renames an existing node in a compute graph Args: graph: The graph in which the node is located path: The location in the USD stage new_path: The new path of the node """ def __init__(self, graph: og.Graph, path: str, new_path: str): self._graph = graph self._node_path = path self._new_node_path = new_path self._did_doit = False self._node = None def do(self): if not Sdf.Path.IsValidPathString(self._new_node_path): carb.log_error(f"Cannot rename {self._node_path} to {self._new_node_path} as it is not a valid USD path") elif self._graph.get_node(self._new_node_path).is_valid(): carb.log_error(f"Cannot rename {self._node_path} to {self._new_node_path} as it already exists") else: self._node = self._graph.get_node(self._node_path) if self._node is not None and self._node.is_valid(): if self._node.is_backed_by_usd(): # TODO: we want to rename the prim inside graph.rename_node() instead of using MovePrimCommand # see Graph::renameNodePath() in Graph.cpp for details # Since we are doing it this hack'ish way, we need to disable USD notice handling in the graph # so it doesn't respond to the move prim command, and so the subsequent call to rejig the graph # state can happen free of interference from that other code path omni.kit.commands.execute("DisableGraphUSDHandler", graph=self._graph) omni.kit.commands.execute("MovePrim", path_from=self._node_path, path_to=self._new_node_path) omni.kit.commands.execute("EnableGraphUSDHandler", graph=self._graph) # rename_node should come after USD rename self._graph.rename_node(self._node_path, self._new_node_path) self._did_doit = True def undo(self): if self._did_doit: # All the previously executed commands should undo automatically self._graph.rename_node(self._new_node_path, self._node_path) self._node = None self._did_doit = False # ============================================================================================================== class RenameSubgraphCommand(omni.kit.commands.Command): """ Rename Subgraph **Command**. Renames an existing subgraph in a compute graph Args: graph: The graph in which the subgraph is located path: The location in the USD stage new_path: The new path of the subgraph """ def __init__(self, graph: og.Graph, path: str, new_path: str): self._graph = graph self._subgraph_path = path self._new_subgraph_path = new_path self._did_doit = False self._subgraph = None def do(self): if not Sdf.Path.IsValidPathString(self._new_subgraph_path): carb.log_error( f"Cannot rename {self._subgraph_path} to {self._new_subgraph_path} as it is not a valid USD path" ) elif self._graph.get_subgraph(self._new_subgraph_path).is_valid(): carb.log_error(f"Cannot rename {self._subgraph_path} to {self._new_subgraph_path} as it already exists") else: self._subgraph = self._graph.get_subgraph(self._subgraph_path) if self._subgraph is not None and self._subgraph.is_valid(): # TODO: we want to rename the prim inside graph.rename_subgraph(), instead of using MovePrimCommand # see Graph::renameSubgraphPath() in Graph.cpp for details omni.kit.commands.execute("DisableGraphUSDHandler", graph=self._graph) omni.kit.commands.execute("MovePrim", path_from=self._subgraph_path, path_to=self._new_subgraph_path) omni.kit.commands.execute("EnableGraphUSDHandler", graph=self._graph) # rename_subgraph should come after USD rename self._graph.rename_subgraph(self._subgraph_path, self._new_subgraph_path) self._did_doit = True def undo(self): if self._did_doit: # All the previously executed commands should undo automatically self._graph.rename_subgraph(self._new_subgraph_path, self._subgraph_path) self._graph = None self._did_doit = False # ============================================================================================================== class SetAttrCommand(omni.kit.commands.Command): """ SetAttr **Command**. Sets the value of an attribute on a node Args: attr: The attribute to set value: The value to set the attribute to set_type: The OGN type name to set the attribute to for extended attributes that require Type resolution. You can also embed the type in the value using a TypedValue on_gpu: If True then set the value in the GPU memory, otherwise CPU memory update_usd: If True then immediately propagate the new value to the USD backing, if it exists """ def __init__( self, attr: og.Attribute, value: ValueToSet_t, set_type: str = None, on_gpu: bool = False, update_usd: bool = True, ): self._did_doit = False self._attr = attr self._value = value self._set_type = set_type self._old_value = None self._on_gpu = on_gpu self._update_usd = update_usd self._helper = og.AttributeValueHelper(attr) @staticmethod def do_immediate( attr: og.Attribute, value: ValueToSet_t, on_gpu: bool = False, update_usd: bool = True, ): og.AttributeValueHelper(attr).set(value, on_gpu, update_usd) def do(self): try: self._old_value = self._helper.get(self._on_gpu) except og.OmniGraphError: # This is expected for unresolved types if self._attr.get_resolved_type().base_type != og.BaseDataType.UNKNOWN: raise self._old_value = None self._helper.set(self._value, self._on_gpu, update_usd=self._update_usd) self._did_doit = True def undo(self): if self._did_doit and self._old_value is not None: # Blindly use the same memory type, so there will be a slight inefficiency in the case of calling this # command to set values on the opposite device they are currently on (i.e. setting the GPU value for # data currently on the CPU, and vice versa). Fabric will do that work for us. self._helper.set(self._old_value, self._on_gpu, update_usd=self._update_usd) # ============================================================================================================== class SetAttrDataCommand(omni.kit.commands.Command): """ SetAttrData **Command**. Sets the value of an attribute data Args: attribute_data: The attribute data to set value: The value to be set graph: The graph to operate on (deprecated and unnecessary) on_gpu: If True then set the value in the GPU memory, otherwise CPU memory """ def __init__( self, attribute_data: og.AttributeData, value: ValueToSet_t, graph: Optional[og.Graph] = None, on_gpu: bool = False, ): self._did_doit = False self._attribute_data = attribute_data self._value = value self._on_gpu = on_gpu self._old_value = None self._helper = og.AttributeDataValueHelper(attribute_data) if graph is not None: carb.log_warn("'graph' parameter to SetAttrData is deprecated and unnecessary and will be ignored.") @staticmethod def do_immediate( attribute_data: og.AttributeData, value: ValueToSet_t, on_gpu: bool = False, ): helper = og.AttributeDataValueHelper(attribute_data) if isinstance(value, og.TypedValue): carb.log_warn("Type is ignored when using SetAttrData, use SetAttr instead to set explicitly typed data") helper.set(value.value, on_gpu) else: helper.set(value, on_gpu) def do(self): self._old_value = self._helper.get(self._on_gpu) if isinstance(self._value, og.TypedValue): carb.log_warn("Type is ignored when using SetAttrData, use SetAttr instead to set explicitly typed data") self._helper.set(self._value.value, self._on_gpu) else: self._helper.set(self._value, self._on_gpu) self._did_doit = True def undo(self): if self._did_doit: # Blindly use the same memory type, so there will be a slight inefficiency in the case of calling this # command to set values on the opposite device they are currently on (i.e. setting the GPU value for # data currently on the CPU, and vice versa). Fabric will do that work for us. self._helper.set(self._old_value, self._on_gpu) # ============================================================================================================== class ChangePipelineStageCommand(omni.kit.commands.Command): """ Change Pipeline Stage **Command**. Change the pipeline stage of an existing graph. Args: graph: The graph whose pipeline stage needs to be changed new_pipeline_stage: The new pipeline stage of the graph """ def __init__(self, graph: og.Graph, new_pipeline_stage: og.GraphPipelineStage): self._graph = graph self._new_pipeline_stage = new_pipeline_stage self._old_pipeline_stage = None self._did_doit = False def do(self): self._old_pipeline_stage = self._graph.get_pipeline_stage() self._graph.change_pipeline_stage(self._new_pipeline_stage) self._did_doit = True def undo(self): if self._did_doit: self._graph.change_pipeline_stage(self._old_pipeline_stage) # ============================================================================================================== class SetEvaluationModeCommand(omni.kit.commands.Command): """ Set Evaluation Mode **Command**. Change the evaluation mode of an existing graph. Args: graph: The graph to change the evaluation mode on new_evaluation_mode: The new graph evaluation mode """ def __init__(self, graph: og.Graph, new_evaluation_mode: og.GraphEvaluationMode): self._graph = graph self._new_evaluation_mode = new_evaluation_mode self._old_evaluation_mode = None def do(self): self._old_evaluation_mode = self._graph.evaluation_mode self._graph.evaluation_mode = self._new_evaluation_mode def undo(self): if self._old_evaluation_mode is not None: self._graph.evaluation_mode = self._old_evaluation_mode self._old_evaluation_mode = None # ============================================================================================================== class SetVariableTooltipCommand(omni.kit.commands.Command): """ Set Variable Tooltip **Command**. Set the tooltip/description of a variable. Args: variable: The variable to set the tooltip of tooltip: The tooltip text to set """ def __init__(self, variable: og.IVariable, tooltip: str): self._variable = variable self._tooltip = tooltip self._old_tooltip = None self._set_tooltip = False def do(self): if not self._variable: return self._old_tooltip = self._variable.tooltip if self._old_tooltip == self._tooltip: return self._variable.tooltip = self._tooltip self._set_tooltip = True def undo(self): if not self._set_tooltip: return self._variable.tooltip = self._old_tooltip
16,636
Python
35.645374
117
0.557406
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/lookup_tables.py
""" Support file for other functional modules. Kept separate just to keep the other scripts readable. """ from typing import Callable, Optional, Tuple import omni.graph.core as og __all__ = [ "IDX_ARRAY_GET", "IDX_ARRAY_GET_TENSOR", "IDX_ARRAY_SET", "IDX_GET", "IDX_GET_TENSOR", "IDX_SET", "type_access_methods", "UNSUPPORTED_METHODS", ] # ---------------------------------------------------------------------- # Lookup tables mapping attributes to the methods to use for getting or setting their data. # Avoids deep if/else chain since there are over 50 types to support. # 0 = Get array data # 1 = Get array tensor data # 2 = Set array data # 3 = Get non-tensor data # 4 = Get tensor data # 5 = Set data IDX_ARRAY_GET = 0 IDX_ARRAY_GET_TENSOR = 1 IDX_ARRAY_SET = 2 IDX_GET = 3 IDX_GET_TENSOR = 4 IDX_SET = 5 CTX = og.GraphContext # Syntactic sugar # Helper constants that describe why a method is not available in the arrays below UNSUPPORTED = None # TODO: The methods supporting the type have not yet been written NOT_APPLICABLE = None # The method does not apply to the data type - e.g. tensors of a single integer value UNSUPPORTED_METHODS = [UNSUPPORTED, UNSUPPORTED, UNSUPPORTED, UNSUPPORTED, UNSUPPORTED, UNSUPPORTED] DOUBLE_MATRIX_METHODS = [ CTX.get_attribute_as_nested_doublearray, CTX.get_attribute_as_nested_doublearray_tensor, CTX.set_nested_doublearray_attribute, CTX.get_attribute_as_doublearray, UNSUPPORTED, CTX.set_double_matrix_attribute, ] BOOL_METHODS = [ CTX.get_attribute_as_boolarray, UNSUPPORTED, CTX.set_boolarray_attribute, CTX.get_attribute_as_bool, NOT_APPLICABLE, CTX.set_bool_attribute, ] DOUBLE_METHODS = [ CTX.get_attribute_as_doublearray, CTX.get_attribute_as_doublearray_tensor, CTX.set_doublearray_attribute, CTX.get_attribute_as_double, NOT_APPLICABLE, CTX.set_double_attribute, ] DOUBLE_ARRAY_METHODS = [ CTX.get_attribute_as_nested_doublearray, CTX.get_attribute_as_nested_doublearray_tensor, CTX.set_nested_doublearray_attribute, CTX.get_attribute_as_doublearray, CTX.get_attribute_as_doublearray_tensor, CTX.set_doublearray_attribute, ] FLOAT_METHODS = [ CTX.get_attribute_as_floatarray, CTX.get_attribute_as_floatarray_tensor, CTX.set_floatarray_attribute, CTX.get_attribute_as_float, NOT_APPLICABLE, CTX.set_float_attribute, ] FLOAT_ARRAY_METHODS = [ CTX.get_attribute_as_nested_floatarray, CTX.get_attribute_as_nested_floatarray_tensor, CTX.set_nested_floatarray_attribute, CTX.get_attribute_as_floatarray, CTX.get_attribute_as_floatarray_tensor, CTX.set_floatarray_attribute, ] HALF_METHODS = [ CTX.get_attribute_as_halfarray, UNSUPPORTED, CTX.set_halfarray_attribute, CTX.get_attribute_as_half, NOT_APPLICABLE, CTX.set_half_attribute, ] HALF_ARRAY_METHODS = [ CTX.get_attribute_as_nested_halfarray, UNSUPPORTED, CTX.set_nested_halfarray_attribute, CTX.get_attribute_as_halfarray, UNSUPPORTED, CTX.set_halfarray_attribute, ] INT_METHODS = [ CTX.get_attribute_as_intarray, CTX.get_attribute_as_intarray_tensor, CTX.set_intarray_attribute, CTX.get_attribute_as_int, NOT_APPLICABLE, CTX.set_int_attribute, ] INT_ARRAY_METHODS = [ CTX.get_attribute_as_nested_intarray, CTX.get_attribute_as_nested_intarray_tensor, CTX.set_nested_intarray_attribute, CTX.get_attribute_as_intarray, CTX.get_attribute_as_intarray_tensor, CTX.set_intarray_attribute, ] INT64_METHODS = [ CTX.get_attribute_as_int64array, UNSUPPORTED, CTX.set_int64array_attribute, CTX.get_attribute_as_int64, NOT_APPLICABLE, CTX.set_int64_attribute, ] INT64_ARRAY_METHODS = [ UNSUPPORTED, UNSUPPORTED, UNSUPPORTED, CTX.get_attribute_as_int64array, UNSUPPORTED, CTX.set_int64array_attribute, ] STRING_METHODS = [ CTX.get_attribute_as_stringlist, UNSUPPORTED, CTX.set_stringarray_attribute, CTX.get_attribute_as_string, NOT_APPLICABLE, CTX.set_string_attribute, ] UCHAR_METHODS = [ CTX.get_attribute_as_uchararray, UNSUPPORTED, CTX.set_uchararray_attribute, CTX.get_attribute_as_uchar, NOT_APPLICABLE, CTX.set_uchar_attribute, ] UCHAR_ARRAY_METHODS = [ UNSUPPORTED, UNSUPPORTED, UNSUPPORTED, CTX.get_attribute_as_uchararray, UNSUPPORTED, CTX.set_uchararray_attribute, ] UINT_METHODS = [ CTX.get_attribute_as_uintarray, UNSUPPORTED, CTX.set_uintarray_attribute, CTX.get_attribute_as_uint, NOT_APPLICABLE, CTX.set_uint_attribute, ] UINT_ARRAY_METHODS = [ UNSUPPORTED, UNSUPPORTED, UNSUPPORTED, CTX.get_attribute_as_uintarray, UNSUPPORTED, CTX.set_uintarray_attribute, ] UINT64_METHODS = [ CTX.get_attribute_as_uint64array, UNSUPPORTED, CTX.set_uint64array_attribute, CTX.get_attribute_as_uint64, NOT_APPLICABLE, CTX.set_uint64_attribute, ] UINT64_ARRAY_METHODS = [ UNSUPPORTED, UNSUPPORTED, UNSUPPORTED, CTX.get_attribute_as_uint64array, UNSUPPORTED, CTX.set_uint64array_attribute, ] # ============================================================================================================== def type_access_methods( ogn_type: og.Type, ) -> Tuple[Tuple[Callable, Callable, Callable, Callable, Callable, Callable], Optional[str]]: """Returns the tuple of lookup methods used for accessing attribute data of the passed in ogn_type""" if ogn_type.role in [og.AttributeRole.TRANSFORM, og.AttributeRole.MATRIX, og.AttributeRole.FRAME]: return [DOUBLE_MATRIX_METHODS, "double"] if ogn_type.base_type == og.BaseDataType.BOOL: return [BOOL_METHODS, None] if ogn_type.role in [og.AttributeRole.TEXT, og.AttributeRole.PATH] or ogn_type.base_type == og.BaseDataType.TOKEN: return [STRING_METHODS, None] if ogn_type.base_type == og.BaseDataType.DOUBLE: if ogn_type.tuple_count > 1: return [DOUBLE_ARRAY_METHODS, "double"] return [DOUBLE_METHODS, None] if ogn_type.base_type == og.BaseDataType.FLOAT: if ogn_type.tuple_count > 1: return [FLOAT_ARRAY_METHODS, "float"] return [FLOAT_METHODS, None] if ogn_type.base_type == og.BaseDataType.HALF: if ogn_type.tuple_count > 1: return [HALF_ARRAY_METHODS, "half"] return [HALF_METHODS, None] if ogn_type.base_type == og.BaseDataType.INT: if ogn_type.tuple_count > 1: return [INT_ARRAY_METHODS, "int"] return [INT_METHODS, None] if ogn_type.base_type == og.BaseDataType.INT64: return [INT64_METHODS, None] if ogn_type.base_type == og.BaseDataType.UCHAR: return [UCHAR_METHODS, None] if ogn_type.base_type == og.BaseDataType.UINT: return [UINT_METHODS, None] if ogn_type.base_type == og.BaseDataType.UINT64: return [UINT64_METHODS, None] return [[], None] # ==================================================================================================== # Conversion table for attribute base names in OGN to their base data type and role in the og.Type object OGN_NAMES_TO_TYPES = { "any": (og.BaseDataType.TOKEN, og.AttributeRole.NONE), "bool": (og.BaseDataType.BOOL, og.AttributeRole.NONE), "bundle": (og.BaseDataType.RELATIONSHIP, og.AttributeRole.BUNDLE), "colord": (og.BaseDataType.DOUBLE, og.AttributeRole.COLOR), "colorf": (og.BaseDataType.FLOAT, og.AttributeRole.COLOR), "colorh": (og.BaseDataType.HALF, og.AttributeRole.COLOR), "double": (og.BaseDataType.DOUBLE, og.AttributeRole.NONE), "execution": (og.BaseDataType.UINT, og.AttributeRole.EXECUTION), "float": (og.BaseDataType.FLOAT, og.AttributeRole.NONE), "frame": (og.BaseDataType.DOUBLE, og.AttributeRole.FRAME), "half": (og.BaseDataType.HALF, og.AttributeRole.NONE), "int": (og.BaseDataType.INT, og.AttributeRole.NONE), "int64": (og.BaseDataType.INT64, og.AttributeRole.NONE), "matrixd": (og.BaseDataType.DOUBLE, og.AttributeRole.MATRIX), "normald": (og.BaseDataType.DOUBLE, og.AttributeRole.NORMAL), "normalf": (og.BaseDataType.FLOAT, og.AttributeRole.NORMAL), "normalh": (og.BaseDataType.HALF, og.AttributeRole.NORMAL), "objectId": (og.BaseDataType.UINT64, og.AttributeRole.OBJECT_ID), "path": (og.BaseDataType.UCHAR, og.AttributeRole.PATH), "pointd": (og.BaseDataType.DOUBLE, og.AttributeRole.POSITION), "pointf": (og.BaseDataType.FLOAT, og.AttributeRole.POSITION), "pointh": (og.BaseDataType.HALF, og.AttributeRole.POSITION), "quatd": (og.BaseDataType.DOUBLE, og.AttributeRole.QUATERNION), "quatf": (og.BaseDataType.FLOAT, og.AttributeRole.QUATERNION), "quath": (og.BaseDataType.HALF, og.AttributeRole.QUATERNION), "string": (og.BaseDataType.UCHAR, og.AttributeRole.TEXT), "texcoordd": (og.BaseDataType.DOUBLE, og.AttributeRole.TEXCOORD), "texcoordf": (og.BaseDataType.FLOAT, og.AttributeRole.TEXCOORD), "texcoordh": (og.BaseDataType.HALF, og.AttributeRole.TEXCOORD), "timecode": (og.BaseDataType.DOUBLE, og.AttributeRole.TIMECODE), "token": (og.BaseDataType.TOKEN, og.AttributeRole.NONE), "transform": (og.BaseDataType.DOUBLE, og.AttributeRole.TRANSFORM), "uchar": (og.BaseDataType.UCHAR, og.AttributeRole.NONE), "uint": (og.BaseDataType.UINT, og.AttributeRole.NONE), "uint64": (og.BaseDataType.UINT64, og.AttributeRole.NONE), "vectord": (og.BaseDataType.DOUBLE, og.AttributeRole.VECTOR), "vectorf": (og.BaseDataType.FLOAT, og.AttributeRole.VECTOR), "vectorh": (og.BaseDataType.HALF, og.AttributeRole.VECTOR), } # ==================================================================================================== # Conversion table for attribute base names in USD to their base data type and role in the og.Type object. # There are some subtle differences here that are best explained through the table rather than programmatically. # The extra parameter is an override for tuple count. # In OGN they are all explicit (quatd[4]) in USD some are implicit (quatd) USD_NAMES_TO_TYPES = { "bool": (og.BaseDataType.BOOL, og.AttributeRole.NONE, None), "colord": (og.BaseDataType.DOUBLE, og.AttributeRole.COLOR, None), "colorf": (og.BaseDataType.FLOAT, og.AttributeRole.COLOR, None), "colorh": (og.BaseDataType.HALF, og.AttributeRole.COLOR, None), "double": (og.BaseDataType.DOUBLE, og.AttributeRole.NONE, None), "float": (og.BaseDataType.FLOAT, og.AttributeRole.NONE, None), "frame": (og.BaseDataType.DOUBLE, og.AttributeRole.FRAME, 16), "half": (og.BaseDataType.HALF, og.AttributeRole.NONE, None), "int": (og.BaseDataType.INT, og.AttributeRole.NONE, None), "int64": (og.BaseDataType.INT64, og.AttributeRole.NONE, None), "matrixd": (og.BaseDataType.DOUBLE, og.AttributeRole.NONE, None), "normald": (og.BaseDataType.DOUBLE, og.AttributeRole.NORMAL, None), "normalf": (og.BaseDataType.FLOAT, og.AttributeRole.NORMAL, None), "normalh": (og.BaseDataType.HALF, og.AttributeRole.NORMAL, None), "pointd": (og.BaseDataType.DOUBLE, og.AttributeRole.POSITION, None), "pointf": (og.BaseDataType.FLOAT, og.AttributeRole.POSITION, None), "pointh": (og.BaseDataType.HALF, og.AttributeRole.POSITION, None), "quatd": (og.BaseDataType.DOUBLE, og.AttributeRole.QUATERNION, 4), "quatf": (og.BaseDataType.FLOAT, og.AttributeRole.QUATERNION, 4), "quath": (og.BaseDataType.HALF, og.AttributeRole.QUATERNION, 4), "string": (og.BaseDataType.UCHAR, og.AttributeRole.TEXT, None), "texCoordd": (og.BaseDataType.DOUBLE, og.AttributeRole.TEXCOORD, None), "texCoordf": (og.BaseDataType.FLOAT, og.AttributeRole.TEXCOORD, None), "texCoordh": (og.BaseDataType.HALF, og.AttributeRole.TEXCOORD, None), "timecode": (og.BaseDataType.DOUBLE, og.AttributeRole.TIMECODE, None), "token": (og.BaseDataType.TOKEN, og.AttributeRole.NONE, None), "transform": (og.BaseDataType.DOUBLE, og.AttributeRole.TRANSFORM, 16), "uchar": (og.BaseDataType.UCHAR, og.AttributeRole.NONE, None), "uint": (og.BaseDataType.UINT, og.AttributeRole.NONE, None), "uint64": (og.BaseDataType.UINT64, og.AttributeRole.NONE, None), "vectord": (og.BaseDataType.DOUBLE, og.AttributeRole.VECTOR, None), "vectorf": (og.BaseDataType.FLOAT, og.AttributeRole.VECTOR, None), "vectorh": (og.BaseDataType.HALF, og.AttributeRole.VECTOR, None), }
12,504
Python
37.009118
118
0.681462
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/type_resolution.py
""" Utilities helpful for type resolution logic """ from typing import Sequence, Tuple import omni.graph.core as og __all__ = ["resolve_base_coupled", "resolve_fully_coupled"] # ================================================================================ def resolve_fully_coupled(attributes: Sequence[og.Attribute]) -> None: """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 we want the types of 'a' and 'b' to always match. This function will take under consideration the available conversions This function should only be called from `on_connection_type_resolve`. Args: attributes: list of extended attributes to be resolved """ attributes[0].get_node().resolve_coupled_attributes(attributes) # ================================================================================ def resolve_base_coupled(attribute_specs: Sequence[Tuple[og.Attribute, int, int, og.AttributeRole]]) -> None: """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. For example if node 'makeTuple2' has two input attributes 'a' and 'b' and one output 'c' and we want to resolve 'a':float, 'b':float, 'c':float[2] (convertible base types, different tuple counts) we would use the input: .. code-block:: python [ (node.get_attribute("inputs:a"), None, None, None), (node.get_attribute("inputs:b"), None, None, None), (node.get_attribute("outputs:c"), None, 1, None) ] Assuming `a` gets resolved first, the None will be set to the respective values for the resolved type (`a`). For this example, it will use defaults tuple_count=1, array_depth=0, role=NONE. This function should only be called from `on_connection_type_resolve`. Args: attribute_specs: list of (attribute, tuple_count, array_depth, role) of extended attributes to be resolved. 'None' for tuple_count, array_depth, or role means 'use the resolved type'. """ attributes = [a for a, _, _, _ in attribute_specs] tuples = [255 if b is None else b for _, b, _, _ in attribute_specs] arrays = [255 if c is None else c for _, _, c, _ in attribute_specs] roles = [og.AttributeRole.NONE if d is None else d for _, _, _, d in attribute_specs] attributes[0].get_node().resolve_partially_coupled_attributes(attributes, tuples, arrays, roles)
2,589
Python
45.249999
115
0.642719
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/util.py
from contextlib import contextmanager PROP_INFIX = "__PROP__" FUNC_INFIX = "__FUNC__" GET_SUFFIX = "__GET" SET_SUFFIX = "__SET" NAMESPACE_INFIX = "__NSP__" # ================================================================================ def sanitize_qualname(name: str) -> str: return name.replace(".", NAMESPACE_INFIX) # ================================================================================ def python_name_to_ui_name(name: str) -> str: # de-snake strings = name.split("_") case_corrected = [s.capitalize() if s.islower() else s for s in strings] return " ".join(case_corrected) # ================================================================================ def sanitized_name_to_ui_name(name: str) -> str: def correct_case(s): return s.capitalize() if s.islower() else s strings = name.split(NAMESPACE_INFIX) name = ".".join([correct_case(s) for s in strings]) strings = name.split(FUNC_INFIX) name = " : ".join([correct_case(s) for s in strings]) strings = name.split(PROP_INFIX) name = " : ".join([correct_case(s) for s in strings]) return name # ================================================================================ def is_private(name: str) -> bool: """checks if a name should be considered private""" return len(name) > 1 and name.startswith("_") # ================================================================================ def is_class_private(name: str) -> bool: """Checks if a name is a class private member. Used to warn if a name will get mangled. Based on https://github.com/python/cpython/blob/bd46174a5a09a54e5ae1077909f923f56a7cf710/Python/compile.c#L236-L258 """ return name.startswith("__") and not name.endswith("__") # ================================================================================ def is_dunder(name: str) -> bool: """Checks if a name is an internal python name. Based on https://github.com/python/cpython/blob/148f32913573c29250dfb3f0d079eb8847633621/Objects/typeobject.c#L3299-L3306 """ return len(name) > 4 and name.isascii() and name.startswith("__") and name.endswith("__") # ================================================================================ class GeneratedCode: """Tiny code generation utility""" strbuf = "" indent_level = 0 # -------------------------------------------------------------------------------- def line(self, txt: str): self.strbuf += self.indent_level * " " + txt + "\n" # -------------------------------------------------------------------------------- @contextmanager def indent(self, txt): try: self.line(txt) self.indent_level += 4 yield None finally: self.indent_level -= 4 # -------------------------------------------------------------------------------- def __repr__(self) -> str: return self.strbuf
2,966
Python
33.103448
116
0.450101
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/function.py
import copy import functools import inspect import json from collections import OrderedDict from typing import Callable, Dict, List, _GenericAlias import carb from . import type_definitions from .util import GeneratedCode EXEC_ATTRIBUTE_PREFIX = "exec" NODE_DATA_LITERAL = "node_data" # ================================================================================ class AutoFunctionWrapper(type_definitions.AutoNodeDefinitionWrapper): """Class to wrap python functions and classmethods. Contains methods for creating an Ogn annotation from a python function, and methods for applying values to the function. """ def __init__( self, func: Callable, *, pure: bool, ui_name: str, unique_name: str, tags: List[str], annotation: Dict = None ) -> None: super().__init__() self._func_proto = func self._func = func self._is_bound = hasattr(func, "__self__") self._returns_tuple = False self._argument_cache: Dict = {} self._has_node_data_signature = False self._node_impl = None self.python_name = func.__name__ or func.__qualname__ self.name = ui_name or self.python_name self.pure = pure or False if unique_name is None: raise NameError(f"{func.__qualname__} does not have a specified unique name") self.unique_name = unique_name self.descriptor = {} self.descriptor["uiName"] = self.name self.descriptor["version"] = 1 self.descriptor["language"] = "Python" self.descriptor["tags"] = tags or [] docstring = func.__doc__ or "[no documentation]" self.descriptor["description"] = f"{self.name}: {docstring}. Autogenerated" self.descriptor["inputs"] = OrderedDict( { f"_unique_name_{self.unique_name}": { "uiName": "Function Name", "type": "string", "description": "autogenerated qualified name", "metadata": {"hidden": 1}, "default": self.unique_name, } } ) if not self.pure: self.descriptor["tags"].append("action") self.descriptor["inputs"][EXEC_ATTRIBUTE_PREFIX] = { "uiName": "Exec", "description": "exec input", "type": "execution", } if annotation is not None: # If the annotation shim exists, use it: for key in annotation: if key == "return": self._set_output_type(annotation[key]) elif key == "self": # FIXME (OS): func.__class__ will not contain the whole type # in the case pybind is used self._add_input(key, func.__class__) else: self._add_input(key, annotation[key]) else: # fall back to inspection otherwise sig = inspect.signature(func) params = sig.parameters for name in params: item = params[name] if name == NODE_DATA_LITERAL: # This node holds state self._has_node_data_signature = True elif name == "self" and item.annotation is inspect._empty: self._add_input(item.name, func.__class__) else: self._add_input(item.name, item.annotation) self._set_output_type(sig.return_annotation) # -------------------------------------------------------------------------------- @staticmethod def get_type_signature(type_desc: type) -> Dict: """Constructs an Ogn type signature from the incoming type. If the type can be converted to a native Ogn type, the method attempts to do this automatically. Args: type_desc: a type object to describe an input type Returns: A dict object with Ogn properties """ if type_desc is None: return None conversion = type_definitions.AutoNodeTypeConversion.from_type(type_desc) ret = {"description": "autogenerated python type"} if conversion is not None: ret["type"] = conversion.og_type ret["default"] = conversion.default else: try: type_name = type_desc.__name__ except AttributeError: type_name = str(type_desc) ret["type"] = "objectId" ret["metadata"] = {"python_type_desc": type_name} return ret # -------------------------------------------------------------------------------- def _add_input(self, name: str, type_desc: type): """Adds an input to the function wrpper Args: name: a string to name the input in the node's public interface type_desc: a type for the function's public interface """ self.descriptor["inputs"][name] = AutoFunctionWrapper.get_type_signature(type_desc) self.descriptor["inputs"].move_to_end(name) # -------------------------------------------------------------------------------- def _set_output_type(self, type_desc: type): """Sets the function's output signature. Adds an "exec" port if the function isn't marked as "pure" If the function returns a 'Tuple' type, the Tuple is unpacked to individual node outputs, labeled 'out_0', 'out_1', etc. Args: type_desc: a return type """ outputs = OrderedDict() if not self.pure: outputs[EXEC_ATTRIBUTE_PREFIX] = {"type": "execution", "description": "autogenerated output"} if type_desc is None: self.descriptor["outputs"] = outputs return # Handle case where tuples are returned if isinstance(type_desc, _GenericAlias) and type_desc.__origin__ == tuple: self._returns_tuple = True if self._returns_tuple: for num, tuple_type_desc in enumerate(reversed(type_desc.__args__)): name = f"out_{num}" outputs[name] = AutoFunctionWrapper.get_type_signature(tuple_type_desc) outputs.move_to_end(name) else: outputs["out_0"] = AutoFunctionWrapper.get_type_signature(type_desc) outputs.move_to_end("out_0") self.descriptor["outputs"] = outputs # -------------------------------------------------------------------------------- def clear(self): """Resets all bindings in the function argument cache.""" self._argument_cache = {} self._func = self._func_proto # -------------------------------------------------------------------------------- @property def func(self) -> Callable: """Access to the bound function. Returns: A partially or fully bound function. """ if not self._func: self._func = self.class_ref.__getattribute__(self.python_name) # noqa: PLC2801,PLE1101 return self._func # -------------------------------------------------------------------------------- @property def is_bound(self) -> bool: """Whether the underlying function dependes on a specific self parameter""" return self._is_bound # -------------------------------------------------------------------------------- @property def has_node_data(self) -> bool: """Whether this function's signature has a "node data" component""" return self._has_node_data_signature # -------------------------------------------------------------------------------- def assign_input(self, name: str, value): """Assigns one of the function inputs into the function argument cache. Args: name: argument name value: unwrapped value to be applied. """ self._argument_cache[name] = value return self # -------------------------------------------------------------------------------- def assign_input_with_wrapper(self, name: str, value: type_definitions.AutographDataWrapper): """Unwraps an object wrapper and applies it to the function argument cache. Args: name: argument name value: object wrapper """ return self.assign_input(name, value.value) # -------------------------------------------------------------------------------- def assign_input_by_id(self, name: str, obj_id: int): """Retrieves an input from the object store by its id and applies it to the function argument cache. Args: name: argument name obj_id: the object ID for the argument wrapper, used to retrieve it from the object store Raises: KeyError in case the argument isn't found. """ try: wrapper = type_definitions.TypeRegistry.instance().refs.pop(obj_id) except KeyError as e: carb.log_error( f"""Input assignment error: Referenced input [{self.name}:{name}] not found in object store. It may have been consumed: {e}""" ) raise e return self.assign_input_with_wrapper(name, wrapper) # -------------------------------------------------------------------------------- def execute(self): """Executes the wrapped function and clears the argument cache. Returns: The function's return value, else None. Raises: ValueError if not all arguments in the argument cache are proerly filled """ args = {} if self.is_bound and "self" in self.descriptor["inputs"]: # method needs to provide its own 'self' func_name = self._func_proto.__name__ func_source = self._argument_cache["self"] # find the specific method bound to the 'self' we're after self._func = getattr(func_source, func_name) args.update({k: v for k, v in self._argument_cache.items() if k != "self"}) else: args.update(self._argument_cache) if len(args) > 0: self._func = functools.partial(self._func, **args) ret = self.func.__call__() # noqa: PLR1705,PLC2801 self.clear() return ret # -------------------------------------------------------------------------------- def execute_and_add_to_graph(self) -> int: """Executes the wrapped function and adds it to the object store if it has a return value. Does not attempt to convert to an existing Ogn type. Clears the underlying function argument cache. Returns: The object ID if added to the graph, 0 otherwise. """ ret = self.execute() if ret is not None: return type_definitions.TypeRegistry.add_to_graph(ret) return 0 # -------------------------------------------------------------------------------- def get_ogn(self) -> str: """Gets the Ogn function representation Returns: A JSON String with the representation """ d = {self.unique_name: self.descriptor} return json.dumps(d) def get_module_name(self) -> str: return self._func.__module__ def get_node_impl(self) -> type: if self._node_impl is None: class NodeImpl( AutographGenericFunction, unique_name=self.get_unique_name(), annotation=self.get_ogn(), # FIXME (OS): Change to actual type autograph_data={} if self.has_node_data else None, returns_tuple=self._returns_tuple, ): pass self._node_impl = NodeImpl return self._node_impl def get_unique_name(self) -> str: return self.unique_name # ================================================================================ class AutographGenericFunction: """Ogn Python function runner for single output""" def __init_subclass__(cls, unique_name: str, annotation: Dict, autograph_data: Dict, returns_tuple: bool) -> None: cls.unique_name = unique_name cls.annotation = json.loads(annotation)[unique_name] cls.autograph_data = autograph_data cls.returns_tuple = returns_tuple cls.generate_compute() # -------------------------------------------------------------------------------- @classmethod def generate_compute(cls): """Generates the compute function for an instntiated class. This code generator aims to minimize the size of code that runs at every frame """ code = GeneratedCode() code.line("@classmethod") with code.indent("def compute(*args) -> bool:"): code.line("cls = args[0]") code.line("db = args[1]") code.line(f"func_obj = type_definitions.TypeRegistry.get_func('{cls.unique_name}')") def key_filter(x: str) -> bool: ret = not x.startswith("_") # no private attributes ret &= not x.startswith(EXEC_ATTRIBUTE_PREFIX) # no exec attributes return not ret for key in cls.annotation["inputs"]: if key_filter(key): continue typename = cls.annotation["inputs"][key]["type"] conversion = type_definitions.AutoNodeTypeConversion.from_ogn_type(typename) if conversion: if conversion.og_to_type is not None: code.line( f"value = type_definitions.AutoNodeTypeConversion.from_ogn_type('{typename}')" f".og_to_type(db.inputs.{key})" ) else: code.line(f"value = db.inputs.{key}") code.line(f"func_obj.assign_input('{key}',value)") else: with code.indent("try:"): code.line(f"func_obj.assign_input_by_id('{key}', db.inputs.{key})") with code.indent("except KeyError as e:"): code.line( f"""carb.log_error("Failed to assign input at [{cls.unique_name} : {key}] : " + str(e))""" ) code.line("return False") if cls.autograph_data is not None: code.line(f"func_obj.assign_input('{NODE_DATA_LITERAL}', db.internal_state)") output_list = [ output for output in cls.annotation["outputs"] if output.startswith("out_") and output[len("out_") :].isnumeric() ] if len(output_list) == 0: code.line("func_obj.execute()") else: # this class returns something, unclear if native Ogn # extract the output; if it's a tuple iterate over values, if not continue for single value code.line("ret = func_obj.execute()") by_keys = {int(output[len("out_") :]): output for output in output_list} for key, output in by_keys.items(): if not cls.returns_tuple: code.line("out_value = ret") else: code.line(f"out_value = ret[{key}]") typename = cls.annotation["outputs"][output]["type"] conversion = type_definitions.AutoNodeTypeConversion.from_ogn_type(typename) if conversion: # convertible if conversion.type_to_og is not None: # converter = f"{conversion.type_to_og.__qualname__}" if ( conversion.type_to_og_conversion_method == type_definitions.AutoNodeTypeConversion.Method.ASSIGN ): # noqa code.line( f"db.outputs.out_{key} = type_definitions.AutoNodeTypeConversion" f".from_ogn_type('{typename}').type_to_og(out_value)" ) elif ( conversion.type_to_og_conversion_method == type_definitions.AutoNodeTypeConversion.Method.MODIFY ): # noqa code.line( f"type_definitions.AutoNodeTypeConversion.from_ogn_type('{typename}')" f".type_to_og(out_value, db.outputs.out_{key})" ) else: code.line(f"db.outputs.out_{key} = out_value") else: # non-convertible code.line("out_id = type_definitions.TypeRegistry.add_to_graph(out_value)") code.line(f"db.outputs.out_{key} = out_id") code.line("db.outputs.exec = True") code.line("return True") carb.log_verbose(f"Generated code for {cls.unique_name}:\n{str(code)}") exec(str(code), globals()) # noqa: PLW0122 # makes this generated function a class function cls.compute = compute # noqa - compute is defined by the exec # ================================================================================ @classmethod def internal_state(cls): return None if cls.autograph_data is None else copy.copy(cls.autograph_data)
17,782
Python
39.600457
118
0.500112
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/event.py
import codecs import pickle from abc import ABC, abstractmethod from enum import Enum from typing import Callable, Iterable, Optional, Tuple import carb.events # import omni.graph.core as og import omni.kit.app from .type_definitions import AutoNodeDefinitionGenerator, AutoNodeDefinitionWrapper, TypeRegistry from .util import is_private, python_name_to_ui_name, sanitize_qualname payload_path = "!path" # ================================================================================ class IEventStream(ABC): _event_type = None def __init__(self): raise RuntimeError("IEventStream: interfaces can't be instantiated.") # -------------------------------------------------------------------------------- @abstractmethod def create_subscription_to_pop(self, callback: Callable, name: Optional[str]): pass # -------------------------------------------------------------------------------- @abstractmethod def create_subscription_to_self(self, callback: Callable, name: Optional[str]): pass # -------------------------------------------------------------------------------- @abstractmethod def create_subscription_to_pop_by_type(self, callback: Callable, event_type: Enum, name: Optional[str]): pass # -------------------------------------------------------------------------------- @abstractmethod def create_subscription_to_push_by_type(self, callback: Callable, event_type: Enum, name: Optional[str]): pass # -------------------------------------------------------------------------------- @classmethod def get_event_type(cls): return cls._event_type # -------------------------------------------------------------------------------- @classmethod def __class_getitem__(cls, key: Enum): sanitized = sanitize_qualname(key.__name__) def create_subscription_to_pop_by_type(self, callback: Callable, event_type: key, name: Optional[str]): pass def create_subscription_to_push_by_type(self, callback: Callable, event_type: key, name: Optional[str]): pass ret = type( f"IEventStream_{sanitized}", (cls,), { "_event_type": key, "create_subscription_to_pop_by_type": create_subscription_to_pop_by_type, "create_subscription_to_push_by_type": create_subscription_to_push_by_type, }, ) return ret # ================================================================================ class EventSubscriptionType(Enum): NONE = 0 POP = 1 PUSH = 2 ALL = 3 # ================================================================================ class OgnOnEventInternalState: """Convenience class for maintaining per-node state information""" def __init__(self, event_stream): """Instantiate the per-node state information.""" # This subscription object controls the lifetime of our callback, it will be # cleaned up automatically when our node is destroyed self.sub = None # Set when the callback has triggered self.is_set = False # The last payload received self.payload = None # the event emitted # FIXME (OS): Handle push too self.subscription = event_stream.create_subscription_to_pop(self.on_event) # -------------------------------------------------------------------------------- def on_event(self, custom_event): """The event callback""" if custom_event is None: return self.is_set = True self.payload = custom_event.payload # -------------------------------------------------------------------------------- def try_pop_event(self): """Pop the payload of the last event received, or None if there is no event to pop""" if self.is_set: self.is_set = False payload = self.payload self.payload = None return payload return None # ================================================================================ class OgnOnEvent: """ This node triggers when the specified message bus event is received """ def __init_subclass__(cls, event_name: str, event_stream: Callable, **kwargs): cls.event_name = event_name cls.event_stream = event_stream cls.event_type = kwargs.get("event_type", None) cls.subscription_type = kwargs.get("subscription_type", EventSubscriptionType.POP) # -------------------------------------------------------------------------------- @classmethod def internal_state(*args): # noqa: PLE0211 """Returns an object that will contain per-node state information""" cls = args[0] internal_state = OgnOnEventInternalState(cls.event_stream) return internal_state # -------------------------------------------------------------------------------- @classmethod def initialize(*args): # noqa: PLE0211 # cls = args[0] # graph_context = args[1] # node = args[2] pass # -------------------------------------------------------------------------------- @classmethod def release(*args): # noqa: PLE0211 # node = args[1] pass # -------------------------------------------------------------------------------- @classmethod def compute(*args) -> bool: # noqa: PLE0211 """Compute the outputs from the current input""" # cls = args[0] db = args[1] state = db.internal_state payload = state.try_pop_event() if payload is None: return True # Copy the event dict contents into the output bundle db.outputs.bundle.clear() for name in payload.get_keys(): # Special 'path' entry gets copied to output attrib if name == payload_path: db.outputs.path = payload[name] continue as_str = payload[name] arg_obj = pickle.loads(codecs.decode(as_str.encode(), "base64")) attr_type, attr_value = arg_obj new_attr = db.outputs.bundle.insert((attr_type, name)) new_attr.value = attr_value db.outputs.execOut = True return True # ================================================================================ class AutoNodeEventStreamWrapper(AutoNodeDefinitionWrapper): def __init__(self, event_stream: IEventStream, event_name: str, module_name: str, **kwargs): super().__init__() self.event_name = event_name self.event_stream = event_stream self.event_type = event_stream.get_event_type() self.module_name = module_name self.subscription_type = kwargs.get("subscription_type", EventSubscriptionType.POP) # -------------------------------------------------------------------------------- def get_ogn(self): event_ogn = { f"On{self.event_name}": { "description": [ "Event node which fires when the specified custom event is sent.", "This node is used in combination with SendCustomEvent", ], "version": 1, "uiName": f"On {python_name_to_ui_name(self.event_name)}", "language": "Python", "state": {}, "inputs": {}, "outputs": { "path": { "type": "token", "description": "The path associated with the received custom event", "uiName": "Path", }, "bundle": {"type": "bundle", "description": "Bundle received with the event", "uiName": "Bundle"}, "execOut": { "type": "execution", "description": "Executes when the event is received", "uiName": "Received", }, }, } } return event_ogn # -------------------------------------------------------------------------------- def get_node_impl(self): class OgnOnEventWrapper( OgnOnEvent, event_name=self.event_name, event_stream=self.event_stream, event_type=self.event_type ): pass return OgnOnEventWrapper # -------------------------------------------------------------------------------- def get_unique_name(self): return self.event_name # -------------------------------------------------------------------------------- def get_module_name(self): return self.module_name # ================================================================================ class OgnForwardEventInternalState: """Convenience class for maintaining per-node state information""" # -------------------------------------------------------------------------------- def __init__(self, event_stream): """Instantiate the per-node state information.""" # This subscription object controls the lifetime of our callback, it will be # cleaned up automatically when our node is destroyed self.event_stream: IEventStream = event_stream self.event_name: str = "" self.subscription = None # -------------------------------------------------------------------------------- def start_forwarding(self): # FIXME (OS): Handle push too self.subscription = self.event_stream.create_subscription_to_pop(self.on_event) # -------------------------------------------------------------------------------- def stop_forwarding(self): self.subscription = None # -------------------------------------------------------------------------------- def on_event(self, custom_event): """The event callback""" if custom_event is None: return # Returns the internal name used for the given custom event name n = "omni.graph.action." + self.event_name name = carb.events.type_from_string(n) message_bus = omni.kit.app.get_app().get_message_bus_event_stream() message_bus.push(name, custom_event) # ================================================================================ class OgnForwardEvent: """ This node triggers when the specified message bus event is received """ # -------------------------------------------------------------------------------- def __init_subclass__(cls, event_name: str, event_stream: Callable, **kwargs): cls.event_name = event_name cls.event_stream = event_stream cls.event_type = kwargs.get("event_type", None) cls.subscription_type = kwargs.get("subscription_type", EventSubscriptionType.POP) # -------------------------------------------------------------------------------- @classmethod def internal_state(*args): # noqa: PLE0211 """Returns an object that will contain per-node state information""" cls = args[0] internal_state = OgnForwardEventInternalState(cls.event_stream) return internal_state # -------------------------------------------------------------------------------- @classmethod def compute(*args) -> bool: # noqa: PLE0211 """Compute the outputs from the current input""" # cls = args[0] db = args[1] state = db.internal_state if db.inputs.start_forwarding: evstream_id = db.inputs.event_stream state.event_stream = TypeRegistry.remove_from_graph(evstream_id).value state.event_name = db.inputs.event_name state.start_forwarding() if db.inputs.stop_forwarding: state.stop_forwarding() db.outputs.execOut = True return True # ================================================================================ class AutoNodeEventStreamForwardWrapper(AutoNodeDefinitionWrapper): def __init__(self, event_stream: IEventStream, event_name: str, module_name: str, **kwargs): super().__init__() self.event_name = event_name self.event_stream = event_stream self.event_type = event_stream.get_event_type() self.module_name = module_name self.subscription_type = kwargs.get("subscription_type", EventSubscriptionType.POP) # -------------------------------------------------------------------------------- def get_ogn(self): event_ogn = { f"Forward{self.event_name}": { "description": [ "This event forwards the output of this event stream to another named event stream", "It can be used in combination with OnCustomEvent.", ], "version": 1, "uiName": f"Forward {python_name_to_ui_name(self.event_name)}", "language": "Python", "state": {}, "inputs": { "start_forwarding": { "description": "Trigger this to begin forwarding events from the wrapped event stream" " to the main event stream", "type": "execution", "uiName": "Start forwarding events", }, "stop_forwarding": { "description": "Trigger this to stop any event forwarding to the main event stream.", "type": "execution", "uiName": "Stop forwarding", }, "event_stream": { "description": "Event stream to forward from", "type": "objectId", "uiName": "Event stream", "metadata": {"python_type_desc": "IEventStream"}, }, "event_name": { "description": "Name for outgoing events, to be used in 'On Custom Event' nodes.", "type": "string", "uiName": "Event Name", }, }, "outputs": { "execOut": { "type": "execution", "description": "Executes when the event is received", "uiName": "Received", } }, } } return event_ogn # -------------------------------------------------------------------------------- def get_node_impl(self): class OgnForwardEventWrapper( OgnForwardEvent, event_name=self.event_name, event_stream=self.event_stream, event_type=self.event_type ): pass return OgnForwardEventWrapper # -------------------------------------------------------------------------------- def get_unique_name(self): return self.event_name # -------------------------------------------------------------------------------- def get_module_name(self): return self.module_name # ================================================================================ class EventAutoNodeDefinitionGenerator(AutoNodeDefinitionGenerator): _name = "IEventStream" # -------------------------------------------------------------------------------- @classmethod def generate_from_definitions( # noqa: PLW0221 cls, target_type: type, type_name_sanitized: str, type_name_short: str, module_name: str ) -> Tuple[Iterable[AutoNodeDefinitionWrapper], Iterable[str]]: members_covered = set() generators = set() if issubclass(target_type, IEventStream): generators.add( AutoNodeEventStreamWrapper( event_stream=target_type, event_name=type_name_short, module_name=module_name ) ) generators.add( AutoNodeEventStreamForwardWrapper( event_stream=target_type, event_name=type_name_short, module_name=module_name ) ) members_covered.update(key for key in IEventStream.__dict__ if not is_private(key)) return generators, members_covered
16,417
Python
37.905213
118
0.460681
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/type_definitions.py
import enum from abc import ABC, abstractmethod from collections import namedtuple from typing import Callable, Dict, Iterable, NewType, Optional, Tuple import numpy as np Vector3d = NewType("Vector3d", np.ndarray) Vector3f = NewType("Vector3f", np.ndarray) Vector3h = NewType("Vector3h", np.ndarray) Float = NewType("Float", np.float) Float2 = NewType("Float2", np.ndarray) Float3 = NewType("Float3", np.ndarray) Float4 = NewType("Float4", np.ndarray) Half = NewType("Half", np.half) Half2 = NewType("Half2", np.ndarray) Half3 = NewType("Half3", np.ndarray) Half4 = NewType("Half4", np.ndarray) Double = NewType("Double", np.double) Double2 = NewType("Double2", np.ndarray) Double3 = NewType("Double3", np.ndarray) Double4 = NewType("Double4", np.ndarray) Int = NewType("Int", int) Int2 = NewType("Int2", np.ndarray) Int3 = NewType("Int3", np.ndarray) Int4 = NewType("Int4", np.ndarray) def int_to_int32(input: int) -> Int: return input & 0xFFFFFFFF Timecode = NewType("Timecode", float) Token = NewType("Token", str) UInt = NewType("UInt", np.uint) UChar = NewType("UChar", np.ubyte) def int_to_uchar(input: int) -> UChar: return input & 0xFF Matrix2d = NewType("Matrix2d", np.ndarray) Matrix3d = NewType("Matrix3d", np.ndarray) Matrix4d = NewType("Matrix4d", np.ndarray) Normal3f = NewType("Normal3f", np.ndarray) Normal3d = NewType("Normal3d", np.ndarray) Normal3h = NewType("Normal3h", np.ndarray) Point3f = NewType("Point3f", np.ndarray) Point3d = NewType("Point3d", np.ndarray) Point3h = NewType("Point3h", np.ndarray) Quatd = NewType("Quatd", np.ndarray) Quatf = NewType("Quatf", np.ndarray) Quath = NewType("Point3h", np.ndarray) TexCoord2d = NewType("TexCoord2d", np.ndarray) TexCoord2f = NewType("TexCoord2f", np.ndarray) TexCoord2h = NewType("TexCoord2h", np.ndarray) TexCoord3d = NewType("TexCoord3d", np.ndarray) TexCoord3f = NewType("TexCoord3f", np.ndarray) TexCoord3h = NewType("TexCoord3h", np.ndarray) Color3f = NewType("Color3f", np.ndarray) Color4f = NewType("Color4f", np.ndarray) Color3d = NewType("Color3d", np.ndarray) Color4d = NewType("Color4d", np.ndarray) Color3h = NewType("Color3h", np.ndarray) Color4h = NewType("Color4h", np.ndarray) all_types = [ Vector3d, Vector3f, Vector3h, Float, Float2, Float3, Float4, Half, Half2, Half3, Half4, Double, Double2, Double3, Double4, Int, Int2, Int3, Int4, Timecode, Token, UInt, UChar, Matrix2d, Matrix3d, Matrix4d, Normal3f, Normal3d, Normal3h, Point3f, Point3d, Point3h, Quatd, Quatf, Quath, TexCoord2d, TexCoord2f, TexCoord2h, TexCoord3d, TexCoord3f, TexCoord3h, Color3f, Color4f, Color3d, Color4d, Color3h, Color4h, ] TypeDesc = namedtuple( "TypeDesc", [ "type", "og_type", "type_to_og", "type_to_og_conversion_method", "og_to_type", "og_to_type_conversion_method", "default", ], ) # ================================================================================ class AutoNodeTypeConversion: """Static class for storing conversion methods between python types and Omnigraph types""" class Method(enum.Enum): ASSIGN = (0,) MODIFY = 1 # flake8: noqa: E241 types = [ TypeDesc(bool, "bool", bool, Method.ASSIGN, None, Method.ASSIGN, False), TypeDesc(Color3d, "colord[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Color3f, "colorf[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Color3h, "colorh[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Color4d, "colord[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(Color4f, "colorf[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(Color4h, "colorh[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(Double, "double", None, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Double2, "double[2]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0)), TypeDesc(Double3, "double[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Double4, "double[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(float, "double", None, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Float, "float", np.float, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Float2, "float[2]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0)), TypeDesc(Float3, "float[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Float4, "float[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(Half, "half", np.half, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Half2, "half[2]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0)), TypeDesc(Half3, "half[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Half4, "half[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(int, "int64", None, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Int, "int", int_to_int32, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Int2, "int[2]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0)), TypeDesc(Int3, "int[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Int4, "int[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(Matrix2d, "matrixd[2]", None, Method.ASSIGN, None, Method.ASSIGN, ((1, 0), (0, 1))), TypeDesc(Matrix3d, "matrixd[3]", None, Method.ASSIGN, None, Method.ASSIGN, ((1, 0, 0), (0, 1, 0), (0, 0, 1))), TypeDesc( Matrix4d, "matrixd[4]", None, Method.ASSIGN, None, Method.ASSIGN, ((1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)), ), TypeDesc(Normal3d, "normald[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Normal3f, "normalf[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Normal3h, "normalh[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Point3d, "pointd[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Point3f, "pointf[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Point3h, "pointh[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Quatd, "quatd[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(Quatf, "quatf[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(Quath, "quath[4]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0, 0)), TypeDesc(str, "string", None, Method.ASSIGN, None, Method.ASSIGN, ""), TypeDesc(TexCoord2d, "texcoordd[2]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0)), TypeDesc(TexCoord2f, "texcoordf[2]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0)), TypeDesc(TexCoord2h, "texcoordh[2]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0)), TypeDesc(TexCoord3d, "texcoordd[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(TexCoord3f, "texcoordf[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(TexCoord3h, "texcoordh[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Timecode, "timecode", None, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Token, "token", None, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(UInt, "uint", int_to_uchar, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(UChar, "uchar", int_to_uchar, Method.ASSIGN, None, Method.ASSIGN, 0), TypeDesc(Vector3d, "vectord[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Vector3f, "vectorf[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), TypeDesc(Vector3h, "vectorh[3]", None, Method.ASSIGN, None, Method.ASSIGN, (0, 0, 0)), ] user_types = [] # -------------------------------------------------------------------------------- def __init__(self): raise RuntimeError("AutoNodeTypeConversion is a static class, do not instantiate") # -------------------------------------------------------------------------------- @classmethod def from_type(cls, type_desc: type) -> Optional[TypeDesc]: """Searches the conversion registry using a python type. Args: type_desc: python type to convert Returns: TypeDesc for the found python type if it's found, None otherwise """ for tb in cls.user_types: if tb.type == type_desc: return tb for tb in cls.types: if tb.type == type_desc: return tb return None # -------------------------------------------------------------------------------- @classmethod def from_ogn_type(cls, og_type: str) -> Optional[TypeDesc]: """Searches the conversion registry using an Omnigraph type. Searches the user types first, defaults to the system types. Args: og_type: string representing the incoming ogn type Returns: TypeDesc for the found python type if it's found, None otherwise """ # TODO (OS): Solve for arrays for tb in cls.user_types: og_coded_type = tb.og_type if og_coded_type == og_type: return tb for tb in cls.types: og_coded_type = tb.og_type if og_coded_type == og_type: return tb return None # -------------------------------------------------------------------------------- @classmethod def register_type_conversion( cls, python_type: type, ogn_typename: str, python_to_ogn: Optional[Callable] = None, python_to_ogn_method: Method = Method.ASSIGN, ogn_to_python: Optional[Callable] = None, ogn_to_python_method: Method = Method.ASSIGN, default=None, ): """Registers a type conversion between a python type and an ogn type. Masks any existing system setting. If a previous user-submitted type conversion is registered, it will be overridden. Args: python_type: the type representation in python. ogn_typename: string representation of the ogn type. Node generation will fail if the type isn't recognized by ogn. python_to_ogn: [optional] function to convert a python return value to an OGN struct. Signature is Callable[[[python_type], object]. Defaults to None ogn_to_python: [optional] function to convert an OGN struct to a python return value. Signature is Callable[[[object], python_type]. Defaults to None """ desc = TypeDesc( python_type, ogn_typename, python_to_ogn, python_to_ogn_method, ogn_to_python, ogn_to_python_method, default ) unregistered = cls.unregister_type_conversion(python_type) if unregistered: carb.log_warn( "Registering an autograph type conversion for {type}->{ogn_typename} replaces anohter conversion for: {desc.type}->{og_type}" ) cls.user_types.append(desc) # -------------------------------------------------------------------------------- @classmethod def unregister_type_conversion(cls, python_type: type = None, ogn_type_name: str = None) -> Optional[TypeDesc]: """Unregisters a type conversion from python to ogn. Doesn't unregister system types. Args: python_type: the python type to be removed from support ogn_type_name: the ogn type name type to be removed from support Returns: The TypeDesc tuple just unregistered, or none. """ if python_type is not None: for desc in cls.user_types: if desc.type == python_type: cls.user_types.remove(desc) return desc if ogn_type_name is not None: for desc in cls.user_types: if desc.og_type == ogn_type_name: cls.user_types.remove(desc) return desc return None # ================================================================================ class AutoNodeDefinitionWrapper(ABC): """Container for a single node representation consumed by the Ogn code generator. Class is abstract and meant to be overridden. A sufficient implementation overrides these methods: * get_ogn(self) -> Dict * get_node_impl(self) * get_unique_name(self) -> str * get_module_name(self) -> str """ def __init__(self): super().__init__() # -------------------------------------------------------------------------------- @abstractmethod def get_ogn(self) -> Dict: """Get the Ogn dictionary representation of the node interface.""" return {} # -------------------------------------------------------------------------------- @abstractmethod def get_node_impl(self): """Returns the Ogn class implementing the node behavior. See omnigraph docuemntation on how to implement. A sufficient implementation contains a staticmethod with the function: compute(db) """ return None # -------------------------------------------------------------------------------- @abstractmethod def get_unique_name(self) -> str: """Get nodes unique name, to be saved as an accessor in the node database. Returns: the non-manlged unique name """ return "" # -------------------------------------------------------------------------------- @abstractmethod def get_module_name(self) -> str: """Get the module this autograph method was defined in. Returns: the module name """ return "" # ================================================================================ class AutoNodeDefinitionGenerator(ABC): """Defines an interface for generating a node definition""" _name = "" # -------------------------------------------------------------------------------- @classmethod def name(cls): return cls._name # -------------------------------------------------------------------------------- @classmethod @abstractmethod def generate_from_definitions(cls, new_type: type) -> Tuple[Iterable[AutoNodeDefinitionWrapper], Iterable[str]]: """This method scans the type new_type and outputs an AutoNodeDefinitionWrapper from it, representing the type, as well as a list of members it wishes to hide from the rest of the node extraction process. Args: new_type: the type to analyze by attribute Returns: a tuple of: Iterable[AutoNodeDefinitionWrapper] - an iterable of AutoNodeDefinitionWrapper - every node wrapper that is generated from this type. Iterable[str] - an iterable of all members covered by this handler that other handlers should ignore. """ pass class AutographDataWrapper: """Class to wrap around data being passed in the graph, to ensure a standard interface for passing data in the graph. Accepts both reference and value types. """ # -------------------------------------------------------------------------------- def __init__(self, value) -> None: self._value = value self._type = type(value) if isinstance(self._type, AutographDataWrapper): raise KeyError("Attempted to wrap a datawrapper") # -------------------------------------------------------------------------------- @property def value(self): """Returns the stored value without side effects""" return self._value # -------------------------------------------------------------------------------- @property def type(self) -> type: """Returns the value type stored at initialization time without side effects""" return self._type class AutographObjectStore: """Obejct store with simple put-pop interface.""" # -------------------------------------------------------------------------------- def __init__(self): self._store = {} # -------------------------------------------------------------------------------- def pop(self, obj_id: int) -> AutographDataWrapper: """Attempts to return a value from the object store, and deletes it from the store. Args: obj_id: the object ID to be retrieved Returns: an AutographDataWrapper if successful Raises: KeyError if the object isn't there. """ return self._store.pop(obj_id) # -------------------------------------------------------------------------------- def put(self, obj_id: int, value: AutographDataWrapper) -> Optional[AutographDataWrapper]: """Places an object in the object store according to an object ID. If an object already exists in the data store with the same ID, it is popped. Args: obj_id: integer object ID for input object value: the actual object ID. Does not check for types. Returns: The previous object with the same ID stored in the object store, None otherwise. """ swapped = self._store.get(obj_id, None) self._store[obj_id] = value return swapped # ================================================================================ class TypeRegistry: """Main singleton for storing graph objects and generating and registering functions.""" def __init__(self): raise RuntimeError("Singleton class, use instance() instead") # -------------------------------------------------------------------------------- def _initialize(self): self.class_to_methods: Dict[type, Dict[str, str]] = {} # Meant to make accessing functions easier self.func_name_to_func = {} # Meant to keep a pointer to an object, so it doesn't get garbage collected self.refs = AutographObjectStore() # Meant to handle types whene generating nodes self.type_handlers = set() # Stores omnigraph implementations self._impl_modules = {} # -------------------------------------------------------------------------------- @classmethod def _reset(cls): """Resets all internal data strucutres. Does not unregister nodes.""" cls.instance()._initialize() # -------------------------------------------------------------------------------- @classmethod def instance(cls): """Retrieves the class instance for this singleton. Returns: Class instance """ if not hasattr(cls, "_instance"): cls._instance = cls.__new__(cls) cls._instance._initialize() return cls._instance # -------------------------------------------------------------------------------- @classmethod def get_func(cls, unique_name: str) -> Optional[AutoNodeDefinitionWrapper]: """Retrieves a function from the object store Attributes unique_name: function's qualified name. Name mangling is handled by this class Returns: Function Wrapper. """ return cls.instance().func_name_to_func.get(unique_name, None) # -------------------------------------------------------------------------------- @classmethod def add_to_graph(cls, obj) -> int: """Adds an object `obj` to the data store without checking for uniqueness of held object. Does check uniqueness of reference object. Attributes obj: Object to add to the data store. Returns: the object id. """ wrapper = AutographDataWrapper(obj) obj_id = id(wrapper) cls.instance().refs.put(obj_id, wrapper) return obj_id # -------------------------------------------------------------------------------- @classmethod def remove_from_graph(cls, obj_id: int) -> AutographDataWrapper: """Attempts to remove an object ID from the object store. Attributes obj_id: the object ID to be removed from the data store. Returns: the object stored if it was found, None otherwise. """ return cls.instance().refs.pop(obj_id)
20,788
Python
36.867031
161
0.550125
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/core.py
import importlib from typing import Callable import omni.graph.tools.ogn as ogn from ..settings import Settings from .type_definitions import AutoNodeDefinitionWrapper, TypeRegistry # ============================================================================================================== class AutoNode: @staticmethod def registry(): return TypeRegistry.instance() # -------------------------------------------------------------------------------- @staticmethod def generate_code_and_store( wrapper: AutoNodeDefinitionWrapper, unique_name: str, *, module_name: str = None ) -> None: """Generates the implementation for the Ogn class and stores it in the registry. Attributes func_wrapper: Positional. The function wrapper object for which code should be generated. func_name: name of function getting stored. Name is assumed to be sanitized module_name: [optional] override the name of the module as detected by the reflection system. """ if not unique_name.find(".") == -1: raise NameError(f"{unique_name} is not a valid name for a class, since it contains a '.'") AutoNode.registry().func_name_to_func[unique_name] = wrapper name_prefixed = f"Ogn_{unique_name}" module_name = module_name or wrapper.get_module_name() code = ogn.code_generation( wrapper.get_ogn(), name_prefixed, module_name, "omni.graph.tools", Settings.generator_settings(), ) ################## # Code Injection # ################## # create a virtual module v_module = importlib.util.module_from_spec(globals()["__spec__"]) AutoNode.registry()._impl_modules[name_prefixed] = v_module # noqa: PLW0212 # inject dependencies into the generated module v_module.__dict__["AutoNode"] = AutoNode # v_module.__dict__.update([(a.__name__, a) for a in all_types]) # DANGER ZONE: execute the python node database definition in the target node exec(code["python"], vars(v_module)) # noqa: PLW0122 # inject the generated implementation into the module setattr(v_module, name_prefixed, wrapper.get_node_impl()) node_class = getattr(v_module, name_prefixed) # retrieve the registration action from the node db and register the node db_class = getattr(v_module, name_prefixed + "Database") do_register = db_class.register do_register(node_class) # -------------------------------------------------------------------------------- @staticmethod def generate_custom_node(wrapper: AutoNodeDefinitionWrapper): AutoNode.generate_code_and_store( wrapper, unique_name=wrapper.get_unique_name(), module_name=wrapper.get_module_name() ) # ============================================================================================================== class AutoNodeEvaluationDelayedExecutionQueue: _queue = [] def __init__(self): raise RuntimeError("AutoNodeEvaluationDelayedExecutionQueue is a singleton") # -------------------------------------------------------------------------------- @classmethod def instance(cls): if not hasattr(cls, "_instance"): cls._instance = cls.__new__(cls) # -------------------------------------------------------------------------------- @classmethod def add_to_queue(cls, callable_fn: Callable): cls.instance()._queue.append(callable_fn) # noqa: PLW0212 # -------------------------------------------------------------------------------- @classmethod def execute_queue(cls): while len(cls.instance()._queue) > 0: # noqa: PLW0212 callable_fn = cls.instance()._queue.pop() # noqa: PLW0212 callable_fn()
3,932
Python
37.558823
112
0.524669
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/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. Exports: `AutoClass`, `AutoFunc` How an AutoNode decorator works: # TODO How an AutoNode function execution works: 1. Attribute discovery Attributes are scanned from the db at runtime 2. Attribute type resolution types.py contains type conversion facilities to decide on the outgoing type of afunction 3. Attribute value resolution If needed, values are retrieved from the object store 4. Function execution function is called. 5. Return value resolution if the return value needs to be stored outside node, it happens now. 6. Dispatch to other nodes propagation of values and execution statnode""" # standard lib imports import inspect # meta imports from typing import Callable, Dict, List # framework imports import carb from .core import AutoNode from .enum_wrappers import EnumAutoNodeDefinitionGenerator from .event import EventAutoNodeDefinitionGenerator from .function import AutoFunctionWrapper from .property import AutoPropertyWrapper # module imports from .type_definitions import AutoNodeDefinitionGenerator from .util import FUNC_INFIX, GET_SUFFIX, PROP_INFIX, SET_SUFFIX, is_private, python_name_to_ui_name, sanitize_qualname # ================================================================================ def GenerateAutoFunc( # noqa: N802 func: Callable, *, qualname: str = None, ui_name: str = None, pure: bool = False, module_name: str = None, tags: List[str] = None, annotation: Dict = None, ): """Decorator for methods and function objects. Attributes func: the function object being wrapped. Should be a pure python function object or any other callable which has an `__annotations__` property. qualname: [optional] override the inferred qualified name ui_name: [optional] name that appears in the funcion's menu and node display. pure: [optional] override this function to be a pure function - a function independent of object state and without side effects, which doesn't enforce a specific execution order. module_name:[optional] override the inferred module name tags: [optional] annotation: [optional] override annotations """ qualname = qualname or func.__qualname__ unique_name = sanitize_qualname(qualname) module_name = module_name or func.__module__ ui_name = ui_name or python_name_to_ui_name(qualname) func_wrapper = AutoFunctionWrapper( func, unique_name=unique_name, ui_name=ui_name, pure=pure, tags=tags, annotation=annotation ) AutoNode.generate_code_and_store(func_wrapper, unique_name=unique_name, module_name=module_name) return func # ================================================================================ def GenerateAutoClass(target_class, *, module_name: str, annotation: Dict = None): # noqa: N802 """Decorator for classes. Registers the class in the type registry, and returns the wrapped class. Attributes target_class: class being wrapped. module_name: [optional] override the inferred module name annotation: a dict containing annotations for all members in the class. Used if passed a type with no annotations. """ class_directory = {} module_name = module_name or target_class.__module__ class_shortname = target_class.__name__ class_unique_name = f"{target_class.__qualname__}" class_sanitized_name = sanitize_qualname(target_class.__qualname__) # first, extract special type functionality and ignore special type helpers members_to_ignore = set() for type_handler in AutoNode.registry().type_handlers: definitions, members = type_handler.generate_from_definitions( target_type=target_class, type_name_sanitized=class_sanitized_name, type_name_short=class_shortname, module_name=module_name, ) for definition in definitions: AutoNode.generate_custom_node(definition) members_to_ignore.update(members) def _member_filter(name): ret = True ret &= not is_private(name) ret &= name not in members_to_ignore return ret members_to_scan = [key for key in target_class.__dict__ if _member_filter(key)] # scan remaining, ordinary members for key in members_to_scan: key_unique_name = f"{class_unique_name} : {python_name_to_ui_name(key)}" value = target_class.__dict__[key] if inspect.ismethoddescriptor(value): # this method came from C++, but isn't a function if annotation is None or key not in annotation: # can't handle instance methods for now carb.log_warn( f"Can't wrap {key_unique_name}: C functions require an annotation shim and none was provided" ) continue func_sanitized_name = f"{class_sanitized_name}{FUNC_INFIX}{key}" func_ui_name = f"{class_unique_name} : {python_name_to_ui_name(key)}" GenerateAutoFunc( value, qualname=func_sanitized_name, ui_name=func_ui_name, module_name=module_name, pure=False, annotation=annotation[key], ) class_directory[key] = func_sanitized_name elif inspect.isfunction(value): # python function object func_sanitized_name = f"{class_sanitized_name}{FUNC_INFIX}{key}" func_ui_name = f"{class_unique_name} : {python_name_to_ui_name(key)}" shim = annotation.get(key, None) if annotation else None GenerateAutoFunc( value, qualname=func_sanitized_name, ui_name=func_ui_name, module_name=module_name, pure=False, annotation=shim, ) class_directory[key] = func_sanitized_name elif inspect.isdatadescriptor(value): # has a getter, a setter and a deleter prop_sanitized_name = f"{class_sanitized_name}{PROP_INFIX}{key}" getter_sanitized_name = f"{prop_sanitized_name}{GET_SUFFIX}" getter_ui_name = f"{class_unique_name} : Get {key}" setter_sanitized_name = f"{prop_sanitized_name}{SET_SUFFIX}" setter_ui_name = f"{class_unique_name} : Set {key}" type_override = annotation.get(key, None) if annotation else None if not type_override: carb.log_warn(f"{class_unique_name}.{key} has no annotation, and will be skipped") continue getter_shim = {"return": type_override} setter_shim = {"value": type_override, "return": None} GenerateAutoFunc( value.getter, qualname=getter_sanitized_name, ui_name=getter_ui_name, module_name=module_name, annotation=getter_shim, ) GenerateAutoFunc( value.setter, qualname=setter_sanitized_name, ui_name=setter_ui_name, module_name=module_name, annotation=setter_shim, ) class_directory[key] = {"get": getter_sanitized_name, "set": setter_sanitized_name} else: # it's a value and should be wrapped in a property prop_sanitized_name = f"{class_sanitized_name}{PROP_INFIX}{key}" getter_sanitized_name = f"{prop_sanitized_name}{GET_SUFFIX}" getter_ui_name = f"{class_unique_name} : Get {key}" setter_sanitized_name = f"{prop_sanitized_name}{SET_SUFFIX}" setter_ui_name = f"{class_unique_name} : Set {key}" shim = annotation.get(key, None) if annotation else None wrapper = AutoPropertyWrapper(target_class, name=key, type_override=shim) GenerateAutoFunc( wrapper.get, qualname=getter_sanitized_name, ui_name=getter_ui_name, module_name=module_name, pure=False ) GenerateAutoFunc( wrapper.set, qualname=setter_sanitized_name, ui_name=setter_ui_name, module_name=module_name, pure=False ) class_directory[key] = {"get": getter_sanitized_name, "set": setter_sanitized_name} AutoNode.registry().func_name_to_func[prop_sanitized_name] = wrapper AutoNode.registry().class_to_methods[target_class] = class_directory return target_class ################################################################################## # # # public interface # # # ################################################################################## # ================================================================================ def AutoClass(**kwargs): # noqa: N802 # inject locals for linking if "module_name" not in kwargs: try: kwargs["module_name"] = inspect.currentframe().f_back.f_locals["__package__"] except (AttributeError, KeyError): kwargs["module_name"] = "default_module" carb.log_warn("No module name found in package. Assigning default name 'default_module'") def ret(cls): return GenerateAutoClass(cls, **kwargs) # noqa: PLE1125 ret.__doc__ = GenerateAutoClass.__doc__ return ret # ================================================================================ def AutoFunc(**kwargs): # noqa: N802 # inject locals for linking if "module_name" not in kwargs: try: kwargs["module_name"] = inspect.currentframe().f_back.f_locals["__package__"] except (AttributeError, KeyError): kwargs["module_name"] = "default_module" carb.log_warn("No module name found in package. Assigning default name 'default_module'") def ret(func): return GenerateAutoFunc(func, **kwargs) ret.__doc__ = GenerateAutoFunc.__doc__ return ret # ================================================================================ def register_autonode_type_extension(handler: AutoNodeDefinitionGenerator, **kwargs): # if "module_name" not in kwargs: # kwargs['module_name'] = inspect.currentframe().f_back.f_locals["__package__"] AutoNode.registry().type_handlers.add(handler) # ================================================================================ def unregister_autonode_type_extension(handler: AutoNodeDefinitionGenerator, **kwargs): # if "module_name" not in kwargs: # kwargs['module_name'] = inspect.currentframe().f_back.f_locals["__package__"] AutoNode.registry().type_handlers.remove(handler) # should help clean in hot reloads AutoNode.registry()._reset() # noqa: PLW0212 # Add Enums register_autonode_type_extension(EnumAutoNodeDefinitionGenerator) # Add Events register_autonode_type_extension(EventAutoNodeDefinitionGenerator)
11,670
Python
38.296296
120
0.594173
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/property.py
# ================================================================================ class AutoPropertyWrapper: """Wrapper to generate a getter and setter from a property in a class""" def __init__(self, target_class, name: str, *, type_override: type = None) -> None: try: self._type = type_override or target_class.__annotations__[name] except KeyError: self._type = type(target_class.__dict__[name]) self._name = name self.get.__annotations__["target"] = type(target_class) self.get.__annotations__["return"] = self._type self.set.__annotations__["target"] = type(target_class) self.set.__annotations__["value"] = self._type def get(self, target): return getattr(target, self._name) def set(self, target, value): # noqa: A003 setattr(target, self._name, value) return target
903
Python
35.159999
87
0.542636
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/autonode/enum_wrappers.py
from typing import Dict, Iterable, OrderedDict, Tuple import carb from .type_definitions import AutoNodeDefinitionGenerator, AutoNodeDefinitionWrapper from .util import GeneratedCode # ================================================================================ class OgnEnumExecutionWrapper: def __init_subclass__(cls, target_class: type) -> None: cls.target_class = target_class cls.member_names = list(target_class.__members__) cls.generate_compute() @classmethod def generate_compute(cls): code = GeneratedCode() code.line("from .type_definitions import TypeRegistry") code.line("@classmethod") with code.indent("def compute(*args):"): code.line("cls = args[0]") code.line("db = args[1]") with code.indent("if not db.inputs.exec:"): code.line("return True") code.line("input = db.inputs.enum") code.line("value = TypeRegistry.remove_from_graph(input).value") for name in cls.member_names: code.line(f"db.outputs.{name} = bool(value == cls.target_class.{name})") code.line("return True") carb.log_verbose(f"Generated code for {cls.target_class}:\n{str(code)}") exec(str(code), globals()) # noqa: PLW0122 cls.compute = compute # noqa: Defined in exec() code # ================================================================================ class OgnEnumWrapper(AutoNodeDefinitionWrapper): """Wrapper around Enums""" def __init__(self, target_class, unique_name: str, module_name: str, *, ui_name: str = None): super().__init__() self.target_class = target_class self.unique_name = unique_name self.ui_name = ui_name or target_class.__name__ self.module_name = module_name self.descriptor: Dict = {} self.descriptor["uiName"] = ui_name self.descriptor["version"] = 1 self.descriptor["language"] = "Python" self.descriptor["description"] = f"Enum Wrapper for {self.ui_name}" self.descriptor["inputs"] = OrderedDict( { "enum": { "uiName": "Input", "description": "Enum input", "type": "objectId", "default": 0, "metadata": {"python_type_desc": self.unique_name}, }, "exec": {"uiName": "Exec", "description": "Execution input", "type": "execution", "default": 0}, } ) def signature(name): return {"uiName": name, "description": f"Execute on {name}", "type": "execution", "default": 0} self.descriptor["outputs"] = OrderedDict({name: signature(name) for name in self.target_class.__members__}) # -------------------------------------------------------------------------------- def get_unique_name(self) -> str: return self.unique_name # -------------------------------------------------------------------------------- def get_module_name(self) -> str: return self.module_name # -------------------------------------------------------------------------------- def get_node_impl(self): class OgnEnumReturnType(OgnEnumExecutionWrapper, target_class=self.target_class): pass return OgnEnumReturnType # -------------------------------------------------------------------------------- def get_ogn(self) -> Dict: d = {self.unique_name: self.descriptor} return d # ================================================================================ class EnumAutoNodeDefinitionGenerator(AutoNodeDefinitionGenerator): _name = "Enum" # -------------------------------------------------------------------------------- @classmethod def generate_from_definitions( # noqa: PLW0221 cls, target_type: type, type_name_sanitized: str, type_name_short: str, module_name: str ) -> Tuple[Iterable[AutoNodeDefinitionWrapper], Iterable[str]]: members_covered = set() returned_generators = set() if hasattr(target_type, "__members__"): ret = OgnEnumWrapper( target_type, unique_name=type_name_sanitized, module_name=module_name, ui_name=f"Switch on {type_name_short}", ) members_covered.update(target_type.__members__) returned_generators.add(ret) return returned_generators, members_covered
4,582
Python
38.17094
115
0.498691
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/v1_5_0/update_file_format.py
"""File format upgrade utilities""" from typing import Any, Dict, List, Optional, Tuple import carb import omni.graph.core as og import omni.usd from omni.kit.commands import execute from pxr import Gf, OmniGraphSchema, Usd from .utils import ALLOW_IMPLICIT_GRAPH_SETTING, USE_SCHEMA_PRIMS_SETTING EXTENDED_ATTRIBUTE_SCOPED_CUSTOM_DATA_VERSION = og.FileFormatVersion(1, 5) LAST_FILE_FORMAT_VERSION_WITHOUT_SCHEMA = og.FileFormatVersion(1, 10) """TODO: This is the last file format version where it is possible to have OmniGraph prims that do not use the schema It should be updated when the final deprecation is made. """ # ============================================================================================================== def remove_global_compute_graph(old_format_version, new_format_version, graph): """If the setting to allow a global implicit graph is not on then remove it if found and replace it with a regular graph""" settings = carb.settings.get_settings() allow_implicit_graph = settings.get(ALLOW_IMPLICIT_GRAPH_SETTING) # If the schema is enabled it will fix the global compute graphs too use_schema_prims = settings.get(og.USE_SCHEMA_PRIMS_SETTING) if not allow_implicit_graph and not use_schema_prims: stage = omni.usd.get_context().get_stage() if stage is not None: iterator = iter(stage.TraverseAll()) for prim in iterator: if prim.GetTypeName() == "GlobalComputeGraph": carb.log_info( "Converting " + prim.GetPrimPath().pathString + "from GlobalComputeGraph to ComputeGraph" ) prim.SetTypeName("ComputeGraph") iterator.PruneChildren() # ============================================================================================================== def check_for_bare_connections(stage: Usd.Stage) -> List[str]: """Check for any of the old unsupported connections from nodes to prims that cannot exist in schema-based world Return: List of strings describing the forbidden connections found """ iterator = iter(stage.TraverseAll()) bad_connections = [] for prim in iterator: if prim.GetTypeName() in ["ComputeNode", "OmniGraphNode"]: for attribute in prim.GetAttributes(): for connected_path in attribute.GetConnections(): connected_prim = stage.GetPrimAtPath(connected_path.GetPrimPath()) if not connected_prim.IsValid(): carb.log_warn( f"Invalid connection found at {attribute.GetPath()}:" f" {connected_path.GetPrimPath()} while migrating to new schema" ) elif connected_prim.GetTypeName() not in ["ComputeNode", "OmniGraphNode"]: bad_connections.append(f"{prim.GetPrimPath()} - {connected_path}") return bad_connections # ============================================================================================================== def migrate_attribute_custom_data( old_format_version: og.FileFormatVersion, new_format_version: og.FileFormatVersion, _ ): """Add scoped customData to attributes which have the old format""" if old_format_version < EXTENDED_ATTRIBUTE_SCOPED_CUSTOM_DATA_VERSION: stage = omni.usd.get_context().get_stage() if stage is None: return iterator = iter(stage.TraverseAll()) for prim in iterator: if prim.GetTypeName() in ["OmniGraphNode", "ComputeNode"]: for attribute in prim.GetAttributes(): custom_data = attribute.GetCustomData() extended_type = custom_data.get("ExtendedAttributeType", None) if extended_type: attribute.SetCustomDataByKey("omni:graph:attrType", extended_type) iterator.PruneChildren() # ============================================================================================================== class OmniGraphSchemaMigrator: """Collection of methods to manage all of the steps involved in migrating an arbitrary graph to use schema prims""" def __init__(self): """Set up initial values""" self.__command_count = 0 # -------------------------------------------------------------------------------------------------------------- @property def stage(self) -> Usd.Stage: """Returns the stage in use - set as a property so that the latest version is always used as it changes""" return omni.usd.get_context().get_stage() # -------------------------------------------------------------------------------------------------------------- def __check_for_old_prim_nodes(self) -> List[str]: """Check for any of the old unsupported prim nodes that cannot exist in schema-based world Return: List of prim paths for any unsupported prim node types """ iterator = iter(self.stage.TraverseAll()) prim_nodes = [] for prim in iterator: if prim.GetTypeName() == "ComputeNode": node_type_attr = prim.GetAttribute("node:type") if node_type_attr.IsValid() and node_type_attr.Get() == "omni.graph.core.Prim": prim_nodes.append(prim.GetPrimPath()) return prim_nodes # -------------------------------------------------------------------------------------------------------------- def __change_prim_types_to_match_schema(self) -> List[Tuple[str, str, str]]: """Modify any old prim names to match the ones used by the schema Return: List of (path, old_type, new_type) for prims whose type was changed """ iterator = iter(self.stage.TraverseAll()) retyped = [] for prim in iterator: if prim.GetTypeName() in ["GlobalComputeGraph", "ComputeGraph"]: carb.log_info(f"Converting graph {prim.GetPrimPath()} from {prim.GetTypeName()} to OmniGraph") retyped.append((str(prim.GetPrimPath()), prim.GetTypeName(), "OmniGraph")) prim.SetTypeName("OmniGraph") elif prim.GetTypeName() == "ComputeNode": carb.log_info(f"Converting node {prim.GetPrimPath()} from ComputeNode to OmniGraphNode") retyped.append((str(prim.GetPrimPath()), prim.GetTypeName(), "OmniGraphNode")) prim.SetTypeName("OmniGraphNode") # Ensure that the schema-defined attributes on the node are no longer custom node_prim = OmniGraphSchema.OmniGraphNode(prim) if node_prim: node_type_attr = node_prim.GetNodeTypeAttr() if node_type_attr.IsValid(): if not node_type_attr.SetCustom(False): carb.log_warn(f"Failed to set node:type attribute to non-custom on {prim.GetPrimPath()}") else: carb.log_warn(f"OmniGraph prim node {prim.GetPrimPath()} has no node:type attribute") node_type_version_attr = node_prim.GetNodeTypeVersionAttr() if node_type_version_attr.IsValid(): if not node_type_version_attr.SetCustom(False): carb.log_warn( f"Failed to set node:typeVersion attribute to non-custom on {prim.GetPrimPath()}" ) else: carb.log_warn(f"OmniGraph prim node {prim.GetPrimPath()} has no node:type attribute") else: # This might be an error or it might just be the fact that the USD notification to change the type # hasn't been processed yet. As this is only temporary compatibility code and we know that when # reading a file the prims are immediately valid there is no need to add the complexity here to # tie into an event loop and await the USD notification propagation. pass return retyped # -------------------------------------------------------------------------------------------------------------- def __create_top_level_graph(self) -> List[Tuple[str, str]]: """If there are any nodes or settings not in a graph then create a graph for them and move them into it. Assumes that before calling this all of the old prim type names have been replaced with the schema prim type names. Args: stage: USD stage on which to replace settings Return: List of (old_path, new_path) for prims that were moved from the root level to a new graph Raises: og.OmniGraphError if the required prim changes failed """ iterator = iter(self.stage.TraverseAll()) # Collect this map of settings prim path onto the path at which the parent graph must be created prims_to_move = [] for prim in iterator: if prim.GetTypeName() in ["ComputeGraphSettings", "OmniGraphNode"]: parent = prim.GetParent() if not parent.IsValid() or parent.GetTypeName() != "OmniGraph": prims_to_move.append(prim) elif prim.GetTypeName() in ["ComputeGraph", "OmniGraph"]: iterator.PruneChildren() prim_paths_moved = [] if prims_to_move: carb.log_info(f"Creating top level graph for global nodes {[prim.GetPrimPath() for prim in prims_to_move]}") for prim in prims_to_move: parent_path = str(prim.GetParent().GetPrimPath()) if parent_path[-1] != "/": parent_path += "/" default_global_graph_path = f"{parent_path}__graphUsingSchemas" global_graph_prim = self.stage.GetPrimAtPath(default_global_graph_path) if not global_graph_prim: (status, result) = execute("CreatePrim", prim_path=default_global_graph_path, prim_type="OmniGraph") if not status: raise og.OmniGraphError( f"Error creating OmniGraph prim at {default_global_graph_path} - {result}" ) new_prim_path = f"{default_global_graph_path}/{prim.GetName()}" prim_paths_moved.append((str(prim.GetPrimPath()), new_prim_path)) carb.log_info(f"Move {prim.GetPrimPath()} -> {new_prim_path}") (status, result) = execute("MovePrim", path_from=prim.GetPrimPath(), path_to=new_prim_path) if not status: raise og.OmniGraphError( f"Error moving OmniGraph prim from {prim.GetPrimPath()} to {new_prim_path} - {result}" ) return prim_paths_moved # -------------------------------------------------------------------------------------------------------------- def __replace_settings_with_properties(self, new_file_format_version: Tuple[int, int]) -> List[str]: """If there are any of the old settings prims move their property values into their containing graph. Args: new_file_format_version: The file format version that should be used for the graph setting Return: List of prim paths with settings that were transferred to the containing graph and then deleted """ iterator = iter(self.stage.TraverseAll()) prims_to_remove = [] for prim in iterator: # noqa: PLR1702 if prim.GetTypeName() == "ComputeGraphSettings": carb.log_info(f"Moving settings from {prim.GetPrimPath()} into the parent graph") graph_prim = prim.GetParent() # Need to check against the old types as well as the USD change notices may not have percolated if graph_prim.IsValid() and graph_prim.GetTypeName() in [ "GlobalComputeGraph", "ComputeGraph", "OmniGraph", ]: for attr in prim.GetAttributes(): setting_name = attr.GetName() setting_value = attr.Get() if setting_name == "flatCacheBacking": setting_name = "fabricCacheBacking" if setting_value == "StagedWithHistory": setting_value = "StageWithHistory" graph_attr = graph_prim.GetAttribute(setting_name) if not graph_attr.IsValid(): graph_attr = graph_prim.CreateAttribute( setting_name, attr.GetTypeName(), custom=False, variability=attr.GetVariability() ) if graph_attr.IsValid(): graph_attr.Set(setting_value) else: carb.log_warn( f"Could not create settings attribute {attr.GetName()}" f" on graph {graph_prim.GetPrimPath()}" ) prims_to_remove.append(str(prim.GetPrimPath())) schema_prim = OmniGraphSchema.OmniGraph(graph_prim) if bool(schema_prim): file_format_version_attr = schema_prim.GetFileFormatVersionAttr() file_format_version_attr.Set(Gf.Vec2i(new_file_format_version)) else: carb.log_warn(f"Could not cast graph prim {graph_prim.GetPrimPath()} to OmniGraph schema") else: carb.log_warn(f"Could not find graph above {prim.GetPrimPath()} to receive settings") elif prim.GetTypeName() == "ComputeNodeMetadata": # Take advantage of the loop to also get rid of the obsolete metadata children prims_to_remove.append(str(prim.GetPrimPath())) if prims_to_remove: (status, result) = execute("DeletePrims", paths=prims_to_remove) if not status: raise og.OmniGraphError(f"Error deleting prims {prims_to_remove} - {result}") return prims_to_remove # -------------------------------------------------------------------------------------------------------------- # Handling for old files that did not use the OmniGraph schema (earlier than 1.3) def update(self, new_file_format_version: Optional[Tuple[int, int]] = None) -> Dict[str, Any]: """Update the current file to use the new schema. This can run either before OmniGraph has attached to the stage (e.g. when reading in an old file) or when an explicit migration has been requested (e.g. when an old file exists and the user wants to migrate it). In both cases if any prim types have been migrated the useSchemaPrims setting will be forced to True so that subsequent OmniGraph additions use the schema types. (Mostly because this is easier than trying to track the state of whether a graph contains such prims already.) Conversion of old scenes entails: - Changing any ComputeGraph or GlobalComputeGraph prims to be OmniGraph types - If a ComputeGraphSettings prim exists, migrating its attribute values to the OmniGraph prim - Changing any ComputeNode prims to be OmniGraphNode types - If any ComputeNode prims appear without a parent ComputeGraph then create a default graph and move them into it Args: new_file_format_version: The file format version that should be used for the graph setting. If None then it will force the version immediately following the schema conversion (1, 4) Return: A dictionary of operations that were performed as part of the migration (key describes the operation, value is the objects to which it was applied) """ stage = omni.usd.get_context().get_stage() if stage is None: return {"message": "No stage to convert"} try: self.__command_count = 0 return_values = {} # Verify that the old prim nodes don't exist old_prim_nodes = self.__check_for_old_prim_nodes() if old_prim_nodes: raise og.OmniGraphError( f"Deprecated omni.graph.core.Prim nodes not allowed with schema - {old_prim_nodes}" ) # Verify that bare connections from OmniGraph nodes to non-OmniGraph prims do not exist bare_connections = check_for_bare_connections(self.stage) if bare_connections: raise og.OmniGraphError( "Deprecated connections from an OmniGraph node to a USD Prim not allowed with schema" f" - {bare_connections}" ) # First pass - change ComputeGraph/GlobalComputeGraph -> OmniGraph and ComputeNode -> OmniGraphNode return_values["Prim Types Changed"] = self.__change_prim_types_to_match_schema() # Second pass - if there are any OmniGraphNode or ComputeGraphSettings prims not in a graph, # create one and move them into it return_values["Root Prims Moved To Graph"] = self.__create_top_level_graph() # Third pass - move settings from their own prim to the parent graph prim if new_file_format_version is None: new_file_format_version = (1, 4) return_values["Settings Removed"] = self.__replace_settings_with_properties(new_file_format_version) # Now that the scene has been migrated the schema setting has to be enabled or bad things will happen. # Don't bother doing it if nothing changed though. if any(return_values.values()): carb.settings.get_settings().set(USE_SCHEMA_PRIMS_SETTING, True) return return_values except og.OmniGraphError as error: # If anything failed it would leave the graph in a hybrid state so try to restore it back to its original # state so that it remains stable. carb.log_error(str(error)) for _i in range(self.__command_count): omni.kit.undo() return_values = {} return return_values # ============================================================================================================== # Handling for old files that did not use the OmniGraph schema (earlier than 1.3) def update_to_include_schema(new_file_format_version: Optional[Tuple[int, int]] = None) -> Dict[str, Any]: """Update the current file to use the new schema. See OmniGraphSchemaMigrator.update() for details This can run either before OmniGraph has attached to the stage (e.g. when reading in an old file) or when an explicit migration has been requested (e.g. when an old file exists and the user wants to migrate it). In both cases if any prim types have been migrated the useSchemaPrims setting will be forced to True so that subsequent OmniGraph additions use the schema types. (Mostly because this is easier than trying to track the state of whether a graph contains such prims already.) Conversion of old scenes entails: - Changing any ComputeGraph or GlobalComputeGraph prims to be OmniGraph types - If a ComputeGraphSettings prim exists, migrating its attribute values to the OmniGraph prim - Changing any ComputeNode prims to be OmniGraphNode types - If any ComputeNode prims appear without a parent ComputeGraph create a default graph and move them into it Args: new_file_format_version: The file format version that should be used for the graph setting. If None then it will force the version immediately following the schema conversion (1, 4) Return: A dictionary of operations that were performed as part of the migration (key describes the operation, value is the objects to which it was applied) Raises: og.OmniGraphError if any of the attempted changes failed - will attempt to restore graph to original state """ return OmniGraphSchemaMigrator().update() # ============================================================================================================== # Handling for old files that did not use the OmniGraph schema (earlier than 1.3) def cb_update_to_include_schema( old_version: Optional[og.FileFormatVersion], new_version: Optional[og.FileFormatVersion], graph: Optional[og.Graph] ) -> Dict[str, Any]: """Callback invoked when a file is loaded to update old files to use the new schema. This will be called anytime a file is loaded with a non-current version. The old version and new version are checked to confirm that the values cross over the boundary when schemas were created, and if so then the schema information is applied to the file. Args: old_version: Version the file to upgrade uses new_version: Current file version expected graph: Graph to convert (only present for historical reasons - the entire stage is updated) Return: A dictionary of operations that were performed as part of the migration (key describes the operation, value is the objects to which it was applied) """ # If the setting to automatically migrate is not on then there is nothing to do here if not carb.settings.get_settings().get(USE_SCHEMA_PRIMS_SETTING): return {} # If the file format version is one of the ones that must contain schema prims no migration is needed if old_version is not None and ( old_version.majorVersion > LAST_FILE_FORMAT_VERSION_WITHOUT_SCHEMA.majorVersion or ( old_version.majorVersion == LAST_FILE_FORMAT_VERSION_WITHOUT_SCHEMA.majorVersion and old_version.minorVersion > LAST_FILE_FORMAT_VERSION_WITHOUT_SCHEMA.minorVersion ) ): return {"message": f"File format version {old_version} already uses the schema"} return update_to_include_schema((new_version.majorVersion, new_version.minorVersion)) # -------------------------------------------------------------------------------------------------------------- RESETTING_USE_SCHEMA_PRIMS = False """Global variable to avoid potential infinite recursion when restoring the useSchemaPrims setting""" RESETTING_IMPLICIT_GRAPH = False """Global variable to avoid potential infinite recursion when restoring the allowGlobalImplicitGraph setting""" # -------------------------------------------------------------------------------------------------------------- def can_set_use_schema_prims_setting(new_value: bool) -> str: """Check to see if a new value for the schema prims setting is valid - returns warning text, empty if okay""" def __prim_types_in_scene(prim_types: List[str]) -> bool: """Returns true if the scene contains prims whose types are any in the list""" found_prims = [] stage = omni.usd.get_context().get_stage() if stage is not None: iterator = iter(stage.TraverseAll()) for prim in iterator: if prim.GetTypeName() in prim_types: found_prims.append(f"{prim.GetPrimPath()} : {prim.GetTypeName()}") return found_prims if new_value: forbidden_prims = __prim_types_in_scene( ["ComputeGraphSettings", "ComputeNode", "ComputeGraph", "GlobalComputeGraph"] ) if forbidden_prims: return f"Cannot enable {USE_SCHEMA_PRIMS_SETTING} when the scene contains old style prims {forbidden_prims}" bare_connections = check_for_bare_connections(check_for_bare_connections(omni.usd.get_context().get_stage())) if bare_connections: return ( f"Cannot enable {USE_SCHEMA_PRIMS_SETTING} when the scene contains" f" direct prim connections {bare_connections}" ) else: forbidden_prims = __prim_types_in_scene(["OmniGraph", "OmniGraphNode"]) if forbidden_prims: return f"Cannot disable {USE_SCHEMA_PRIMS_SETTING} when the scene contains schema prims {forbidden_prims}" return ""
24,664
Python
53.089912
120
0.579144
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/v1_5_0/omnigraph_helper.py
# noqa: PLC0302 r"""Deprecated class that handles interactions with the OmniGraphs - use og.Controller instead _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ """ import os from contextlib import suppress from typing import Any, Dict, List, Optional, Tuple, Union import omni.graph.core as og import omni.graph.tools as ogt import omni.kit.commands from carb import log_info, log_warn from pxr import Sdf, Tf, Usd from ..errors import OmniGraphError from ..object_lookup import ObjectLookup from ..typing import Attribute_t, Node_t from ..utils import DBG_EVAL, dbg_eval from .context_helper import ContextHelper from .utils import ( ATTRIBUTE_TYPE_HINTS, ATTRIBUTE_TYPE_OR_LIST, ATTRIBUTE_TYPE_TYPE_HINTS, ATTRIBUTE_VALUE_PAIR, ATTRIBUTE_VALUE_PAIRS, EXTENDED_ATTRIBUTE_TYPE_HINTS, NODE_TYPE_HINTS, NODE_TYPE_OR_LIST, ) # Function argument types passed to the various graph interface operations ConnectData_t = Tuple[Node_t, Attribute_t, Node_t, Attribute_t] ConnectDatas_t = Union[ConnectData_t, List[ConnectData_t]] CreateNodeData_t = Tuple[str, Node_t] CreateNodeDatas_t = Union[CreateNodeData_t, List[CreateNodeData_t]] CreatePrimData_t = Tuple[str, Dict[str, Tuple[str, Any]]] CreatePrimDatas_t = Union[CreatePrimData_t, List[CreatePrimData_t]] DeleteNodeData_t = str DeleteNodeDatas_t = Union[DeleteNodeData_t, List[DeleteNodeData_t]] DisconnectData_t = Tuple[Node_t, Attribute_t, Node_t, Attribute_t] DisconnectDatas_t = Union[DisconnectData_t, List[DisconnectData_t]] SetValueData_t = Tuple[Attribute_t, Any] SetValueDatas_t = Union[SetValueData_t, List[SetValueData_t]] # Decoded attribute bundle possibilities BundledAttribute_t = Optional[Union[Usd.Prim, Usd.Property]] # ===================================================================== @ogt.DeprecatedClass("og.OmniGraphHelper is deprecated after version 1.5.0. Use og.Controller instead.") class OmniGraphHelper: """Class to provide a simple interface to OmniGraph manipulation functions Provides functions for creating nodes, making and breaking connections, and setting values. Graph manipulation functions are undoable, value changes are not. The main benefit this class provides over direct manipulation of the graph is that it accepts a variety of types for its operations. e.g. a connection could take an OmniGraph Node, a USD Prim, or a string indicating the path to the node. Attributes: graph: The OmniGraph on which operations will be performed. Raises: OmniGraphError: If there is not enough information to perform the requested operation """ # Type of connection point PRIM_TYPE = 0 BUNDLE_TYPE = 1 REGULAR_TYPE = 2 UNKNOWN = -1 # ---------------------------------------------------------------------- def __init__(self, omnigraph: Optional[og.Graph] = None): """Initialize the graph""" if omnigraph is None: self.graph = og.get_current_graph() else: self.graph = omnigraph # ---------------------------------------------------------------------- def context(self): """Returns the evaluation context for the graph to which this helper is attached""" return self.graph.get_default_graph_context() # ---------------------------------------------------------------------- async def evaluate(self): """Wait for the next Graph evaluation cycle - await this function to ensure it is finished before returning. If the graph evaluation time is not incremented after 10 application updates, RuntimeError is raised. """ start_t = self.context().get_time_since_start() # Ensure that a graph evaluation has happened before returning for _ in range(10): await omni.kit.app.get_app().next_update_async() now_t = self.context().get_time_since_start() if now_t > start_t: return raise RuntimeError(f"Graph evaluation time {now_t} was not incremented from start time {start_t}") # ---------------------------------------------------------------------- @staticmethod def safe_node_name(node_type_name: str, abbreviated: bool = False) -> str: """Returns a USD-safe node name derived from the node_type_name (stripping namespace) Args: node_type_name: Fully namespaced name of the node type abbreviated: If True then remove the namespace, else just make the separators into underscores Returns: A safe node name that roughly corresponds to the given node type name """ if abbreviated: last_namespace = node_type_name.rfind(".") if last_namespace < 0: return node_type_name return node_type_name[last_namespace + 1 :] return node_type_name.replace(".", "_") # ---------------------------------------------------------------------- def omnigraph_node(self, node_info: NODE_TYPE_OR_LIST) -> Union[og.Node, List[og.Node]]: """Returns the OmniGraph node(s) corresponding to the variable type parameter Args: node_info: Information for the node to find. If a list then iterate over the list Returns: Node(s) corresponding to the description(s) in the current graph, None where there is no match Raises: OmniGraphError if the node description wasn't one of the recognized types """ return ObjectLookup.node(node_info) # ---------------------------------------------------------------------- def omnigraph_attribute( self, node: NODE_TYPE_HINTS, attribute_info: ATTRIBUTE_TYPE_OR_LIST ) -> Union[og.Attribute, List[og.Attribute]]: """Returns the OmniGraph attribute(s) corresponding to the variable type parameter Args: node: Node to which the attribute belongs. Ignored if attribute_info is an og.Attribute attribute_info: Information on which attribute to look for. If a list then get all of them Returns: Attribute(s) matching the description(s) - None where there is no match Raises: OmniGraphError if the attribute description wasn't one of the recognized types, or if any of the attributes could not be found """ return ObjectLookup.attribute(attribute_info, node) # ---------------------------------------------------------------------- def node_as_prim(self, node: NODE_TYPE_HINTS) -> Usd.Prim: """Returns the prim corresponding to the variable type parameter""" if isinstance(node, Sdf.Path): return omni.usd.get_context().get_stage().GetPrimAtPath(node.GetPrimPath()) if isinstance(node, og.Node): return omni.usd.get_context().get_stage().GetPrimAtPath(node.get_prim_path()) if isinstance(node, Usd.Prim): return node with suppress(Exception): if isinstance(node, str): return omni.usd.get_context().get_stage().GetPrimAtPath(self.graph.get_node(node).get_prim_path()) raise OmniGraphError(f"Failed to get prim on {node}") # ---------------------------------------------------------------------- def get_prim_path(self, node: NODE_TYPE_HINTS): """Returns the prim path corresponding to the variable type parameter""" if isinstance(node, Sdf.Path): return node.GetPrimPath() if isinstance(node, og.Node): return node.get_prim_path() if isinstance(node, Usd.Prim): return node.GetPath() with suppress(Exception): if isinstance(node, str): return self.graph.get_node(node).get_prim_path() raise OmniGraphError(f"Failed to get prim path on {node}") # ---------------------------------------------------------------------- # begin-create-attribute-function def create_attribute( self, node: NODE_TYPE_HINTS, attr_name: str, attr_type: ATTRIBUTE_TYPE_TYPE_HINTS, attr_port: Optional[og.AttributePortType] = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT, attr_default: Optional[Any] = None, attr_extended_type: Optional[ EXTENDED_ATTRIBUTE_TYPE_HINTS ] = og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR, ) -> Optional[og.Attribute]: """Create a new dynamic attribute on the node Args: node: Node on which to create the attribute (path or og.Node) attr_name: Name of the new attribute, either with or without the port namespace attr_type: Type of the new attribute, as an OGN type string or og.Type attr_port: Port type of the new attribute, default is og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT attr_default: The initial value to set on the attribute, default is None attr_extended_type: The extended type of the attribute, default is og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR. If the extended type is og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION then this parameter will be a 2-tuple with the second element being a list or comma-separated string of union types Returns: The newly created attribute, None if there was a problem creating it """ # end-create-attribute-function ogt.dbg(f"Create attribute '{attr_name}' on node {node} of type {attr_type}") omg_node = self.omnigraph_node(node) omg_attr_type = ObjectLookup.attribute_type(attr_type) (success, result) = og.cmds.CreateAttr( node=omg_node, attr_name=attr_name, attr_type=omg_attr_type, attr_port=attr_port, attr_default=attr_default, attr_extended_type=attr_extended_type, ) if not result or not success: return None namespace = og.get_port_type_namespace(attr_port) if not attr_name.startswith(namespace): if ( omg_attr_type.get_type_name() == "bundle" and attr_port != og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ): separator = "_" else: separator = ":" attr_name = f"{namespace}{separator}{attr_name}" return omg_node.get_attribute(attr_name) # ---------------------------------------------------------------------- # begin-remove-attribute-function def remove_attribute(self, attribute: ATTRIBUTE_TYPE_HINTS, node: Optional[NODE_TYPE_HINTS] = None) -> bool: """Removes an existing dynamic attribute from a node. Args: attribute: Name of the attribute to be removed node: If not None and the attribute is specified as a string then this is the node on which it lives Returns: True if the attribute was successfully removed, else False """ # end-remove-attribute-function ogt.dbg(f"Remove attribute {attribute} using node {node}") omg_attribute = self.omnigraph_attribute(node, attribute) (success, result) = og.cmds.RemoveAttr(attribute=omg_attribute) return success and result # ---------------------------------------------------------------------- def create_node( self, node_path: str, node_type: str, allow_exists: bool = False, version: Optional[int] = None ) -> og.Node: """Create an OmniGraph node of the given type and version at the given path. Args: node_path: SdfPath to the node in the stage node_type: Type of node to create check_exists: If true then succeed if a node with matching path, type, and version already exists version: Version of the node type to create. By default it creates the most recent. Raises: OmniGraphError: If the node already existed Returns: OmniGraph node added to the scene, or None if it could not be created """ ogt.dbg(f"Create '{node_path}' of type '{node_type}', allow={allow_exists}, version={version}") if version is not None: raise OmniGraphError("Creating nodes with specific versions not supported") node = self.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 == current_node_type: return node error = f"already exists as type {current_node_type}" else: error = "already exists" raise OmniGraphError(f"Creation of {node_path} as type {node_type} failed - {error}") og.cmds.CreateNode(graph=self.graph, node_path=node_path, node_type=node_type, create_usd=True) return self.graph.get_node(node_path) # ---------------------------------------------------------------------- def create_prim(self, prim_path: str, attribute_info: Dict[str, Tuple[Union[str, og.Type], Any]]): """Create a prim node containing a predefined set of attribute values and a ReadPrim OmniGraph node for it Args: prim_path: Location of the prim attribute_info: Dictionary of {NAME: (TYPE, VALUE)} for all prim attributes The TYPE is in OGN format, so "float[3][]", "bundle", etc. The VALUE should be in a format suitable for passing to pxr::UsdAttribute.Set() Returns: og.Node of the created node """ stage = omni.usd.get_context().get_stage() omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="BundleSource") prim = stage.GetPrimAtPath(prim_path) # Walk the list of attribute descriptions, creating them on the prim as they go for attribute_name, (attribute_type_name, attribute_value) in attribute_info.items(): if isinstance(attribute_type_name, og.Type): attribute_type = attribute_type_name attribute_type_name = attribute_type.get_ogn_type_name() else: attribute_type = og.AttributeType.type_from_ogn_type_name(attribute_type_name) manager = ogt.get_attribute_manager_type(attribute_type_name) sdf_type_name = manager.sdf_type_name() if sdf_type_name is not None: sdf_type = getattr(Sdf.ValueTypeNames, sdf_type_name) usd_value = og.attribute_value_as_usd(attribute_type, attribute_value) prim.CreateAttribute(attribute_name, sdf_type).Set(usd_value) # Add the new Prim to OmniGraph return og.cmds.CreateNode( graph=self.graph, node_path=prim_path, node_type="omni.graph.core.Prim", create_usd=False )[1] # ---------------------------------------------------------------------- def delete_node(self, node: NODE_TYPE_HINTS, allow_noexists: bool = False) -> bool: """Deletes an OmniGraph node at the given path. Args: node: node to be deleted allow_noexists: If true then succeed if no node with matching path exists Raises: OmniGraphError: If the node does not exist Returns: True if the node is gone """ ogt.dbg(f"Delete '{node}', allow_noexists={allow_noexists}") try: omnigraph_node = self.omnigraph_node(node) except Exception: if allow_noexists: return True raise return og.cmds.DeleteNode(graph=self.graph, node_path=omnigraph_node.get_prim_path(), modify_usd=True)[0] # ---------------------------------------------------------------------- def attach_to_prim(self, prim: Union[Usd.Prim, str]) -> og.Node: """Create a new compute node attached to an ordinary USD prim. Args: prim: Prim node or name of prim node to which the OmniGraph node should attach Returns: OmniGraph Prim type node associated with the passed in Prim """ ogt.dbg(f"Attach to prim {prim}") if isinstance(prim, str): prim_path = prim else: prim_path = str(prim.GetPath()) return self.create_node(prim_path, "omni.graph.core.Prim", allow_exists=True) # ---------------------------------------------------------------------- @staticmethod def get_attr_type_name(attr): """ Get the type name for the given attribute, taking in to account extended type Args: attr: Attribute whose type is to be determined Returns: The type name of the attribute """ type_name = None with suppress(AttributeError): if attr.get_extended_type() in [ og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_ANY, og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_UNION, ]: type_name = attr.get_resolved_type().get_type_name() if type_name is None: try: type_name = attr.get_type_name() except AttributeError: type_name = attr.get_type().get_type_name() return type_name # ---------------------------------------------------------------------- @staticmethod def get_attr_type(attr: Union[og.Attribute, og.AttributeData]): """ 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 """ return attr.get_resolved_type() if isinstance(attr, og.Attribute) else attr.get_type() # ---------------------------------------------------------------------- def _decode_connection_point( self, node_info: NODE_TYPE_HINTS, attr_info: ATTRIBUTE_TYPE_HINTS ) -> Tuple[int, Optional[Usd.Prim], og.Node, Optional[og.Attribute]]: """Decode a connection point into identifying pieces Args: node_info: Identifying information for an OmniGraph node attr_info: Identifying information for an OmniGraph node's attribute Returns: (location_type, prim, node, attribute) location_type: what type of connection point this is - bundle, regular, or prim prim: Prim of the connection point, or None if it is not a prim type node: og.Node of the connection point, or None if it is a prim attribute: og.Attribute of the connection point, or None if it is a prim Raises: OmniGraphError if the configuration of the connection point is not consistent """ attr_type = self.UNKNOWN prim = None node = node_info attr = None if attr_info is None: prim = self.node_as_prim(node_info) if not prim.IsValid(): raise OmniGraphError("When attribute is None, node must be a valid Prim") attr_type = self.PRIM_TYPE else: node = self.omnigraph_node(node_info) if not node.is_valid(): raise OmniGraphError("When attribute is specified, node must be a valid OmniGraph node") attr = self.omnigraph_attribute(node, attr_info) if not attr.is_valid(): raise OmniGraphError("Attribute is not valid") if attr.get_type_name() == "bundle": attr_type = self.BUNDLE_TYPE else: attr_type = self.REGULAR_TYPE assert attr_type != self.UNKNOWN return (attr_type, prim, node, attr) # ---------------------------------------------------------------------- def _decode_connection_type( self, src_node_info: NODE_TYPE_HINTS, src_attr_info: ATTRIBUTE_TYPE_HINTS, dst_node_info: NODE_TYPE_HINTS, dst_attr_info: ATTRIBUTE_TYPE_HINTS, ) -> Tuple[Union[Usd.Prim, og.Attribute], og.Attribute]: """ Decode the node and source information into an Attribute->Attribute connection or a Prim->Bundle connection. Everything is set up to be fairly generic so that if we have more general connections in the future it can still be handled using the same framework. The source and destination comes from _decode_connection_point() with these legal cases: Prim -> bundleAttribute src_attr_info is None, src_node_info is Prim, dst_attr_info.type == bundle bundleAttribute -> bundleAttribute src_attr_info.type == dst_attr_info.type == bundle attribute -> attribute src_attr_info.type != bundle, dst_attr_info.type != bundle Args: src_node_info: Node on the source (input) end of the connection. src_attr_info: Attribute on the source (input) end of the connection - None means connect from a Prim. dst_node_info: Node on the destination (output) end of the connection. dst_attr_info: Attribute on the destination (output) end of the connection. Returns: (src_location, dst_location): If a Prim->Bundle connection: src_location: Usd.Prim where the connection originates dst_location: og.Attribute where the connection terminates If an Attribute->Attribute connection src_location: og.Attribute where the connection originates dst_location: og.Attribute where the connection terminates Raises: OmniGraphError: If the connection request doesn't fall into one of the allowed cases """ src_location = None dst_location = None src_path = f"{self.get_prim_path(src_node_info)}.{src_attr_info}" dst_path = f"{self.get_prim_path(dst_node_info)}.{dst_attr_info}" try: (src_type, src_prim, src_node, src_attr) = self._decode_connection_point(src_node_info, src_attr_info) (dst_type, _, dst_node, dst_attr) = self._decode_connection_point(dst_node_info, dst_attr_info) if src_type == self.PRIM_TYPE: if dst_type == self.PRIM_TYPE: raise OmniGraphError("Prim -> Prim connection not valid, use AddRelationship/RemoveRelationship") if dst_type == self.REGULAR_TYPE: raise OmniGraphError("Prim -> Attribute connection not allowed") if not dst_node or not dst_node.is_valid() or not dst_attr: raise OmniGraphError("Destination is invalid") # Prim -> Bundle connection if dst_type == self.BUNDLE_TYPE: src_location = src_prim dst_location = dst_attr ogt.dbg(f"Prim -> Bundle {src_path} -> {dst_path}") elif src_type == self.BUNDLE_TYPE: if dst_type == self.REGULAR_TYPE: raise OmniGraphError("Bundle -> Attribute connection not allowed") if not src_node or not src_node.is_valid() or not src_attr: raise OmniGraphError("Source is invalid") if not dst_node or not dst_node.is_valid() or not dst_attr: raise OmniGraphError("Destination is invalid") # Bundle -> Bundle connection if dst_type == self.BUNDLE_TYPE: src_location = src_attr dst_location = dst_attr ogt.dbg(f"Bundle -> Bundle {src_path} -> {dst_path}") # Bundle -> Prim connection if dst_type == self.PRIM_TYPE: raise OmniGraphError("Bundle -> Prim connection not allowed") else: if dst_type == self.PRIM_TYPE: raise OmniGraphError("Attribute -> Prim connection not allowed") if dst_type == self.BUNDLE_TYPE: raise OmniGraphError("Attribute -> Bundle connection not allowed") if not src_node or not src_node.is_valid() or not src_attr: raise OmniGraphError("Source is invalid") if not dst_node or not dst_node.is_valid() or not dst_attr: raise OmniGraphError("Destination is invalid") # Attribute -> Attribute connection src_location = src_attr dst_location = dst_attr ogt.dbg(f"Attribute -> Attribute {src_path} -> {dst_path}") except OmniGraphError as error: raise OmniGraphError(f"{src_path} -> {dst_path}") from error return (src_location, dst_location) # ---------------------------------------------------------------------- def connect( self, src_node: NODE_TYPE_HINTS, src_attr: ATTRIBUTE_TYPE_HINTS, dst_node: NODE_TYPE_HINTS, dst_attr: ATTRIBUTE_TYPE_HINTS, ): """Create a connection between two attributes Args: src_node: Node on the source (input) end of the connection. Ignored if src_attr is an og.Attribute src_attr: Attribute on the source (input) end of the connection. (If None then it's a prim connection) dst_node: Node on the destination (output) end of the connection. Ignored if dst_attr is an og.Attribute dst_attr: Attribute on the destination (output) end of the connection. Raises: OmniGraphError: If nodes or attributes could not be found, or connection fails """ ogt.dbg(f"Connect {src_node},{src_attr} -> {dst_node},{dst_attr}") (src_location, dst_location) = self._decode_connection_type(src_node, src_attr, dst_node, dst_attr) if src_location is None or dst_location is None: success = False error = "Connection locations not recognized" elif isinstance(src_location, Usd.Prim): ogt.dbg(" Connect Prim -> Bundle") (success, error) = og.cmds.ConnectPrim( attr=dst_location, prim_path=src_location.GetPath().pathString, is_bundle_connection=src_attr is not None, ) else: ogt.dbg(f" Connect Attr {src_location.get_name()} to {dst_location.get_name()}") (success, error) = og.cmds.ConnectAttrs(src_attr=src_location, dest_attr=dst_location, modify_usd=True) if not success: raise OmniGraphError( f"Failed to connect {self.get_prim_path(src_node)}.{src_attr}" f" -> {self.get_prim_path(dst_node)}.{dst_attr} ({error})" ) # ---------------------------------------------------------------------- def disconnect( self, src_node: NODE_TYPE_HINTS, src_attr: ATTRIBUTE_TYPE_HINTS, dst_node: NODE_TYPE_HINTS, dst_attr: ATTRIBUTE_TYPE_HINTS, ): """Break a connection between two attributes Args: src_node: Node on the source (input) end of the connection. Ignored if src_attr is an og.Attribute src_attr: Attribute on the source (input) end of the connection. If None then it is a prim connection. dst_node: Node on the destination (output) end of the connection. Ignored if dst_attr is an og.Attribute dst_attr: Attribute on the destination (output) end of the connection. Raises: OmniGraphError: If nodes or attributes could not be found, connection didn't exist, or disconnection fails """ ogt.dbg(f"Disconnect {src_node},{src_attr} -> {dst_node},{dst_attr}") (src_location, dst_location) = self._decode_connection_type(src_node, src_attr, dst_node, dst_attr) if src_location is None or dst_location is None: success = False error = "Connection locations not recognized" elif isinstance(src_location, Usd.Prim): (success, error) = og.cmds.DisconnectPrim( attr=dst_location, prim_path=src_location.GetPath().pathString, is_bundle_connection=src_attr is not None, ) else: ogt.dbg(f" Disconnect Attr {src_location.get_name()} from {dst_location.get_name()}") (success, error) = og.cmds.DisconnectAttrs(src_attr=src_location, dest_attr=dst_location, modify_usd=True) if not success: raise OmniGraphError( f"Failed to disconnect {self.get_prim_path(src_node)}.{src_attr}" f" -> {self.get_prim_path(dst_node)}.{dst_attr} ({error})" ) # ---------------------------------------------------------------------- def disconnect_all( self, attr: ATTRIBUTE_TYPE_HINTS, node: Optional[NODE_TYPE_HINTS] = None, ): """Break all connections to and from an attribute Args: attr: Attribute on the source (input) end of the connection. If None then it is a prim connection. node: Node on the source (input) end of the connection. Ignored if attr is an og.Attribute Raises: OmniGraphError: If nodes or attributes could not be found, connection didn't exist, or disconnection fails """ ogt.dbg(f"Disconnect all on {node},{attr}") attribute = self.omnigraph_attribute(node, attr) if attribute is None: success = False error = "Disconnection attribute not recognized" else: ogt.dbg(f" Disconnect All from {attribute.get_name()}") (success, error) = og.cmds.DisconnectAllAttrs(attr=attribute, modify_usd=True) if not success: raise OmniGraphError(f"Failed to break connections on {self.get_prim_path(node)}.{attr} ({error})") # ---------------------------------------------------------------------- def set_attribute_data_values( self, values_to_set: List[Tuple[og.AttributeData, Any]], graph: Optional[og.Graph] = None ): """Set a bunch of attribute data values Args: values_to_set: List of (AttributeData, Value) pairs which are the values to be set Raises: OmniGraphError: If values could not be set """ if not values_to_set: return for (attribute_data, value) in values_to_set: try: (success, error) = og.cmds.SetAttrData(attribute_data=attribute_data, value=value, graph=graph) if not success: raise TypeError(error) except TypeError as error: raise OmniGraphError(f"Could not set value on attribute data '{attribute_data.get_name()}'") from error # ---------------------------------------------------------------------- def set_attribute_values(self, values_to_set: List[Tuple[og.Attribute, Any]], ignore_usd: bool = False): """Set a bunch of attribute values Dict values can be used to specify a type in additional to a value. If the attribute is unresolved, it will be resolved to that type before setting the value. For example: set_attribute_values([(attrib, {"type": "float2", "value": (1.0, 2.0)})]) Args: values_to_set: List of (Attribute, Value) pairs which are the values to be set. ignore_usd: If False then report any problems updating the USD attributes Raises: OmniGraphError: If values could not be set """ if not values_to_set: return for (attribute, value) in values_to_set: set_type = None if isinstance(value, dict): # special case - we may need to resolve the attribute to this particular type before setting set_type = value["type"] value = value["value"] try: (success, error) = og.cmds.SetAttr(attr=attribute, value=value, set_type=set_type) if not success: raise TypeError(error) except TypeError as error: raise OmniGraphError(f"Could not set value on attribute '{attribute.get_name()}'") from error # ---------------------------------------------------------------------------------------------------- # TODO: This is necessary to update USD at the moment. Updating flatcache and USD should be handled # directly in SetAttrCommand. Once that has been done this can be deleted. # { stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(attribute.get_node().get_prim_path()) if prim.IsValid() and attribute.get_extended_type() == og.ExtendedAttributeType.EXTENDED_ATTR_TYPE_REGULAR: try: # The Set method wants USD types for some attribute types so do the translation first value = og.attribute_value_as_usd(OmniGraphHelper.get_attr_type(attribute), value) prim.GetAttribute(attribute.get_name()).Set(value) except Tf.ErrorException as error: if not ignore_usd: log_warn(f"Could not sync USD on attribute {attribute.get_name()} - {error}") except TypeError as error: # TODO: This occurs when the parameters to Set() don't match what USD expects. It could be fixed # by special-casing every known mismatch but this section should be going away so it won't # be done at this time. The current known failures are the quaternion types and arrays of the # tuple-arrays (e.g. "quatd[4]", "double[3][]", "float[2][]", ...) if not ignore_usd: log_info(f"Could not set value on attribute {attribute.get_name()} - {error}") except Exception as error: # noqa: PLW0703 log_warn(f"Unknown problem setting values - {error}") # } # ---------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------- def set_values(self, node: NODE_TYPE_HINTS, values_to_set: ATTRIBUTE_VALUE_PAIRS, ignore_usd: bool = False): """Set a bunch of attribute values on a single node This is general purpose for handling all types of node and attribute descriptions. If you already have the og.Attributes whose values you wish to set then call set_attribute_values() instead. Args: node: Node on which the values are to be set values_to_set: List or single element of (Attribute, Value) pairs which are the values to be set ignore_usd: If False then report any problems updating the USD attributes Raises: OmniGraphError: If nodes or attributes could not be found, or values could not be set """ if not values_to_set: log_warn("Tried to set values from an empty list") return omnigraph_node = self.omnigraph_node(node) def set_a_value(attribute_and_value: ATTRIBUTE_VALUE_PAIR): """Try to set a single value, raising an OmniGraphError exception if anything went wrong""" if len(attribute_and_value) != 2: raise OmniGraphError(f"Values to set should be (attribute, value) pairs, not '{attribute_and_value}'") attribute = self.omnigraph_attribute(omnigraph_node, attribute_and_value[0]) self.set_attribute_values([(attribute, attribute_and_value[1])], ignore_usd=ignore_usd) if isinstance(values_to_set, list): if values_to_set and not isinstance(values_to_set[0], tuple) and not isinstance(values_to_set[0], list): log_warn(f"Call set_values() with a tuple or array of tuples as attribute values, not {values_to_set}") set_a_value(values_to_set) else: for attribute_and_value in values_to_set: set_a_value(attribute_and_value) else: set_a_value(values_to_set) # ---------------------------------------------------------------------- def get_attribute_values(self, attributes_to_get: List[og.Attribute]) -> List[Any]: """Get the values from a list of defined attributes Args: attributes_to_get: List of attributes whose values are to be retrieved Returns: List of values corresponding to the list of attributes passed in """ results = [] context_helper = ContextHelper() for attribute in attributes_to_get: try: results.append(context_helper.get_attr_value(attribute)) except TypeError as error: raise OmniGraphError(f"Could not get value on attribute '{attribute.get_name()}'") from error return results # ---------------------------------------------------------------------- def get_values(self, node: NODE_TYPE_HINTS, attributes_to_get: ATTRIBUTE_TYPE_OR_LIST) -> List[Any]: """Get the values from attributes on a node This is general purpose for handling all types of node and attribute descriptions. If you already have the og.Attributes whose values you wish to retrieve then call get_attribute_values() instead. Args: node: Description of node whose values are to be read attributes_to_get: One or a list of descriptions of attributes whose values are to be retrieved Raises: OmniGraphError: If nodes or attributes could not be found, or values could not be read Returns: One or a list of values corresponding to the attributes passed in """ omnigraph_node = self.omnigraph_node(node) if not isinstance(attributes_to_get, List): return self.get_attribute_values([self.omnigraph_attribute(omnigraph_node, attributes_to_get)])[0] return self.get_attribute_values( [self.omnigraph_attribute(omnigraph_node, attribute) for attribute in attributes_to_get] ) # ---------------------------------------------------------------------- def _edit_delete_nodes(self, root_prim: str, nodes_to_delete: DeleteNodeData_t): """Delete the set of nodes passed, using the format required by edit_graph""" delete_list = nodes_to_delete if isinstance(nodes_to_delete, list) else [nodes_to_delete] for node_name in delete_list: dbg_eval(f"Deleting node {node_name}") node_path = os.path.join(root_prim, node_name).replace("\\", "/") self.delete_node(node_path, False) dbg_eval(f"... deleted {node_path}") # ---------------------------------------------------------------------- def _edit_create_nodes(self, root_prim: str, nodes_to_create: CreateNodeData_t): """Create the set of nodes passed, using the format required by edit_graph Returns a tuple of the map from node path to the created node, and the list of constructed nodes""" node_path_map = {} nodes_constructed = [] create_list = nodes_to_create if isinstance(nodes_to_create, list) else [nodes_to_create] for node_type, node_name in create_list: dbg_eval(f"Creating node {node_name} of type {node_type}") node_path = os.path.join(root_prim, node_name).replace("\\", "/") node_path_map[node_name] = self.create_node(node_path, node_type, False) nodes_constructed.append(node_path_map[node_name]) dbg_eval(f"... created {node_path_map[node_name]}") return (node_path_map, nodes_constructed) # ---------------------------------------------------------------------- def _edit_create_prims( self, root_prim: str, node_path_map: Dict[str, og.Node], nodes_constructed: List[og.Node], prims_to_create: CreatePrimData_t, ): """Create the set of prims passed, using the format required by edit_graph""" create_list = prims_to_create if isinstance(prims_to_create, list) else [prims_to_create] for prim_path, attribute_info in create_list: dbg_eval(f"Creating prim at {prim_path}") node_path = os.path.join(root_prim, prim_path).replace("\\", "/") node_path_map[prim_path] = self.create_prim(node_path, attribute_info) nodes_constructed.append(node_path_map[prim_path]) dbg_eval(f"... created {node_path_map[prim_path]}") return (node_path_map, nodes_constructed) # ---------------------------------------------------------------------- def _edit_connect(self, node_path_map: Dict[str, og.Node], connections_to_make: ConnectData_t): """Make a set of attribute connections, using the format required by edit_graph""" connection_list = connections_to_make if isinstance(connections_to_make, list) else [connections_to_make] try: for (src_node_name, src_attr_name, dst_node_name, dst_attr_name) in connection_list: dbg_eval(f"Connecting {src_node_name}.{src_attr_name} -> {dst_node_name}.{dst_attr_name}") try: src_node = node_path_map[src_node_name] except KeyError: src_node = src_node_name try: dst_node = node_path_map[dst_node_name] except KeyError: dst_node = dst_node_name dbg_eval(f"...nodes resolved to {src_node} and {dst_node}") self.connect(src_node, src_attr_name, dst_node, dst_attr_name) dbg_eval("...connection succeeded") except ValueError as error: raise OmniGraphError( f"Connect requires src_node, src_attr, dst_node, dst_attr - got {connection_list}" ) from error # ---------------------------------------------------------------------- def _edit_disconnect(self, node_path_map: Dict[str, og.Node], connections_to_break: DisconnectData_t): """Make a set of attribute disconnections, using the format required by edit_graph""" connection_list = connections_to_break if isinstance(connections_to_break, list) else [connections_to_break] try: for (src_node_name, src_attr_name, dst_node_name, dst_attr_name) in connection_list: dbg_eval(f"Disconnecting {src_node_name}.{src_attr_name} -> {dst_node_name}.{dst_attr_name}") try: src_node = node_path_map[src_node_name] except KeyError: src_node = src_node_name try: dst_node = node_path_map[dst_node_name] except KeyError: dst_node = dst_node_name dbg_eval(f"...nodes resolved to {src_node} and {dst_node}") self.disconnect(src_node, src_attr_name, dst_node, dst_attr_name) dbg_eval("...disconnection succeeded") except ValueError as error: raise OmniGraphError( f"Connect requires src_node, src_attr, dst_node, dst_attr - got {connection_list}" ) from error # ---------------------------------------------------------------------- def _edit_set_values(self, node_path_map: Dict[str, og.Node], values_to_set: SetValueData_t): """Set a bunch of attribute values, using the format required by edit_graph""" value_descriptions = values_to_set if isinstance(values_to_set, list) else [values_to_set] # value_list data can either include a node or not. If the node is not included then # the list members must be og.Attributes, not just names. try: for value_list in value_descriptions: if not isinstance(value_list, tuple) and not isinstance(value_list, list): raise ValueError if len(value_list) == 3: node_name, attr_name, value = value_list _ = DBG_EVAL and dbg_eval(f"Setting value '{value} on {node_name}.{attr_name}") try: node = node_path_map[node_name] except KeyError: node = node_name self.set_values(node, [(attr_name, value)]) else: attr_name, value = value_list if not isinstance(attr_name, og.Attribute): raise OmniGraphError(f"Must set values with og.Attribute, got '{attr_name}'") _ = DBG_EVAL and dbg_eval(f"Setting value '{value} on {attr_name}") self.set_attribute_values([(attr_name, value)]) _ = DBG_EVAL and dbg_eval("...setting value succeeded") except ValueError as ex: raise OmniGraphError(f"Setting value requires ({{node_name, }}attr_name, value) - got {value_list}") from ex # ---------------------------------------------------------------------- def edit(self, graph_description: Dict[str, Any]) -> List[og.Node]: """Modify an OmniGraph relative to the top level of the scene ("/") Convenience function for accessing edit_graph without a root prim when it's not relevant """ return self.edit_graph("/", graph_description) # ---------------------------------------------------------------------- def edit_graph(self, root_prim: str, graph_description: Dict[str, Any]) -> List[og.Node]: """Create an OmniGraph node graph from a dictionary description of the contents. Here's a simple call that first deletes an existing node "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 helper = OmniGraphHelper() (src_node, dst_node) = helper.edit_graph("/", { "deletions" [ "oldnode" ], "nodes": [ ("omni.graph.tutorials.SimpleData", "src"), ("omni.graph.tutorials.SimpleData", "dst") ], "prims": [ ("Prim1", {"attrFloat": ("float", 2.0)), ("Prim2", {"attrBool": ("bool", true)), ], "connections": [ ("src", "outputs:a_int", "dst", "inputs:a_int") ], "disconnections": [ ("src", "outputs:a_float", "dst", "inputs:a_float") ], "values": [ ("src", "inputs:a_int", 5) ] } ) Args: root_prim: Top level prim for the graph nodes (e.g. "/") graph_description: Dictionary of graph construction definitions. 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. - "deletions": [NODE_NAME] Deletes a node at the given path - "nodes": [(NODE_TYPE, NODE_NAME)] Constructs a node of type "NODE_TYPE" and name "NODE_NAME". - "prims": [(PRIM_PATH, {ATTR_NAME: (ATTR_TYPE, ATTR_VALUE)})] Constructs a prim with path "PRIM_PATH containing a set of attributes with specified types and values. - "connections": [(SRC_NODE_NAME, SRC_ATTR_NAME, DST_NODE_NAME, DST_ATTR_NAME)] Makes a connection between the given source and destination attributes - "disconnections": [(SRC_NODE_NAME, SRC_ATTR_NAME, DST_NODE_NAME, DST_ATTR_NAME)] Breaks a connection between the given source and destination attributes - "values": [(NODE_NAME, ATTR_NAME, VALUE)] Sets the value of the given list of attributes. Note that when constructing nodes the "NODE_NAME" may be in use, so a map is constructed when the nodes are created between the requested node name and the actual node created, which will contain the prim path reference. Operations happen in that order (all deletions, all nodes, all connections, all values) to minimize the possibility of errors. As a shortform any of the keys can accept a single tuple as well as a list of tuples. Returns: The list of og.Nodes created for all constructed nodes Raises: 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 """ # 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 = self.graph.is_disabled() self.graph.set_disabled(True) try: # Syntax check first for instruction, data in graph_description.items(): if instruction not in ["nodes", "connections", "disconnections", "values", "deletions", "prims"]: raise OmniGraphError(f"Unknown graph construction operation - {instruction}: {data}") # Delete first because we may be creating nodes with the same names with suppress(KeyError): self._edit_delete_nodes(root_prim, graph_description["deletions"]) # Create nodes next since connect and set may need them node_path_map = {} nodes_constructed = [] with suppress(KeyError): (node_path_map, nodes_constructed) = self._edit_create_nodes(root_prim, graph_description["nodes"]) # Prims next as they may be used in connections with suppress(KeyError): self._edit_create_prims(root_prim, node_path_map, nodes_constructed, graph_description["prims"]) # Connections next as setting values may override their data with suppress(KeyError): self._edit_connect(node_path_map, graph_description["connections"]) # Disconnections may have been created by the connections list so they're next, though that's unlikely with suppress(KeyError): self._edit_disconnect(node_path_map, graph_description["disconnections"]) # Now set the values with suppress(KeyError): self._edit_set_values(node_path_map, graph_description["values"]) finally: # Really important that this always gets reset self.graph.set_disabled(graph_was_disabled) return nodes_constructed
52,187
Python
47.956848
120
0.569414
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/v1_5_0/context_helper.py
r"""Deprecated accessor of attribute values within a graph context. Use og.DataView or og.Controller instead. _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ """ from contextlib import suppress from typing import Any, Optional, Union import omni.graph.core as og import omni.graph.tools as ogt from ..attribute_values import AttributeDataValueHelper, AttributeValueHelper, WrappedArrayType from ..lookup_tables import ( IDX_ARRAY_GET, IDX_ARRAY_GET_TENSOR, IDX_ARRAY_SET, IDX_GET, IDX_GET_TENSOR, IDX_SET, UNSUPPORTED_METHODS, type_access_methods, ) from ..utils import DBG_EVAL, dbg_eval, list_dimensions # ============================================================================================================== # Try to import torch for tensor APIs. If not available the non-tensor APIs will still work. try: import torch_wrap except ImportError: torch_wrap = None # ================================================================================ @ogt.DeprecatedClass("og.ContextHelper is deprecated after version 1.5.0. Use og.Controller instead.") class ContextHelper: """Helper class for managing compute graph contexts Attributes: _py_context: Context on which to apply the operations """ def __init__(self, py_context=None): """Remember the context for future operations. Args: py_context: Context for the operations - if None then get the current one """ if py_context is None: for context in og.get_compute_graph_contexts(): self._py_context = context else: self._py_context = py_context # ---------------------------------------------------------------------- @property def context(self): """Returns the context being used for evaluation""" return self._py_context # ---------------------------------------------------------------------- def get_attribute_configuration(self, attr: Union[og.Attribute, og.AttributeData]): """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][]") List: List of lookup methods for this type 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") ) lookup_methods = UNSUPPORTED_METHODS # 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") try: lookup_methods = type_access_methods(ogn_type)[0] except (KeyError, TypeError) as error: raise TypeError(f"Root type {ogn_type.get_ogn_type_name()} is not yet supported in Python") from error return (type_name, root_type_name, is_array_type, is_matrix_type, lookup_methods) # ---------------------------------------------------------------------- def get( self, attr_object: Union[og.Attribute, og.AttributeData], on_gpu: bool = False, update_immediately: bool = False ): """ Get the value of an attribute or attribute data. Can be used for either type. This method is intended for simple value retrievals. For array values use get_array(). Args: attr_object: attribute data whose value is to be retrieved on_gpu: Is the value stored on the GPU? update_immediately: Should the stage update before getting the value or wait for the next regular update? Returns: Value of the attribute or attribute data Raises: TypeError: If an unsupported object type was passed in """ if isinstance(attr_object, og.AttributeData): helper = AttributeDataValueHelper(attr_object) return helper.get(on_gpu) if isinstance(attr_object, og.Attribute): helper = AttributeValueHelper(attr_object) return helper.get(on_gpu) raise TypeError(f"Object type {type(attr_object)} cannot be set with this method") # ---------------------------------------------------------------------- def get_array( self, attr_object: Union[og.Attribute, og.AttributeData], on_gpu: bool = False, update_immediately: bool = False, get_for_write: bool = False, reserved_element_count: int = 0, return_type: Optional[WrappedArrayType] = None, ) -> Any: """ Get the value of an attribute or attribute data. Can be used for either type. Args: attr_object: attribute whose value is to be retrieved on_gpu: Is the value stored on the GPU? update_immediately: Should the stage update before getting the value or wait for the next regular update? get_for_write: If True then get the data in writable form (which may do other things under the covers) reserved_element_count: For writable array types set the element count to this before retrieving the data. This guarantees a buffer of this many elements is available in the returned data. Returns: Array value of the attribute or attribute data Raises: TypeError: If an unsupported object type was passed in """ # Ask the attribute update its value. If we are using a push graph, this # won't do anything, but in a dirty and pull graph, this generates the "pull" that causes the graph # to evaluate the dirtied attribute. with suppress(AttributeError): attr_object.update_object_value(update_immediately) helper = AttributeValueHelper(attr_object) if get_for_write is not None: if reserved_element_count is None: raise ValueError("Tried to get an array for write without setting the element count") return helper.get_array(get_for_write, reserved_element_count, on_gpu, return_type) return helper.get(on_gpu) # ---------------------------------------------------------------------- def get_attr_value( self, attr: og.Attribute, isGPU: bool = False, # noqa: N803 isTensor: bool = False, # noqa: N803 getDefault: bool = False, # noqa: N803 updateImmediately=False, # noqa: N803 getForWrite=False, # noqa: N803 writeElemCount=0, # noqa: N803 ): """ Get the value of a node attribute in the context managed by this class. Args: attr: attribute whose value is to be retrieved isGPU: Is the attribute stored on the GPU? isTensor: Is the attribute value a tensor type? For some types of data this doesn't mean anything but is silently accepted anyway. isDefault: Whether or not we want to retrieve the default value updateImmediately: Should the stage update immediately or wait for the next regular update? getForWrite: Is the value going to be written to after calling? writeElemCount: If the value to get is a writable array then set it at this size Returns: Value of the attribute Raises: AttributeError: If you try to access array data with "isTensor=True" and torch was not imported TypeError: Raised if the data type of the attribute is not yet supported """ (type_name, root_type_name, is_array_type, _, lookup_methods) = self.get_attribute_configuration(attr) # Verify that getting arrays for write has a valid element count. 0 is okay, None indicates uninitialized if is_array_type and getForWrite and (writeElemCount is None): raise ValueError(f"Attribute {attr.get_name()} requires a size to be set before getting values") # Ask the attribute update its value. If we are using a push graph, this # won't do anything, but in a dirty and pull graph, this generates the "pull" that causes the graph # to evaluate the dirtied attribute. with suppress(AttributeError): attr.update_attribute_value(updateImmediately) can_be_tensor = (isTensor or isGPU) and is_array_type and torch_wrap is not None _ = DBG_EVAL and dbg_eval( f"Getting value of type {type_name} on {attr.get_name()}. GPU = {isGPU}, Tensor = {isTensor}" ) try: _ = DBG_EVAL and dbg_eval(" --> Has Get/Set methods") if is_array_type: if lookup_methods[IDX_ARRAY_GET] is not None: if can_be_tensor and (lookup_methods[IDX_ARRAY_GET_TENSOR] is not None): _ = DBG_EVAL and dbg_eval( f" --> Returning array tensor data with {lookup_methods[IDX_ARRAY_GET_TENSOR]}" ) tensor = lookup_methods[IDX_ARRAY_GET_TENSOR]( self._py_context, attr, isGPU, getForWrite, writeElemCount ) return torch_wrap.wrap_tensor(tensor) if tensor is not None else None _ = DBG_EVAL and dbg_eval(f" --> Returning array data with {lookup_methods[IDX_ARRAY_GET]}") return lookup_methods[IDX_ARRAY_GET]( self._py_context, attr, getDefault, getForWrite, writeElemCount ) raise TypeError(f"Getting array data of type {root_type_name} is not yet supported") if can_be_tensor and lookup_methods[IDX_GET_TENSOR] is not None: _ = DBG_EVAL and dbg_eval(f" --> Returning tensor data with {lookup_methods[IDX_GET_TENSOR]}") tensor = lookup_methods[IDX_GET_TENSOR](self._py_context, attr, isGPU, getForWrite, writeElemCount) return torch_wrap.wrap_tensor(tensor) if tensor is not None else None _ = DBG_EVAL and dbg_eval(f" --> Returning normal data with {lookup_methods[IDX_GET]}") return lookup_methods[IDX_GET](self._py_context, attr, getDefault, getForWrite, writeElemCount) except TypeError as error: raise TypeError(f"Trying to get unsupported attribute type {type_name}") from error except KeyError as error: raise TypeError(f"Trying to get unknown attribute type {type_name}") from error # ---------------------------------------------------------------------- def set_attr_value(self, new_value, attr: og.Attribute): """ Set the value of a attribute in the context managed by this class new_value: New value to be set on the attribute attr: Attribute whose value is to be set Raises: TypeError: Raised if the data type of the attribute is not yet supported or if the parameters were passed in the wrong order. """ if isinstance(new_value, og.Attribute): raise TypeError("set_attr_value is called with value first, attribute second") (type_name, root_type_name, is_array_type, is_matrix_type, lookup_methods) = self.get_attribute_configuration( attr ) # Flatten the matrix data out, if it wasn't already flattened # 2x2 matrix can come in as [[a, b], [c, d]] or [a, b, c, d] but will always go to the ABI as the latter if is_matrix_type: value_dimensions = list_dimensions(new_value) if is_array_type: if value_dimensions == 3: value_to_set = [[item for sublist in matrix for item in sublist] for matrix in new_value] else: value_to_set = new_value else: if value_dimensions == 2: value_to_set = [item for sublist in new_value for item in sublist] else: value_to_set = new_value else: value_to_set = new_value try: _ = DBG_EVAL and dbg_eval(f"Set attribute {attr.get_name()} of type {type_name} to {new_value}") _ = DBG_EVAL and dbg_eval(f" as {root_type_name}, array={is_array_type}, matrix={is_matrix_type}") if is_array_type: if lookup_methods[IDX_ARRAY_GET] and lookup_methods[IDX_ARRAY_SET]: _ = DBG_EVAL and dbg_eval(f" --> Setting array node data using {lookup_methods[IDX_ARRAY_SET]}") # When setting an entire array all at once you need to first ensure the memory is allocated # by calling the get method. lookup_methods[IDX_ARRAY_GET](self._py_context, attr, False, True, len(value_to_set)) lookup_methods[IDX_ARRAY_SET](self._py_context, value_to_set, attr) else: raise TypeError(f"Setting array data of type {type_name} is not yet supported") else: _ = DBG_EVAL and dbg_eval(f" --> Setting simple data with {lookup_methods[IDX_SET]}") lookup_methods[IDX_SET](self._py_context, value_to_set, attr) except KeyError as error: raise TypeError(f"Trying to set unsupported attribute type {type_name}") from error # ---------------------------------------------------------------------- def get_elem_count(self, attr): """ Get the number of elements on the attribute in the context managed by this class attr: Attribute whose element values are to be counted Returns: Number of elements currently on the attribute """ return self._py_context.get_elem_count(attr)
16,501
Python
47.678466
120
0.576389
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/v1_5_0/utils.py
r"""Deprecated utilities _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ """ from typing import Any, List, Tuple, Union import carb import omni.graph.core as og from pxr import Sdf, Usd ALLOW_IMPLICIT_GRAPH_SETTING = "/persistent/omnigraph/allowGlobalImplicitGraph" """Constant for the setting to selectively disable the global implicit graph""" USE_SCHEMA_PRIMS_SETTING = "/persistent/omnigraph/useSchemaPrims" """Constant for the setting to force OmniGraph prims to follow the schema""" ENABLE_LEGACY_PRIM_CONNECTIONS = "/persistent/omnigraph/enableLegacyPrimConnections" """Constant for the setting to enable connections between legacy Prims and OG Nodes""" DISABLE_PRIM_NODES_SETTING = "/persistent/omnigraph/disablePrimNodes" """Constant for the setting to enable legacy Prim nodes to exist in the scene""" # Object type hints are now available in typing.py NODE_TYPE_HINTS = Union[str, og.Node, Usd.Prim, None] # type: ignore NODE_TYPE_OR_LIST = Union[NODE_TYPE_HINTS, List[NODE_TYPE_HINTS]] ATTRIBUTE_TYPE_HINTS = Union[str, og.Attribute, Usd.Attribute] # type: ignore ATTRIBUTE_TYPE_OR_LIST = Union[ATTRIBUTE_TYPE_HINTS, List[ATTRIBUTE_TYPE_HINTS]] ATTRIBUTE_TYPE_TYPE_HINTS = Union[str, og.Type] ATTRIBUTE_VALUE_PAIR = Tuple[ATTRIBUTE_TYPE_HINTS, Any] ATTRIBUTE_VALUE_PAIRS = Union[ATTRIBUTE_VALUE_PAIR, List[ATTRIBUTE_VALUE_PAIR]] EXTENDED_ATTRIBUTE_TYPE_HINTS = Union[og.AttributePortType, Tuple[og.AttributePortType, Union[str, List[str]]]] GRAPH_TYPE_HINTS = Union[str, Sdf.Path, og.Graph, None] # type: ignore GRAPH_TYPE_OR_LIST = Union[GRAPH_TYPE_HINTS, List[GRAPH_TYPE_HINTS]] # ================================================================================ def get_omnigraph(): """Returns the current OmniGraph. Deprecated as there is no longer the notion of a 'current' graph """ carb.log_warn("get_omnigraph() is deprecated and will be removed - use og.ObjectLookup.graph() instead") for context in og.get_compute_graph_contexts(): return context.get_graph() raise ValueError("OmniGraph is not currently available") # ==================================================================================================== def l10n(msg): """Wrapper for l10n for when it gets implemented. Deprecated - implementation is not on the plan and usage is spotty. """ return msg
2,789
Python
43.285714
111
0.570814
omniverse-code/kit/exts/omni.graph/omni/graph/core/_impl/v1_5_0/replaced_functions.py
r"""Deprecation support for functions that have been replaced by equivalents _____ ______ _____ _____ ______ _____ _______ ______ _____ | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ """ import re import omni.graph.core as og import omni.graph.tools as ogt from ..lookup_tables import OGN_NAMES_TO_TYPES, USD_NAMES_TO_TYPES # Pattern match for OGN style type names # MATCH: BaseType, [TupleCount]|None, []|None - e.g. int[3][] = "int",[3],[] RE_OGN_ATTRIBUTE_TYPE_PATTERN = re.compile(r"(^[^\[]+)(\[[0-9]+\]){0,1}(\[\]){0,1}") # Pattern matches for USD style type names. The rules for USD names are a little more complex so they require # multiple patterns to fully grok. (e.g. an int[4] is "int4" but a colord[4] is "color4d") # MATCH: BaseType64, TupleCount|None, []|None - e.g. int64 = "int64",None,None RE_USD_ATTRIBUTE_64_TYPE_PATTERN = re.compile(r"^([a-zA-Z]+64)([0-9]+){0,1}(\[\]){0,1}") # MATCH: BaseType, TupleCount|None, h|d|f|None, []|None - e.g. quat3d[] = "quat",3,d,[] RE_USD_ATTRIBUTE_TYPE_PATTERN = re.compile(r"^([a-zA-Z]+)([0-9]+){0,1}([hdf]){0,1}(\[\]){0,1}") # Mapping of the .ogn base data types to the corresponding og.BaseDataType values BASE_DATA_TYPE_MAP = { "bool": og.BaseDataType.BOOL, "bundle": og.BaseDataType.RELATIONSHIP, "double": og.BaseDataType.DOUBLE, "execution": og.BaseDataType.UINT, "float": og.BaseDataType.FLOAT, "half": og.BaseDataType.HALF, "int": og.BaseDataType.INT, "int64": og.BaseDataType.INT64, "objectId": og.BaseDataType.UINT64, "path": og.BaseDataType.UCHAR, "string": og.BaseDataType.UCHAR, "token": og.BaseDataType.TOKEN, "uchar": og.BaseDataType.UCHAR, "uint": og.BaseDataType.UINT, "uint64": og.BaseDataType.UINT64, } # Mapping of the .ogn role names to the corresponding og.AttributeRole values ROLE_MAP = { "color": og.AttributeRole.COLOR, "execution": og.AttributeRole.EXECUTION, "frame": og.AttributeRole.FRAME, "matrix": og.AttributeRole.MATRIX, "none": og.AttributeRole.NONE, "normal": og.AttributeRole.NORMAL, "objectId": og.AttributeRole.OBJECT_ID, "path": og.AttributeRole.PATH, "point": og.AttributeRole.POSITION, "quat": og.AttributeRole.QUATERNION, "string": og.AttributeRole.TEXT, "texcoord": og.AttributeRole.TEXCOORD, "timecode": og.AttributeRole.TIMECODE, "transform": og.AttributeRole.TRANSFORM, "vector": og.AttributeRole.VECTOR, } # ============================================================================================================== @ogt.deprecated_function("Use og.AttributeType.type_from_ogn_type_name instead") def attribute_type_from_ogn_type_name(ogn_type_name: str) -> og.Type: """Construct an attribute type object from an OGN style type name""" type_match = RE_OGN_ATTRIBUTE_TYPE_PATTERN.match(ogn_type_name) if not type_match: raise AttributeError(f"Attribute type '{ogn_type_name}' does not match known OGN type names") try: (base_type, role) = OGN_NAMES_TO_TYPES[type_match.group(1)] except KeyError as error: raise AttributeError(f"Base type '{type_match.group(1)}' is not a supported OGN type") from error tuple_count = 1 if type_match.group(2) is None else int(type_match.group(2)[1]) array_depth = 0 if type_match.group(3) is None and role in [og.AttributeRole.TEXT, og.AttributeRole.PATH] else 1 is_matrix_type = role in [og.AttributeRole.MATRIX, og.AttributeRole.TRANSFORM, og.AttributeRole.FRAME] if is_matrix_type: tuple_count *= tuple_count return og.Type(base_type, tuple_count, array_depth, role) # ============================================================================================================== @ogt.deprecated_function("Use og.AttributeType.type_from_sdf_type_name instead") def attribute_type_from_usd_type_name(usd_type_name: str) -> og.Type: """Construct an attribute type object from a USD style type name""" # The 64 type pattern (int64, uint64) has to be applied first so that the base type includes it type_match = RE_USD_ATTRIBUTE_64_TYPE_PATTERN.match(usd_type_name) if type_match: (full_type, tuple_count, array_pattern) = type_match.groups() flavour = None else: type_match = RE_USD_ATTRIBUTE_TYPE_PATTERN.match(usd_type_name) if not type_match: raise AttributeError(f"Attribute type '{usd_type_name}' does not match known USD type names") (full_type, tuple_count, flavour, array_pattern) = type_match.groups() # Reassemble the role names (quat3d extracts as "quat",3,"d",None - need "quatd" to grok the types) full_type = f"{full_type}{flavour}" if flavour is not None else full_type tuple_count = 1 if tuple_count is None else int(tuple_count) array_depth = 0 if array_pattern is None else 1 try: (base_type, role, override_tuple_count) = USD_NAMES_TO_TYPES[full_type] if override_tuple_count is not None: tuple_count = override_tuple_count except KeyError as error: raise AttributeError(f"Base type '{full_type}' is not a supported USD type") from error is_matrix_type = usd_type_name.startswith("matrix") if is_matrix_type: tuple_count *= tuple_count return og.Type(base_type, tuple_count, array_depth, role)
5,695
Python
46.865546
116
0.597366
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_bundle_changes.py
import omni.graph.core as og import omni.graph.core.tests as ogt class BundleTestSetup(ogt.OmniGraphTestCase): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.graph = og.Controller.create_graph("/graph") self.context = self.graph.get_default_graph_context() self.factory = og.IBundleFactory.create() self.assertTrue(self.factory is not None) self.bundle_changes = og.IBundleChanges.create(self.context) self.assertTrue(self.bundle_changes is not None) class TestBundleTopologyChanges(BundleTestSetup): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() async def test_bundle_changes_interface(self): bundle_changes = og.IBundleChanges.create(self.context) self.assertTrue(bundle_changes is not None) async def test_create_bundle(self): bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) async def test_create_attribute(self): bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) # modify attrib = bundle.create_attribute("attrib", og.Type(og.BaseDataType.INT)) # check for changes with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) async def test_create_attribute_like(self): bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.bundle_changes.activate_change_tracking(bundle1) self.bundle_changes.activate_change_tracking(bundle2) attrib1 = bundle1.create_attribute("attrib", og.Type(og.BaseDataType.INT)) # setup tracking self.bundle_changes.get_change(bundle1) self.bundle_changes.get_change(bundle2) self.bundle_changes.get_change(attrib1) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib1), og.BundleChangeType.NONE) # command: create attrib based on attrib1 attrib2 = bundle2.create_attribute_like(attrib1) # check for changes with og.BundleChanges(self.bundle_changes, bundle2) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(attrib1), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(bundle2), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(attrib2), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib2), og.BundleChangeType.NONE) async def test_create_child_bundle(self): bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) # modify bundle.create_child_bundle("child") # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) async def test_remove_attribute(self): bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) bundle.create_attribute("attrib", og.Type(og.BaseDataType.INT)) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) # modify bundle.remove_attribute("attrib") # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) async def test_remove_child_bundles(self): bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) child = bundle.create_child_bundle("child") # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) # modify bundle.remove_child_bundle(child) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) async def test_clear_contents(self): bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) # modify bundle.clear_contents() # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) async def test_copy_attribute(self): bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.bundle_changes.activate_change_tracking(bundle1) self.bundle_changes.activate_change_tracking(bundle2) attrib1 = bundle1.create_attribute("attrib1", og.Type(og.BaseDataType.INT)) # setup tracking self.bundle_changes.get_change(bundle1) self.bundle_changes.get_change(bundle2) self.bundle_changes.get_change(attrib1) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib1), og.BundleChangeType.NONE) # modify # only bundle2 is affected, but source bundle1 and attrib1 not bundle2.copy_attribute(attrib1) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle2) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(bundle2), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(attrib1), og.BundleChangeType.NONE) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib1), og.BundleChangeType.NONE) async def test_copy_child_bundle(self): """Test if CoW reference is resolved.""" bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.bundle_changes.activate_change_tracking(bundle1) self.bundle_changes.activate_change_tracking(bundle2) # setup tracking self.bundle_changes.get_change(bundle1) self.bundle_changes.get_change(bundle2) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) # modify # only bundle1 is dirty, but bundle2 stays intact bundle1.copy_child_bundle(bundle2) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle1) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle1), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) async def test_copy_bundle(self): """Copying bundle creates a shallow copy - a reference. To obtain the dirty id the reference needs to be resolved""" bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.bundle_changes.activate_change_tracking(bundle1) self.bundle_changes.activate_change_tracking(bundle2) # setup tracking self.bundle_changes.get_change(bundle1) self.bundle_changes.get_change(bundle2) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) # modify # bundle2 is modified, but bundle1 stays intact bundle2.copy_bundle(bundle1) self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle2) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle2), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle2), og.BundleChangeType.NONE) async def test_get_attribute_by_name(self): """Getting writable attribute data handle does not change dirty id. Only writing to an attribute triggers id to be changed.""" bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) attrib = bundle.create_attribute("attrib", og.Type(og.BaseDataType.INT)) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.get_change(attrib) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) # getting attribute doesn't mark any changes attrib = bundle.get_attribute_by_name("attrib") # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertFalse(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.NONE) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) async def test_get_child_bundle_by_name(self): """Getting writable bundle handle does not change dirty id. Only creating/removing attributes and children triggers id to be changed.""" bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) child = bundle.create_child_bundle("child") # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.get_change(child) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(child), og.BundleChangeType.NONE) # bundle and child must be clean child = bundle.get_child_bundle_by_name("child") # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertFalse(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(child), og.BundleChangeType.NONE) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(child), og.BundleChangeType.NONE) async def test_change_child_and_propagate_changes_to_parent(self): r""" bundle1 \_ child0 \_ child1 \_ child2 <-- create attribute Will propagate dirty id changes up to `bundle1` (child2 -> child1 -> child0 -> bundle1) """ bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) child0 = bundle.create_child_bundle("child0") child1 = child0.create_child_bundle("child1") child2 = child1.create_child_bundle("child2") # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.get_change(child0) self.bundle_changes.get_change(child1) self.bundle_changes.get_change(child2) self.bundle_changes.clear_changes() # check if everything is clean self.assertEqual(self.bundle_changes.get_change(child2), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(child1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(child0), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) # creating attribute automatically make all hierarchy dirty child2.create_attribute("attrib", og.Type(og.BaseDataType.INT)) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(child2), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(child1), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(child0), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(child2), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(child1), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(child0), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) class TestBundleAttributeDataChanges(BundleTestSetup): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() async def test_set_get_simple_attribute_data(self): """Getting simple attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) attrib = bundle.create_attribute("attrib", og.Type(og.BaseDataType.INT)) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.get_change(attrib) self.bundle_changes.clear_changes() self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) # command: set modifies attribute and bundle attrib.set(42) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) # query: get does not modify attribute and bundle self.assertEqual(attrib.as_read_only().get(), 42) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertFalse(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.NONE) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) async def test_set_get_array_attribute_data(self): """Getting simple attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) attrib = bundle.create_attribute("attrib", og.Type(og.BaseDataType.INT, 1, 1)) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.get_change(attrib) self.bundle_changes.clear_changes() self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) # command: set modifies attribute and bundle attrib.set([42]) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) # query: get does not modify attribute and bundle self.assertEqual(attrib.as_read_only().get()[0], 42) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertFalse(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.NONE) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) async def test_set_get_tuple_attribute_data(self): """Getting simple attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.bundle_changes.activate_change_tracking(bundle) attrib = bundle.create_attribute("attrib", og.Type(og.BaseDataType.INT, 2, 0)) # setup tracking self.bundle_changes.get_change(bundle) self.bundle_changes.get_change(attrib) self.bundle_changes.clear_changes() self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) # command: set modifies attribute and bundle attrib.set([42, 24]) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertTrue(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.MODIFIED) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.MODIFIED) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE) # query: get does not modify attribute and bundle self.assertEqual(attrib.as_read_only().get()[0], 42) self.assertEqual(attrib.as_read_only().get()[1], 24) # check for changes and clear them with og.BundleChanges(self.bundle_changes, bundle) as changes: self.assertFalse(changes.has_changed()) self.assertEqual(changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(changes.get_change(attrib), og.BundleChangeType.NONE) # cleaned after leaving the scope self.assertEqual(self.bundle_changes.get_change(bundle), og.BundleChangeType.NONE) self.assertEqual(self.bundle_changes.get_change(attrib), og.BundleChangeType.NONE)
24,227
Python
45.325048
91
0.692987
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_bundle_cow.py
import omni.graph.core as og import omni.graph.core.tests as ogt class TestBundleCow(ogt.OmniGraphTestCase): async def setUp(self): await super().setUp() self.graph = og.Controller.create_graph("/graph") self.context = self.graph.get_default_graph_context() self.factory = og.IBundleFactory.create() self.assertTrue(self.factory is not None) self.bundle1Name = "bundle1" self.bundle2Name = "bundle2" self.attr1Name = "attr1" self.attr1Type = og.Type(og.BaseDataType.BOOL, 1, 1) self.bundle1 = self.factory.create_bundle(self.context, self.bundle1Name) self.assertTrue(self.bundle1.valid) self.bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) self.assertTrue(self.bundle2.valid) async def test_copy_and_remove_attribute_with_metadata(self): meta_name = "meta1" meta_type = og.Type(og.BaseDataType.INT, 1, 1) attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) attr1.set([False, True]) meta1 = self.bundle1.create_attribute_metadata(self.attr1Name, meta_name, meta_type) meta1.set([1, 2, 3, 4]) # copy attribute with metadata self.bundle2.copy_attribute(attr1) # confirm data is accurate after setting it cpy_meta1 = self.bundle2.get_attribute_metadata_by_name(self.attr1Name, meta_name) cpy_meta1.set([4, 3, 2, 1]) self.assertTrue((meta1.get() == [1, 2, 3, 4]).all()) self.assertTrue((cpy_meta1.get() == [4, 3, 2, 1]).all()) # remove copied attribute should leave original attribute intact self.bundle2.remove_attributes_by_name([self.attr1Name]) # confirm source data is intact attr1 = self.bundle1.get_attribute_by_name(self.attr1Name) self.assertTrue(attr1.is_valid()) self.assertTrue((attr1.get() == [False, True]).all()) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 1) meta1 = self.bundle1.get_attribute_metadata_by_name(self.attr1Name, meta_name) self.assertTrue(meta1.is_valid()) self.assertTrue((meta1.get() == [1, 2, 3, 4]).all()) # confirm removed metadata is gone self.assertEqual(self.bundle2.get_attribute_metadata_count(self.attr1Name), 0) attr1 = self.bundle2.get_attribute_metadata_by_name(self.attr1Name, meta_name) self.assertFalse(attr1.is_valid()) async def test_copy_bundle_and_remove_attribute_with_metadata(self): meta_name = "meta1" meta_type = og.Type(og.BaseDataType.INT, 1, 1) attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) attr1.set([False, True]) meta1 = self.bundle1.create_attribute_metadata(self.attr1Name, meta_name, meta_type) meta1.set([1, 2, 3, 4]) # copy attribute with metadata self.bundle2.copy_bundle(self.bundle1) # # Do NOT materialize attribute - keep shallow copy of entire bundle # # remove copied attribute should leave original attribute intact self.bundle2.remove_attributes_by_name([self.attr1Name]) # confirm source data is intact attr1 = self.bundle1.get_attribute_by_name(self.attr1Name) self.assertTrue(attr1.is_valid()) self.assertTrue((attr1.get() == [False, True]).all()) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 1) meta1 = self.bundle1.get_attribute_metadata_by_name(self.attr1Name, meta_name) self.assertTrue(meta1.is_valid()) self.assertTrue((meta1.get() == [1, 2, 3, 4]).all()) # confirm copied metadata is gone self.assertEqual(self.bundle2.get_attribute_metadata_count(self.attr1Name), 0) attr1 = self.bundle2.get_attribute_metadata_by_name(self.attr1Name, meta_name) self.assertFalse(attr1.is_valid()) async def test_remove_attribute_metadata(self): attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) attr1.set([False, True]) meta_name1 = "meta1" meta_type1 = og.Type(og.BaseDataType.INT, 1, 1) meta1 = self.bundle1.create_attribute_metadata(self.attr1Name, meta_name1, meta_type1) meta1.set([1, 2, 3, 4]) meta_name2 = "meta2" meta_type2 = og.Type(og.BaseDataType.BOOL, 1, 1) meta1 = self.bundle1.create_attribute_metadata(self.attr1Name, meta_name2, meta_type2) meta1.set([False, True]) # copy attribute with metadata self.bundle2.copy_bundle(self.bundle1) # # Materialize metadata for bundle2! # self.bundle2.remove_attribute_metadata(self.attr1Name, (meta_name1)) # check if source is intact self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 2) names = self.bundle1.get_attribute_metadata_names(self.attr1Name) self.assertEqual(len(names), 2) self.assertTrue(meta_name1 in names) self.assertTrue(meta_name2 in names) # check if shallow copied metadata bundle has been materialized self.assertEqual(self.bundle2.get_attribute_metadata_count(self.attr1Name), 1) names = self.bundle2.get_attribute_metadata_names(self.attr1Name) self.assertEqual(len(names), 1) self.assertFalse(meta_name1 in names) self.assertTrue(meta_name2 in names) async def test_copy_child_bundle(self): org_child = self.bundle1.create_child_bundle("org_child") # create bundle for modifications mod_bundle = self.factory.create_bundle(self.context, "mod_bundle") mod_child = mod_bundle.copy_child_bundle(org_child) mod_child.create_attribute("attr", og.Type(og.BaseDataType.BOOL, 1, 1)) # original child can not change, but modified change must self.assertEqual(org_child.get_attribute_count(), 0) self.assertEqual(mod_child.get_attribute_count(), 1) async def test_attribute_resize(self): src_bundle = self.factory.create_bundle(self.context, "src_bundle") src_attrib = src_bundle.create_attribute( "attrib", og.Type( og.BaseDataType.FLOAT, tuple_count=1, array_depth=1, ), element_count=100, ) dst_bundle = self.factory.create_bundle(self.context, "dst_bundle") dst_bundle.copy_bundle(src_bundle) self.assertEqual(dst_bundle.get_attribute_count(), 1) dst_attrib = dst_bundle.create_attribute( "attrib", og.Type( og.BaseDataType.FLOAT, tuple_count=1, array_depth=1, ), element_count=200, ) self.assertEqual(src_attrib.size(), 100) self.assertEqual(dst_attrib.size(), 200)
6,926
Python
38.135593
94
0.641207
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_omnigraph_utils.py
""" Suite of tests to exercise small pieces of the OmniGraph utility scripts. These tests are like unit tests in that they all only focus on one piece of functionality, not the integration of many pieces, as these tests usually do. """ import json from contextlib import suppress from pathlib import Path import carb import carb.settings import omni.graph.core as og import omni.graph.core.tests as ogt import omni.kit.app import omni.kit.commands import omni.kit.test import omni.usd class TestOmniGraphUtilities(ogt.OmniGraphTestCase): """Wrapper for unit tests on basic OmniGraph support script functionality""" # ---------------------------------------------------------------------- async def test_ogn_type_conversion(self): """Test operation of the AttributeType.type_from_ogn_type_name() function""" # Test data is tuples of string input and expected Type output simple_data_no_tuples = [ ("any", og.Type(og.BaseDataType.TOKEN)), ("bool", og.Type(og.BaseDataType.BOOL)), ("int64", og.Type(og.BaseDataType.INT64)), ("token", og.Type(og.BaseDataType.TOKEN)), ("uchar", og.Type(og.BaseDataType.UCHAR)), ("uint", og.Type(og.BaseDataType.UINT)), ("uint64", og.Type(og.BaseDataType.UINT64)), ] simple_data = [ ("double", og.Type(og.BaseDataType.DOUBLE)), ("float", og.Type(og.BaseDataType.FLOAT)), ("half", og.Type(og.BaseDataType.HALF)), ("int", og.Type(og.BaseDataType.INT)), ] tuple_data = [(f"{type_name}[2]", og.Type(og_type.base_type, 2, 0)) for (type_name, og_type) in simple_data] array_data = [ (f"{type_name}[]", og.Type(og_type.base_type, 1, 1)) for (type_name, og_type) in simple_data + simple_data_no_tuples ] array_tuple_data = [ (f"{type_name}[3][]", og.Type(og_type.base_type, 3, 1)) for (type_name, og_type) in simple_data ] role_data = [ ("bundle", og.Type(og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.BUNDLE)), ("colord[3]", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.COLOR)), ("colorf[3]", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.COLOR)), ("colorh[3]", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.COLOR)), ("frame[4]", og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.FRAME)), ("matrixd[2]", og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.MATRIX)), ("matrixd[3]", og.Type(og.BaseDataType.DOUBLE, 9, 0, og.AttributeRole.MATRIX)), ("matrixd[4]", og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX)), ("normald[3]", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.NORMAL)), ("normalf[3]", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NORMAL)), ("normalh[3]", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.NORMAL)), ("path", og.Type(og.BaseDataType.UCHAR, 1, 1, og.AttributeRole.PATH)), ("pointd[3]", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.POSITION)), ("pointf[3]", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.POSITION)), ("pointh[3]", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.POSITION)), ("quatd[3]", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.QUATERNION)), ("quatf[3]", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.QUATERNION)), ("quath[3]", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.QUATERNION)), ("target", og.Type(og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.TARGET)), ("texcoordd[3]", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.TEXCOORD)), ("texcoordf[3]", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.TEXCOORD)), ("texcoordh[3]", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.TEXCOORD)), ("timecode[3]", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.TIMECODE)), ("transform[3]", og.Type(og.BaseDataType.DOUBLE, 9, 0, og.AttributeRole.TRANSFORM)), ("vectord[3]", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.VECTOR)), ("vectorf[3]", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.VECTOR)), ("vectorh[3]", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.VECTOR)), ] test_data = simple_data + simple_data_no_tuples + tuple_data + array_data + array_tuple_data + role_data for (attribute_type_spec, attribute_type_expected) in test_data: actual = og.AttributeType.type_from_ogn_type_name(attribute_type_spec) self.assertEqual(attribute_type_expected, actual, f"Failed to convert {attribute_type_spec}") # ---------------------------------------------------------------------- async def test_sdf_type_conversion(self): """Test operation of the AttributeType.type_from_sdf_type_name() function""" # Test data is tuples of string input and expected Type output simple_data_no_tuples = [ ("bool", og.Type(og.BaseDataType.BOOL)), ("int64", og.Type(og.BaseDataType.INT64)), ("token", og.Type(og.BaseDataType.TOKEN)), ("uchar", og.Type(og.BaseDataType.UCHAR)), ("uint", og.Type(og.BaseDataType.UINT)), ("uint64", og.Type(og.BaseDataType.UINT64)), ] simple_data = [ ("double", og.Type(og.BaseDataType.DOUBLE)), ("float", og.Type(og.BaseDataType.FLOAT)), ("half", og.Type(og.BaseDataType.HALF)), ("int", og.Type(og.BaseDataType.INT)), ] tuple_data = [(f"{type_name}2", og.Type(og_type.base_type, 2, 0)) for (type_name, og_type) in simple_data] array_data = [ (f"{type_name}[]", og.Type(og_type.base_type, 1, 1)) for (type_name, og_type) in simple_data + simple_data_no_tuples ] array_tuple_data = [ (f"{type_name}3[]", og.Type(og_type.base_type, 3, 1)) for (type_name, og_type) in simple_data ] role_data = [ ("color3d", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.COLOR)), ("color3f", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.COLOR)), ("color3h", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.COLOR)), ("frame4d", og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.FRAME)), ("matrix2d", og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.MATRIX)), ("matrix3d", og.Type(og.BaseDataType.DOUBLE, 9, 0, og.AttributeRole.MATRIX)), ("matrix4d", og.Type(og.BaseDataType.DOUBLE, 16, 0, og.AttributeRole.MATRIX)), ("normal3d", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.NORMAL)), ("normal3f", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.NORMAL)), ("normal3h", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.NORMAL)), ("point3d", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.POSITION)), ("point3f", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.POSITION)), ("point3h", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.POSITION)), ("quatd", og.Type(og.BaseDataType.DOUBLE, 4, 0, og.AttributeRole.QUATERNION)), ("quatf", og.Type(og.BaseDataType.FLOAT, 4, 0, og.AttributeRole.QUATERNION)), ("quath", og.Type(og.BaseDataType.HALF, 4, 0, og.AttributeRole.QUATERNION)), ("texCoord3d", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.TEXCOORD)), ("texCoord3f", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.TEXCOORD)), ("texCoord3h", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.TEXCOORD)), ("timecode", og.Type(og.BaseDataType.DOUBLE, 1, 0, og.AttributeRole.TIMECODE)), ("vector3d", og.Type(og.BaseDataType.DOUBLE, 3, 0, og.AttributeRole.VECTOR)), ("vector3f", og.Type(og.BaseDataType.FLOAT, 3, 0, og.AttributeRole.VECTOR)), ("vector3h", og.Type(og.BaseDataType.HALF, 3, 0, og.AttributeRole.VECTOR)), ] test_data = simple_data + simple_data_no_tuples + tuple_data + array_data + array_tuple_data + role_data for (attribute_type_spec, attribute_type_expected) in test_data: actual = og.AttributeType.type_from_sdf_type_name(attribute_type_spec) self.assertEqual( attribute_type_expected, actual, f"Failed to convert '{attribute_type_spec}' - '{attribute_type_expected.get_type_name()}'" f" != '{actual.get_type_name()}'", ) # ---------------------------------------------------------------------- async def test_extension_information(self): """Test operation of the utilities to examine extension and OmniGraph node type information""" extension_information = og.ExtensionInformation() manager = omni.kit.app.get_app_interface().get_extension_manager() examples_cpp_extension = "omni.graph.examples.cpp" nodes_extension = "omni.graph.nodes" # If the two known extensions are somehow not found then the test cannot run examples_cpp_extension_id = None nodes_extension_id = None with suppress(Exception): examples_cpp_extension_id = manager.get_extension_id_by_module(examples_cpp_extension) nodes_extension_id = manager.get_extension_id_by_module(nodes_extension) if not examples_cpp_extension_id: carb.log_warn("test_extension_information cannot run since omni.graph.examples.cpp was not found") return if not nodes_extension_id: carb.log_warn("test_extension_information cannot run since omni.graph.nodes was not found") return # Remember the enabled state so that we can gracefully recover after the test run examples_cpp_enabled = manager.is_extension_enabled(examples_cpp_extension) nodes_enabled = manager.is_extension_enabled(nodes_extension) try: # The test proceeds by creating five nodes, two OmniGraph nodes from each of the known extensions # and one Prim that is given attribute information to make it look like an OmniGraph node. Then the # extension mapping information is read in with all of the extension enabled/disabled combinations to # ensure the correct information is retrieved. # Set up the scene with both extensions enabled to begin with manager.set_extension_enabled_immediate(examples_cpp_extension_id, True) manager.set_extension_enabled_immediate(nodes_extension_id, True) examples_cpp_node_types = ["omni.graph.examples.cpp.Smooth", "omni.graph.examples.cpp.VersionedDeformer"] examples_cpp_nodes = ["/TestGraph/Smooth", "/TestGraph/VersionedDeformer"] nodes_node_types = ["omni.graph.nodes.ArrayLength", "omni.graph.nodes.Noop"] nodes_nodes = ["/TestGraph/ArrayLength", "/TestGraph/Noop"] og.Controller.edit( "/TestGraph", { og.Controller.Keys.CREATE_NODES: [ (examples_cpp_nodes[0][11:], examples_cpp_node_types[0]), (examples_cpp_nodes[1][11:], examples_cpp_node_types[1]), (nodes_nodes[0][11:], nodes_node_types[0]), (nodes_nodes[1][11:], nodes_node_types[1]), ] }, ) # test_data is a list of test configurations where the contents are: # Enable omni.graph.examples.cpp? # Enable omni.graph.nodes? test_data = [ [True, True], [True, False], [False, False], [False, True], ] for enable_examples_cpp, enable_nodes in test_data: manager.set_extension_enabled_immediate(examples_cpp_extension_id, enable_examples_cpp) manager.set_extension_enabled_immediate(nodes_extension_id, enable_nodes) # The first test reads the entire set of extension node types. As this is always in flux only a few # that are unlikely to move are checked. (enabled_extensions, disabled_extensions) = extension_information.get_node_types_by_extension() # Make sure the extensions are partitioned correctly by enabled state if enable_examples_cpp: self.assertTrue(examples_cpp_extension in enabled_extensions) self.assertTrue(examples_cpp_extension not in disabled_extensions) for node_type in examples_cpp_node_types: self.assertIn(node_type, enabled_extensions[examples_cpp_extension]) else: self.assertTrue(examples_cpp_extension not in enabled_extensions) self.assertTrue(examples_cpp_extension in disabled_extensions) for node_type in examples_cpp_node_types: self.assertIn(node_type, disabled_extensions[examples_cpp_extension]) if enable_nodes: self.assertTrue(nodes_extension in enabled_extensions) self.assertTrue(nodes_extension not in disabled_extensions) for node_type in nodes_node_types: self.assertIn(node_type, enabled_extensions[nodes_extension]) else: self.assertTrue(nodes_extension not in enabled_extensions) self.assertTrue(nodes_extension in disabled_extensions) for node_type in nodes_node_types: self.assertIn(node_type, disabled_extensions[nodes_extension]) # Check that the node configuration is also returning the correct data (enabled_nodes, disabled_nodes) = extension_information.get_nodes_by_extension() if enable_examples_cpp: self.assertTrue(examples_cpp_extension in enabled_nodes) self.assertTrue(examples_cpp_extension not in disabled_nodes) for node_path in examples_cpp_nodes: self.assertIn(node_path, enabled_nodes[examples_cpp_extension]) else: self.assertTrue(examples_cpp_extension not in enabled_nodes) self.assertTrue(examples_cpp_extension in disabled_nodes) for node_path in examples_cpp_nodes: self.assertIn(node_path, disabled_nodes[examples_cpp_extension]) if enable_nodes: self.assertTrue(nodes_extension in enabled_nodes) self.assertTrue(nodes_extension not in disabled_nodes) for node_path in nodes_nodes: self.assertIn(node_path, enabled_nodes[nodes_extension]) else: self.assertTrue(nodes_extension not in enabled_nodes) self.assertTrue(nodes_extension in disabled_nodes) for node_path in nodes_nodes: self.assertIn(node_path, disabled_nodes[nodes_extension]) finally: manager.set_extension_enabled_immediate(examples_cpp_extension, examples_cpp_enabled) manager.set_extension_enabled_immediate(nodes_extension, nodes_enabled) # ---------------------------------------------------------------------- async def test_graphregistry_event_stream(self): """ Tests the graph registry event stream notifies when extensions with node types are loaded and unloaded """ examples_python_extension = "omni.graph.examples.python" manager = omni.kit.app.get_app_interface().get_extension_manager() examples_python_extension_id = None with suppress(Exception): examples_python_extension_id = manager.get_extension_id_by_module(examples_python_extension) if not examples_python_extension_id: carb.log_warn(f"test_graphregistry_event_stream cannot run since {examples_python_extension} was not found") return examples_enabled = manager.is_extension_enabled(examples_python_extension) # tests the registration count = 0 event_type = None def on_changed(event): nonlocal count nonlocal event_type if event.type in (int(og.GraphRegistryEvent.NODE_TYPE_ADDED), int(og.GraphRegistryEvent.NODE_TYPE_REMOVED)): event_type = event.type count = count + 1 sub = og.GraphRegistry().get_event_stream().create_subscription_to_pop(on_changed) self.assertIsNotNone(sub) try: enabled = examples_enabled # each load/unload should trigger the callback for each node loaded/unloaded last_count = count for i in range(1, 4): enabled = not enabled manager.set_extension_enabled_immediate(examples_python_extension, enabled) await omni.kit.app.get_app().next_update_async() self.assertGreater(count, last_count) if enabled: self.assertEqual(event_type, int(og.GraphRegistryEvent.NODE_TYPE_ADDED)) else: self.assertEquals(event_type, int(og.GraphRegistryEvent.NODE_TYPE_REMOVED)) last_count = count # wait more frames to validate the callback didn't get called without an extension change for _j in range(1, i): await omni.kit.app.get_app().next_update_async() self.assertEqual(count, last_count) finally: manager.set_extension_enabled_immediate(examples_python_extension, examples_enabled) # ---------------------------------------------------------------------- async def test_typed_value(self): """Test operation of the TypedValue class""" # Test data consists of args + kwargs values to pass to the set() method, a boolean indicating whether setting # should succeed or not, and the expected value and type after setting. When there are two args or two kwargs # the __init__ method is used as well as those are the cases in which it is valid. unknown_t = og.Type(og.BaseDataType.UNKNOWN) float_t = og.Type(og.BaseDataType.FLOAT) test_data = [ # Legal args configurations [[], {}, True, None, unknown_t], [[1.0], {}, True, 1.0, unknown_t], [[1.0, "float"], {}, True, 1.0, float_t], [[1.0, float_t], {}, True, 1.0, float_t], # Legal kwargs configurations [[], {"value": 1.0}, True, 1.0, unknown_t], [[], {"value": 1.0, "type": "float"}, True, 1.0, float_t], [[], {"value": 1.0, "type": float_t}, True, 1.0, float_t], [[], {"type": float_t, "value": 1.0}, True, 1.0, float_t], # Illegal args combinations [[1.0, "float", 2], {}, False, None, None], [[1.0, "sink"], {}, False, None, None], [["float", 1.0], {}, False, None, None], # Illegal kwargs combinations [[], {"valley": 1.0}, False, None, None], [[], {"type": "float"}, False, None, None], [[], {"value": 1.0, "type": "flat"}, False, None, None], [[], {"value": 1.0, "type": "float", "scissors": "run_with"}, False, None, None], # Illegal args+kwargs combinations [[1.0], {"type": "float"}, False, None, None], [[1.0, "float"], {"value": 1.0}, False, None, None], ] for args, kwargs, should_succeed, expected_value, expected_type in test_data: test_info = ( f"args={args}, kwargs={kwargs}, success={should_succeed}, value={expected_value}, type={expected_type}" ) if should_succeed: if len(args) == 2: init_test = og.TypedValue(*args) self.assertEqual(init_test.value, expected_value, test_info) self.assertEqual(init_test.type, expected_type, test_info) elif len(kwargs) == 2: init_test = og.TypedValue(**kwargs) self.assertEqual(init_test.value, expected_value, test_info) self.assertEqual(init_test.type, expected_type, test_info) set_test = og.TypedValue() set_test.set(*args, **kwargs) self.assertEqual(set_test.value, expected_value, test_info) self.assertEqual(set_test.type, expected_type, test_info) else: with self.assertRaises(og.OmniGraphError): set_test = og.TypedValue() set_test.set(*args, **kwargs) if len(args) == 2 and not kwargs: with self.assertRaises(og.OmniGraphError): init_test = og.TypedValue(*args) elif len(kwargs) == 2 and not args: with self.assertRaises(og.OmniGraphError): init_test = og.TypedValue(**kwargs) # ---------------------------------------------------------------------- async def test_category_setup(self): """Test that the default category list is something sensible""" # Read the exact set of default categories, which should be the minimum available category list category_path = Path(carb.tokens.get_tokens_interface().resolve("${kit}")) / "dev" / "ogn" / "config" with open(category_path / "CategoryConfiguration.json", "r", encoding="utf-8") as cat_fd: default_categories = dict(json.load(cat_fd)["categoryDefinitions"].items()) actual_categories = og.get_node_categories_interface().get_all_categories() # compounds is a special case that gets added at runtime, not in ogn, and is not intended # for use by .ogn compiled nodes. self.assertTrue("Compounds" in actual_categories) for category_name, category_description in actual_categories.items(): if category_name == "Compounds": continue self.assertTrue(category_name in default_categories) self.assertEqual(category_description, default_categories[category_name]) # ---------------------------------------------------------------------- async def test_app_information(self): """Test the functions which return information about the running application.""" # Make sure that we get back a tuple containing two non-negative ints. kit_version = og.get_kit_version() self.assertTrue( isinstance(kit_version, tuple), f"get_kit_version() returned type {type(kit_version)}, not tuple" ) self.assertEqual( len(kit_version), 2, f"get_kit_version() returned tuple with {len(kit_version)} elements, expected 2" ) self.assertTrue( isinstance(kit_version[0], int) and isinstance(kit_version[1], int), f"get_kit_version() returned types ({type(kit_version[0])}, {type(kit_version[1])}, expected (int, int)", ) self.assertTrue( kit_version[0] >= 0 and kit_version[1] >= 0, f"get_kit_version() returned invalid value '{kit_version}'" ) # ---------------------------------------------------------------------- async def test_temp_settings(self): """Test the Settings.temporary context manager.""" setting_names = ("/omnigraph/test/boolval", "/omnigraph/test/intval", "/omnigraph/test/sub/strval") # Initialize the settings. settings = carb.settings.get_settings() initial_values = (True, None, "first") initial_settings = list(zip(setting_names, initial_values)) for name, value in initial_settings: settings.destroy_item(name) if value is not None: settings.set(name, value) # Test the single setting version of the context. with og.Settings.temporary(setting_names[2], "second"): self.assertEqual(settings.get(setting_names[2]), "second", "Single setting, in context.") self.assertEqual(settings.get(setting_names[2]), initial_values[2], "Single setting, after context.") # Test the list version. temp_settings = list(zip(setting_names, (False, 6, "third"))) with og.Settings.temporary(temp_settings): for name, value in temp_settings: self.assertEqual(settings.get(name), value, f"Multiple settings, in context: '{name}'") for name, value in initial_settings: self.assertEqual(settings.get(name), value, f"Multiple settings, after context: '{name}'") # Clean up. for name in setting_names: settings.destroy_item(name)
25,391
Python
54.806593
120
0.586074
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_register_ogn_nodes.py
""" Contains support for testing methods in ../scripts/register_ogn_nodes """ import os from pathlib import Path from tempfile import TemporaryDirectory import omni.graph.core.tests as ogts import omni.graph.tools.ogn as ogn from .._impl.register_ogn_nodes import find_import_locations class TestRegisterOgnNodes(ogts.OmniGraphTestCase): """Unit test class""" # -------------------------------------------------------------------------------------------------------------- def test_find_import_locations(self): """Test for the utility function find_import_locations Test data consists of list of (inputs, outputs, failure): inputs (2-tuple): Path to file calling the scripts Python import path for the extension outputs (2-tuple): Expected location of the import path's root directory Expected location of the calling file's directory failure (bool): Should the test raise an exception? """ no_exception = False exception = True drive = "C:" if os.name == "nt" else "/drive" test_data = [ [(f"{drive}/a/b/c/d.py", "b.c"), (f"{drive}/a", f"{drive}/a/b/c"), no_exception], [(f"{drive}/a/b/c/d.py", "b.c.d"), (), exception], ] for (index, test_run) in enumerate(test_data): if test_run[2]: with self.assertRaises(ValueError, msg=f"Expected failure in test {index} - {test_run}"): _ = find_import_locations(test_run[0][0], test_run[0][1]) else: results = find_import_locations(test_run[0][0], test_run[0][1]) self.assertEqual(results[0], test_run[1][0], f"Import root for {test_run}") self.assertEqual(results[1], test_run[1][1], f"Generated directory for {test_run}") # -------------------------------------------------------------------------------------------------------------- def test_generate_automatic_test_imports(self): """Test for the utility function generate_automatic_test_imports Test data consists of list of (test_files, output, should_modify): inputs (List[str]): List of test file names to create output (str): Expected contents of __init__.py should_modify (bool): Should the test have modified __init__.py """ full_test_file = ogn.import_file_contents() test_data = [ [], # Generate an empty init file if no tests are available ["TestOgnTest1.py"], # Add a new test case ["TestOgnTest1.py"], # No new testcases so no changes should be made ["TestOgnTest1.py", "TestOgnTest2.py"], # Add a new test case [], # No testcases leaves the file in place ] # Set up temporary test directory with TemporaryDirectory() as test_directory_fd: test_directory = Path(test_directory_fd) import_filepath = test_directory / "__init__.py" for test_run, test_files in enumerate(test_data): # Create empty test files for file in test_files: with open(test_directory / file, "a", encoding="utf-8"): pass ogn.generate_test_imports(test_directory, write_file=True) # Verify __init__.py contents with open(import_filepath, "r", encoding="utf-8") as import_fd: self.assertCountEqual( [line.rstrip() for line in import_fd.readlines()], full_test_file, f"Generated incorrect test import file for run {test_run}", ) # Delete generated test files to prepare for the next test for file in test_directory.glob("TestOgn*.py"): file.unlink()
3,964
Python
42.571428
116
0.53557
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/omnigraph_test_utils.py
# noqa: PLC0302 """A set of utilities useful for testing OmniGraph. Note that this file should not be imported directly, the API is in omni.graph.core.tests. Available in this module are: - omni.graph.core.tests.DataTypeHelper - a utility class to help iterate over all available data types - omni.graph.core.tests.find_build_directory_above - find the root directory of the build - omni.graph.core.tests.load_test_file - load a test file and wait for it to be ready - omni.graph.core.tests.insert_sublayer - load a test file as a sublayer - omni.graph.core.tests.dump_graph - conditionally call omni.graph.core.tests.print_current_graph - omni.graph.core.tests.print_current_graph - print out the contents of the existing OmniGraphs - omni.graph.core.tests.compare_lists - do an unordered comparison of two lists - omni.graph.core.tests.verify_connections - confirm that a set of expected connections exists - omni.graph.core.tests.verify_node_existence - confirm that a set of expected nodes exists - omni.graph.core.tests.verify_values - confirm that a set of expected attribute values are correct - omni.graph.core.tests.create_scope_node - create a Scope prim - omni.graph.core.tests.create_cube - create a Cube prim - omni.graph.core.tests.create_sphere - create a Sphere prim - omni.graph.core.tests.create_cone - create a Cube prim - omni.graph.core.tests.create_grid_mesh - Create a simple mesh consisting of a grid - omni.graph.core.tests.create_input_and_output_grid_meshes - Create two meshes consisting of grids """ import inspect import os import unittest from abc import ABC, abstractmethod from contextlib import suppress from dataclasses import dataclass from math import isclose, isnan from typing import Any, Dict, List, Optional, Tuple, Union import carb import numpy as np import omni.graph.core as og import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn import omni.kit import omni.usd from pxr import OmniGraphSchemaTools, Sdf, Usd, UsdGeom # If a node type version is unspecified then this is the value it gets. # Keep in sync with kDefaultNodeTypeVersion in include/omni/graph/core/NodeTypeRegistrar.h NODE_TYPE_VERSION_DEFAULT = 1 # ============================================================================================================== class TestContextManager(ABC): """Definition of the context classes that can be temporarily enabled during tests. These can be passed in to the test_case_class() factory method to extend the capabilities it has that are hardcoded in this file by instantiating one of these classes and passing it through the extra_contexts= parameter. The __init__ gets called to instantiate the base class information required by the test case. The setUp() method gets called when the test case's setUp method is called (once for every test). The tearDown() method gets called when the test case's tearDown method is called (once for every test) """ @abstractmethod def __init__(self): """Remember the setting name.""" @abstractmethod async def setUp(self): """Called when the test case setUp() is called""" @abstractmethod async def tearDown(self): """Called when the test case tearDown() is called""" # ============================================================================================================== class SettingContext(TestContextManager): """Helper class with an setUp and tearDown for modifying and restoring a carb setting""" def __init__(self, setting_name: str, temporary_value: any): """Remember the setting name.""" super().__init__() self.__setting_name = setting_name self.__temporary_value = temporary_value self.__original_value = None async def setUp(self): """Save the current value of the setting and set it to the desired temporary value""" settings = carb.settings.get_settings() self.__original_value = settings.get(self.__setting_name) ogt.dbg(f"SETUP Setting: Change {self.__setting_name} from {self.__original_value} to {self.__temporary_value}") settings.set(self.__setting_name, self.__temporary_value) async def tearDown(self): """Restore the original value of the setting""" ogt.dbg( f"TEARDOWN Setting: Restore {self.__setting_name} to {self.__original_value} from {self.__temporary_value}" ) carb.settings.get_settings().set(self.__setting_name, self.__original_value) # ============================================================================================================== class __ClearSceneContext(TestContextManager): """Helper class with an setUp and tearDown for potentially clearing the scene when a test is complete""" def __init__(self): # noqa: PLW0246 """Empty init is required since the parent is abstract""" super().__init__() async def setUp(self): """Nothing to do when setting up the test but the method is required""" ogt.dbg("SETUP ClearScene") async def tearDown(self): """If a clear was requested on tearDown do it now""" ogt.dbg("TEARDOWN ClearScene") await omni.usd.get_context().new_stage_async() # ============================================================================================================== def test_case_class(**kwargs) -> object: """ "Factory to return a base class to use for a test case configured with certain transient settings. The argument list is intentionally generic so that future changes can happen without impacting existing cases. The contexts will be invoked in the order specified below, with the extra_contexts being invoked in the order of the list passed in. Args: no_clear_on_finish (bool): If True then the scene will not be cleared after the test is complete extra_contexts (List[TestContextManager]): List of user-defined context managers to pass in deprecated (Tuple[str, DeprecationLevel]): Used to indicate this instantiation of the class has been deprecated base_class (object): Alternative base class for the test case, defaults to omni.kit.test.AsyncTestCase Return: Class object representing the base class for a test case with the given properties """ # Check to see if an alternative base class was passed in base_class = omni.kit.test.AsyncTestCase with suppress(KeyError): base_class = kwargs["base_class"] # Issue the deprecation message if specified, but continue on deprecation = None with suppress(KeyError): deprecation = kwargs["deprecated"] # Create a container for classes that will manage the temporary setting changes custom_actions = [] with suppress(KeyError): extra_contexts = kwargs["extra_contexts"] if not isinstance(extra_contexts, list): extra_contexts = [extra_contexts] for extra_context in extra_contexts: if not isinstance(extra_context, TestContextManager): raise ValueError(f"extra_contexts {extra_context} is not a TestContextManager") custom_actions.append(extra_context) if "no_clear_on_finish" not in kwargs or not kwargs["no_clear_on_finish"]: custom_actions.append(__ClearSceneContext()) # -------------------------------------------------------------------------------------------------------------- # Construct the customized test case base class object using the temporary setting and base class information class OmniGraphCustomTestCase(base_class): """A custom constructed test case base class that performs the prescribed setUp and tearDown actions. Members: __actions: List of actions to perform on setUp (calls action.setUp()) and tearDown (calls action.tearDown()) """ async def setUp(self): """Set up the test by saving and then setting up all of the action contexts""" super().setUp() if deprecation is not None: ogt.DeprecateMessage.deprecated(deprecation[0], deprecation[1]) # Start with no test failures registered og.set_test_failure(False) # Always start with a clean slate as the settings may conflict with something in the scene await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() # Perform the custom action entries self.__action_contexts = custom_actions for action in self.__action_contexts: await action.setUp() async def tearDown(self): """Complete the test by tearing down all of the action contexts""" # Perform the custom action tearDowns for action in reversed(self.__action_contexts): await action.tearDown() super().tearDown() # Return the constructed class definition return OmniGraphCustomTestCase OmniGraphTestCase = test_case_class() """Default test case base class used for most OmniGraph tests""" OmniGraphTestCaseNoClear = test_case_class(no_clear_on_finish=True) """Test case class that leaves the stage as it was when the test completed""" # ============================================================================================================== class DataTypeHelper: """ Class providing utility methods to assist with the comprehensive data type tests. Example of how to walk all of the valid input attribute values: for attribute_type in DataTypeHelper.all_attribute_types(): try: input_value = DataTypeHelper.test_input_value(attribute_type) process(input_value) except TypeError: pass # Cannot process this type yet """ _ATTR_TEST_DATA = None # -------------------------------------------------------------------------------------------------------------- @staticmethod def all_test_data() -> Dict[str, List[Any]]: """Returns a dict mapping all available Sdf attribute type names and a pair of sample values of those types""" if DataTypeHelper._ATTR_TEST_DATA is None: # Lazily initialize since this data is not needed until tests request it test_data = {} for type_name in ogn.supported_attribute_type_names(): attribute_type = og.AttributeType.type_from_ogn_type_name(type_name) sdf_type_name = og.AttributeType.sdf_type_name_from_type(attribute_type) if sdf_type_name is not None: test_data[sdf_type_name] = ogn.get_attribute_manager_type(type_name).sample_values() DataTypeHelper._ATTR_TEST_DATA = test_data return DataTypeHelper._ATTR_TEST_DATA # -------------------------------------------------------------------------------------------------------------- @staticmethod def all_attribute_types() -> List[str]: """Return the list of all supported attribute Sdf type names, including array versions""" return list(DataTypeHelper.all_test_data().keys()) # -------------------------------------------------------------------------------------------------------------- @staticmethod def test_input_value(attribute_type_name: str) -> Any: """ :return: Test value on the input side of a node for the given attribute type :raise TypeError: If the attribute type is not yet supported """ try: return DataTypeHelper.all_test_data()[attribute_type_name][0] # noqa: PLE1136 except KeyError as error: raise TypeError(f"Not yet supporting attribute type {attribute_type_name}") from error # -------------------------------------------------------------------------------------------------------------- @staticmethod def test_output_value(attribute_type_name: str) -> any: """ :return: Test value on the output side of a node for the given attribute type :raise TypeError: If the attribute type is not yet supported """ try: return DataTypeHelper.all_test_data()[attribute_type_name][1] # noqa: PLE1136 except KeyError as error: raise TypeError(f"Not yet supporting attribute type {attribute_type_name}") from error # -------------------------------------------------------------------------------------------------------------- @staticmethod def attribute_names(attribute_type_name: str, is_downstream_node: bool): """ :param attribute_type_name: One of the available attribute types, including arrays of them (e.g. int and int[]) :param is_downstream_node: True means it is one of the nodes accepting inputs, not computing anything itself :return: Pair of (INPUT_ATTRIBUTE_NAME, OUTPUT_ATTRIBUTE_NAME) used for the data test nodes """ suffixes = ["from_input", "from_output"] if is_downstream_node else ["original", "computed"] return [f"a_{attribute_type_name.replace('[]','_array')}_{suffixes[i]}" for i in range(2)] # -------------------------------------------------------------------------------------------------------------- def dump_graph(force_dump: bool = False): """Utility to conditionally print the current contents of the scene and graph""" if ogt.OGN_DEBUG or force_dump: print_current_graph() print(omni.usd.get_context().get_stage().GetRootLayer().ExportToString()) # -------------------------------------------------------------------------------------------------------------- def find_build_directory_above(start_at: Optional[str] = None) -> str: """Find the absolute path to the _build/ directory above the current one. If any of the folder up that path contains `dev/ogn` subfolder that is prioritized over `_build/` for shallow package support which don't have _build folder packaged at all. Using this method avoids the problems associated with following symlinks up a tree. :param start_at: Location at which to start looking; if None start at this script's location :raises ValueError: if there is no build directory above this file's directory :return: Path in which the _build/ directory was found """ starting_file = __file__ if start_at is None else start_at build_directory = os.path.abspath(starting_file) (parent_directory, leaf_directory) = os.path.split(build_directory) while leaf_directory != "_build": if os.path.exists(f"{parent_directory}/dev/ogn"): return f"{parent_directory}/dev" build_directory = parent_directory (parent_directory, leaf_directory) = os.path.split(build_directory) if parent_directory == build_directory: raise ValueError(f"No _build/ directory above {starting_file}") return build_directory # -------------------------------------------------------------------------------------------------------------- async def load_test_file(test_file_name: str, use_caller_subdirectory: bool = False) -> Tuple[bool, str]: """ Load the contents of the USD test file onto the stage, synchronously, when called as "await load_test_file(X)". In a testing environment we need to run one test at a time since there is no guarantee that tests can run concurrently, especially when loading files. This method encapsulates the logic necessary to load a test file using the omni.kit.asyncapi method and then wait for it to complete before returning. Args: test_file_name: Name of the test file to load - if an absolute path use it as-is use_caller_subdirectory: If True, look in the data/ subdirectory of the caller's directory for the file otherwise it will look in the data/ subdirectory below this directory Returns: (LOAD_SUCCEEDED[bool], LOAD_ERROR[str]) Raises: ValueError if the test file is not a valid USD file """ if not Usd.Stage.IsSupportedFile(test_file_name): raise ValueError("Only USD files can be loaded with this method") if os.path.isabs(test_file_name): path_to_file = test_file_name elif use_caller_subdirectory: path_to_file = os.path.join(os.path.dirname(inspect.stack()[1][1]), "data", test_file_name) else: path_to_file = os.path.join(os.path.dirname(__file__), "data", test_file_name) # Unicode error might happen if the file is a .usd rather than .usda and it was already pulled so that case is okay with suppress(UnicodeDecodeError): with open(path_to_file, "r", encoding="utf-8") as test_fd: first_line = test_fd.readline() if first_line.startswith("version"): raise ValueError(f"Do a 'git lfs pull' to update the contents of {path_to_file}") usd_context = omni.usd.get_context() usd_context.disable_save_to_recent_files() (result, error) = await usd_context.open_stage_async(path_to_file) usd_context.enable_save_to_recent_files() dump_graph() await omni.kit.app.get_app().next_update_async() return (result, str(error)) # -------------------------------------------------------------------------------------------------------------- async def insert_sublayer(test_file_name: str, use_caller_subdirectory: bool = False) -> bool: """ Inserts a sublayer from the given usd file into the current stage Args: test_file_name: Name of the test file to load - if an absolute path use it as-is use_caller_subdirectory: If True, look in the data/ subdirectory of the caller's directory for the file otherwise it will look in the data/ subdirectory below this directory Returns: True if the layer was loaded successfully, false otherwise """ if os.path.isabs(test_file_name): path_to_file = test_file_name elif use_caller_subdirectory: path_to_file = os.path.join(os.path.dirname(inspect.stack()[1][1]), "data", test_file_name) else: path_to_file = os.path.join(os.path.dirname(__file__), "data", test_file_name) root_layer = omni.usd.get_context().get_stage().GetRootLayer() sublayer_position = len(root_layer.subLayerPaths) new_layer = Sdf.Layer.FindOrOpen(path_to_file) if new_layer: relative_path = omni.client.make_relative_url(root_layer.identifier, new_layer.identifier).replace("\\", "/") root_layer.subLayerPaths.insert(sublayer_position, relative_path) else: return False await omni.kit.app.get_app().next_update_async() return True # -------------------------------------------------------------------------------------------------------------- def print_current_graph(show_attributes: bool = True, show_connections: bool = True, show_evaluation: bool = True): """ Finds the current compute graph and prints out the nodes and attributes in it. Args: show_attributes: If True then include the attributes on the nodes show_connections: If True then include the connections between the nodes show_evaluation: If True then include the evaluation info for the graph """ flags = [] if show_attributes: flags.append("attributes") if show_connections: flags.append("connections") if show_evaluation: flags.append("evaluation") print(og.OmniGraphInspector().as_json(og.get_all_graphs()[0], flags=flags), flush=True) # -------------------------------------------------------------------------------------------------------------- def compare_lists(expected_values: list, actual_values: list, comparing_what: str): """Compare the values in two lists, returning a relevant message if they are different, None if not""" extra_values = set(actual_values) - set(expected_values) missing_values = set(expected_values) - set(actual_values) if extra_values: return f"Unexpected {comparing_what} found - {extra_values}" if missing_values: return f"Expected {comparing_what} missing - {missing_values}" return None # -------------------------------------------------------------------------------------------------------------- def verify_connections(connections_expected: list): """ Confirm that the list of connections passed in exists in the compute graph, and are the only connections present. The argument is a list of pairs (SRC, DST) corresponding to the connection SRC -> DST """ graph = og.get_all_graphs()[0] if not graph.is_valid(): return "Compute graph has no valid contexts" ogt.dbg(f"Expecting {connections_expected}") # Collect connection information in both directions to verify they are the same upstream_connections_found = [] downstream_connections_found = [] comparison_errors = [] nodes = graph.get_nodes() # Ignore the default nodes since they may change and this test doesn't care nodes_of_interest = [ node for node in nodes if node.get_prim_path().find("/default") != 0 and node.get_prim_path().find("/Omniverse") < 0 and node.get_prim_path() != "/World" and node.get_prim_path() != "/" ] for node in nodes_of_interest: attributes_on_node = node.get_attributes() for attribute in attributes_on_node: this_attr = node.get_attribute(attribute.get_name()) this_attr_name = f"{node.get_prim_path()}.{attribute.get_name()}" upstream_connections = this_attr.get_upstream_connections() if len(upstream_connections) > 0: for connection in upstream_connections: upstream_attr_name = f"{connection.get_node().get_prim_path()}.{connection.get_name()}" upstream_connections_found.append((upstream_attr_name, this_attr_name)) downstream_connections = this_attr.get_downstream_connections() if len(downstream_connections) > 0: for connection in downstream_connections: downstream_attr_name = f"{connection.get_node().get_prim_path()}.{connection.get_name()}" downstream_connections_found.append((this_attr_name, downstream_attr_name)) ogt.dbg(f"Upstream = {upstream_connections_found}") ogt.dbg(f"Downstream = {downstream_connections_found}") comparison_error = compare_lists( upstream_connections_found, downstream_connections_found, "upstream/downstream pair" ) if comparison_error is not None: comparison_errors.append(comparison_error) comparison_error = compare_lists(connections_expected, downstream_connections_found, "connection") if comparison_error is not None: comparison_errors.append(comparison_error) return comparison_errors # -------------------------------------------------------------------------------------------------------------- def verify_node_existence(primitives_expected: list): """ Confirm that the list of nodes passed in exists in the compute graph. Args: primitives_expected: List of node names expected in the graph. Returns: A list of errors found, empty list if none """ graph = og.get_all_graphs()[0] if not graph.is_valid(): return ["Compute graph has no valid contexts"] comparison_errors = [] nodes = graph.get_nodes() # Get the current nodes in the world, ignoring the defaults since they may change and this test doesn't care primitives_found = [node.get_prim_path() for node in nodes if node.get_prim_path() in primitives_expected] comparison_error = compare_lists(primitives_expected, primitives_found, "compute graph primitives") if comparison_error is not None: comparison_errors.append(comparison_error) return comparison_errors # -------------------------------------------------------------------------------------------------------------- def verify_values(expected_value, actual_value, error_message: str): """Generic assert comparison which uses introspection to choose the correct method to compare the data values Args: expected_value: Value that was expected to be seen actual_value: Actual value that was seen error_message: Message describing the error if they do not match Raises: ValueError: With error message if the values do not match """ ogt.dbg(f"Comparing {actual_value} with expected {expected_value} - error = '{error_message}'") def to_np_array(from_value: Union[List, Tuple, np.ndarray]) -> np.ndarray: """Returns the list of values as a flattened numpy array""" # TODO: The only reason this is flattened at the moment is because Python matrix values are incorrectly # extracted as a flat array. They should maintain their data shape. return np.array(from_value).flatten() def is_close(first_value: float, second_value: float): """Raise a ValueError iff the single float values are not equal or floating-point close""" # Handle the NaN values first, which don't equal each other but should compare to equal for testing purposes if isnan(first_value) and isnan(second_value): return if isnan(first_value) or isnan(second_value): raise ValueError("NaN is only equal to other NaN values") # Default tolerance is 1e-9, which is a little tight for most simple uses if not isclose(first_value, second_value, rel_tol=1e-9): if not isclose(first_value, second_value, rel_tol=1e-5): raise ValueError ogt.dbg("The tolerance had to be loosened to make this pass") try: if isinstance(expected_value, (list, tuple, np.ndarray)): # Empty arrays are okay but only if both are empty. Using len() to handle both lists and numpy arrays if not len(expected_value) or not len(actual_value): # noqa: PLC1802 if not len(expected_value) and not len(actual_value): # noqa: PLC1802 return raise ValueError # Lists of strings must be compared elementwise, numeric arrays can use numpy if isinstance(expected_value[0], str): if set(actual_value) != set(expected_value): raise ValueError else: expected_array = to_np_array(expected_value) actual_array = to_np_array(actual_value) # If there are any NaN values then the array has to be checked element-by-element if any(np.isnan(expected_array)) and any(np.isnan(actual_array)): for expected, actual in zip(expected_array, actual_array): is_close(expected, actual) elif not np.allclose(expected_array, actual_array): raise ValueError elif isinstance(actual_value, (float, np.float32, np.float64, np.half)): is_close(actual_value, expected_value) else: if actual_value != expected_value: raise ValueError except ValueError as error: raise ValueError( f"{error_message}: Expected '{expected_value}' ({type(expected_value)}), " f"saw '{actual_value}' ({type(actual_value)})" ) from error # -------------------------------------------------------------------------------------------------------------- def create_scope_node(prim_name: str, attribute_data: Optional[Dict[str, Any]] = None) -> str: """Create a Scope prim at the given path, populated with the attribute data. This prim is a good source for a bundle attribute connection for testing. Args: prim_name: Name to give the prim within the current stage attribute_data: Dictionary of attribute names and the value the attribute should have in the prim The key is the name of the attribute in the prim. The value is the attribute information as a tuple of (TYPE, ATTRIBUTE_VALUE) TYPE: OGN name of the base data type ATTRIBUTE_VALUE: Data stored in the attribute within the prim Returns: Full path to the prim within the current stage (usually the path passed in) """ if attribute_data is None: attribute_data = {} stage = omni.usd.get_context().get_stage() prim_path = omni.usd.get_stage_next_free_path(stage, "/" + prim_name, True) prim = stage.DefinePrim(prim_path, "Scope") prim.CreateAttribute("node:type", Sdf.ValueTypeNames.Token).Set("Scope") return prim # -------------------------------------------------------------------------------------------------------------- def create_cube(stage, prim_name: str, displayColor: tuple) -> Usd.Prim: # noqa: N803 path = omni.usd.get_stage_next_free_path(stage, "/" + prim_name, True) prim = stage.DefinePrim(path, "Cube") prim.CreateAttribute("primvars:displayColor", Sdf.ValueTypeNames.Color3fArray).Set([displayColor]) prim.CreateAttribute("size", Sdf.ValueTypeNames.Double).Set(1.0) return prim # -------------------------------------------------------------------------------------------------------------- def create_sphere(stage, prim_name: str, displayColor: tuple) -> Usd.Prim: # noqa: N803 path = omni.usd.get_stage_next_free_path(stage, "/" + prim_name, True) prim = stage.DefinePrim(path, "Sphere") prim.CreateAttribute("primvars:displayColor", Sdf.ValueTypeNames.Color3fArray).Set([displayColor]) prim.CreateAttribute("radius", Sdf.ValueTypeNames.Double).Set(1.0) return prim # -------------------------------------------------------------------------------------------------------------- def create_cone(stage, prim_name: str, displayColor: tuple) -> Usd.Prim: # noqa: N803 path = omni.usd.get_stage_next_free_path(stage, "/" + prim_name, True) prim = stage.DefinePrim(path, "Cone") prim.CreateAttribute("primvars:displayColor", Sdf.ValueTypeNames.Color3fArray).Set([displayColor]) prim.CreateAttribute("radius", Sdf.ValueTypeNames.Double).Set(1.0) prim.CreateAttribute("height", Sdf.ValueTypeNames.Double).Set(1.0) return prim # -------------------------------------------------------------------------------------------------------------- def create_grid_mesh(stage, path, counts=(32, 32), domain=(620, 620, 20), display_color=(1, 1, 1)): mesh = UsdGeom.Mesh.Define(stage, path) mesh.CreateDoubleSidedAttr().Set(True) num_vertices = counts[0] * counts[1] num_triangles = (counts[0] - 1) * (counts[1] - 1) mesh.CreateFaceVertexCountsAttr().Set([3] * num_triangles * 2) face_vertex_indices = [0] * num_triangles * 6 for i in range(counts[0] - 1): for j in range(counts[1] - 1): a = i * counts[0] + j b = a + 1 c = a + counts[0] d = c + 1 k = (i * (counts[0] - 1) + j) * 6 face_vertex_indices[k : k + 6] = [a, b, d, a, d, c] mesh.CreateFaceVertexIndicesAttr().Set(face_vertex_indices) points = [(0, 0, 0)] * num_vertices for i in range(counts[0]): for j in range(counts[1]): points[i * counts[0] + j] = (i * domain[0] / (counts[0] - 1), j * domain[1] / (counts[1] - 1), domain[2]) mesh.CreatePointsAttr().Set(points) mesh.CreateDisplayColorPrimvar().Set([display_color]) return mesh # -------------------------------------------------------------------------------------------------------------- def create_input_and_output_grid_meshes(stage): input_grid = create_grid_mesh(stage, "/defaultPrim/inputGrid", display_color=(0.2784314, 0.64705884, 1)) output_grid = create_grid_mesh(stage, "/defaultPrim/outputGrid", display_color=(0.784314, 0.64705884, 0.1)) return (input_grid, output_grid) # ============================================================================================================== # Below here is support for generated tests # @dataclass class _TestGraphAndNode: """Helper class to pass graph and node around in test utility methods below""" graph: og.Graph = None node: og.Node = None # -------------------------------------------------------------------------------------------------------------- async def _test_clear_scene(tc: unittest.TestCase, test_run: Dict[str, Any]): """Clear the scene if test run requires it Args: tc: Unit test case executing this method. Used to raise errors test_run: Dictionary of consist of four sub-lists and a dictionary: - values for input attributes, set before the test starts - values for output attributes, checked after the test finishes - initial values for state attributes, set before the test starts - final values for state attributes, checked after the test finishes - setup to be used for populating the scene via controller For complete implementation see generate_user_test_data. """ setup = test_run.get("setup", None) if setup is None or setup: await omni.usd.get_context().new_stage_async() # -------------------------------------------------------------------------------------------------------------- async def _test_setup_scene( tc: unittest.TestCase, controller: og.Controller, test_graph_name: str, test_node_name: str, test_node_type: str, test_run: Dict[str, Any], last_test_info: _TestGraphAndNode, instance_count=0, ) -> _TestGraphAndNode: """Setup the scene based on given test run dictionary Args: tc: Unit test case executing this method. Used to raise errors controller: Controller object to use when constructing the scene (e.g. may have undo support disabled) test_graph_name: Graph name to use when constructing the scene test_node_name: Node name to use when constructing the scene without "setup" explicitly provided in test_run test_node_type: Node type to use when constructing the scene without "setup" explicitly provided in test_run test_run: Dictionary of consist of four sub-lists and a dictionary: - values for input attributes, set before the test starts - values for output attributes, checked after the test finishes - initial values for state attributes, set before the test starts - final values for state attributes, checked after the test finishes - setup to be used for populating the scene via controller For complete implementation see generate_user_test_data. last_test_info: When executing multiple tests cases for the same node, this represents graph and node used in previous run instance_count: number of instances to create assotiated to this graph, in order to test vectorized compute Returns: Graph and node to use in current execution of the test """ test_info = last_test_info setup = test_run.get("setup", None) if setup: (test_info.graph, test_nodes, _, _) = controller.edit(test_graph_name, setup) tc.assertTrue(test_nodes) test_info.node = test_nodes[0] elif setup is None: test_info.graph = controller.create_graph(test_graph_name) test_info.node = controller.create_node((test_node_name, test_info.graph), test_node_type) else: tc.assertTrue( test_info.graph is not None and test_info.graph.is_valid(), "Test is misconfigured - empty setup cannot be in the first test", ) tc.assertTrue(test_info.graph is not None and test_info.graph.is_valid(), "Test graph invalid") tc.assertTrue(test_info.node is not None and test_info.node.is_valid(), "Test node invalid") test_info.graph.set_auto_instancing_allowed(False) await controller.evaluate(test_info.graph) inputs = test_run.get("inputs", []) state_set = test_run.get("state_set", []) values_to_set = inputs + state_set if values_to_set: for attribute_name, attribute_value, _ in values_to_set: controller.set(attribute=(attribute_name, test_info.node), value=attribute_value) # create some instance prims, and apply the graph on it if instance_count != 0: stage = omni.usd.get_context().get_stage() for i in range(instance_count): prim_name = f"/World/Test_Instance_Prim_{i}" stage.DefinePrim(prim_name) OmniGraphSchemaTools.applyOmniGraphAPI(stage, prim_name, test_graph_name) return test_info # -------------------------------------------------------------------------------------------------------------- def _test_verify_scene( tc: unittest.TestCase, controller: og.Controller, test_run: Dict[str, Any], test_info: _TestGraphAndNode, error_msg: str, instance_count=0, ): """Verify the scene state based on given test run dictionary Args: tc: Unit test case executing this method. Used to raise errors controller: Controller object to use when constructing the scene (e.g. may have undo support disabled) test_run: Dictionary of consist of four sub-lists and a dictionary: - values for input attributes, set before the test starts - values for output attributes, checked after the test finishes - initial values for state attributes, set before the test starts - final values for state attributes, checked after the test finishes - setup to be used for populating the scene via controller For complete implementation see generate_user_test_data. error_msg: Customized error message to use as a prefix for all unit test errors detected within this method instance_count: number of instances assotiated to this graph that needs to be verified """ outputs = test_run.get("outputs", []) state_get = test_run.get("state_get", []) for attribute_name, expected_value, _ in outputs + state_get: test_attribute = controller.attribute(attribute_name, test_info.node) expected_type = None if isinstance(expected_value, dict): expected_type = expected_value["type"] expected_value = expected_value["value"] if instance_count != 0: for i in range(instance_count): actual_output = controller.get(attribute=test_attribute, instance=i) verify_values( expected_value, actual_output, f"{error_msg}: {attribute_name} attribute value error on instance {i}", ) else: actual_output = controller.get(attribute=test_attribute) verify_values(expected_value, actual_output, f"{error_msg}: {attribute_name} attribute value error") if expected_type: tp = og.AttributeType.type_from_ogn_type_name(expected_type) actual_type = test_attribute.get_resolved_type() if tp != actual_type: raise ValueError( f"{error_msg} - {attribute_name}: Expected {expected_type}, saw {actual_type.get_ogn_type_name()}" ) # ============================================================================================================== # _____ ______ _____ _____ ______ _____ _______ ______ _____ # | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ # | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | # | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | # | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | # |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ #
39,995
Python
47.538835
130
0.60185
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_internal_registration.py
# pylint: disable=too-many-lines """Tests the correct generation of node type definitions into the cache""" from __future__ import annotations import sys from contextlib import ExitStack from pathlib import Path from tempfile import TemporaryDirectory import omni.graph.core as og import omni.graph.core.tests as ogts import omni.graph.tools._internal as ogi import omni.kit.test from omni.graph.core._impl._registration.extension_management import extension_management_factory from omni.graph.tools.tests.internal_utils import TemporaryPathAddition from ._internal_utils import _TestExtensionManager # Helper constants shared by many tests _CURRENT_VERSIONS = ogi.GenerationVersions(ogi.Compatibility.FullyCompatible) _EXT_INDEX = 0 # ============================================================================================================== class ModuleContexts: def __init__(self, stack: ExitStack): """Set up a stack of contexts to use for tests running in individual temporary directory""" global _EXT_INDEX _EXT_INDEX += 1 self.ext_name = f"omni.test.internal.registration{_EXT_INDEX}" # Default extension version is 0.1.0 so create an ID with that self.ext_id = f"{self.ext_name}-0.1.0" # Put all temporary files in a temporary directory for easy disposal self.test_directory = Path(stack.enter_context(TemporaryDirectory())) # pylint: disable=consider-using-with self.python_root = Path(self.test_directory) / "exts" self.module_name = self.ext_name self.module_path = self.python_root / self.ext_name / self.ext_name.replace(".", "/") # Redirect the usual node cache to the temporary directory self.cache_root = stack.enter_context(ogi.TemporaryCacheLocation(self.test_directory / "cache")) # Add the import path of the new extension to the system path self.path_addition = stack.enter_context(TemporaryPathAddition(self.python_root / self.ext_name)) # Uncomment this to dump debugging information while the tests are running # self.log = stack.enter_context(ogi.TemporaryLogLocation("stdout")) # ============================================================================================================== def _expected_cache_contents( cache_root: Path, node_type_name: str, exclusions: list[ogi.FileType] = None ) -> list[Path]: """Returns a list of the files that should be in the generated cache at the given root for the given node type""" file_list = [cache_root / "__init__.py", cache_root / f"{node_type_name}Database.py"] if ogi.FileType.DOCS not in (exclusions or []): file_list.append(cache_root / "docs" / f"{node_type_name}.rst") if ogi.FileType.TEST not in (exclusions or []): file_list.append(cache_root / "tests" / "__init__.py") file_list.append(cache_root / "tests" / f"Test{node_type_name}.py") if ogi.FileType.USD not in (exclusions or []): file_list.append(cache_root / "tests" / "usd" / f"{node_type_name}Template.usda") return file_list # ============================================================================================================== def _expected_1_18_module_files( module_root: Path, node_type_name: str, exclusions: list[ogi.FileType] = None ) -> list[Path]: """Returns a list of the files that should be in a standard V1.18 generated module directory for one node type""" file_list = [ module_root / "__init__.py", module_root / "ogn" / "nodes" / f"{node_type_name}.ogn", module_root / "ogn" / "nodes" / f"{node_type_name}.py", module_root / "ogn" / f"{node_type_name}Database.py", ] if ogi.FileType.TEST not in (exclusions or []): file_list.append(module_root / "ogn" / "tests" / "__init__.py") file_list.append(module_root / "ogn" / "tests" / f"Test{node_type_name}.py") if ogi.FileType.USD not in (exclusions or []): file_list.append(module_root / "ogn" / "tests" / "usd" / f"{node_type_name}Template.usda") return file_list # ============================================================================================================== def _expected_standalone_module_files(module_root: Path, node_type_name: str) -> list[Path]: """Returns a list of the files that should be in a non-generated module directory for one node type""" return [ module_root / "__init__.py", module_root / "nodes" / f"{node_type_name}.ogn", module_root / "nodes" / f"{node_type_name}.py", ] # ============================================================================================================== class TestInternalRegistration(ogts.OmniGraphTestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.maxDiff = None # Diffs of file path lists can be large so let the full details be seen # -------------------------------------------------------------------------------------------------------------- async def _test_extension_modules(self, import_ogn: bool, import_ogn_tests: bool, generate_tests: bool): """Metatest that the utility to create a test extension creates the proper imports for a single configuration Args: import_ogn: Add the ogn submodule to the extension.toml python module list import_ogn: Add the ogn.tests submodule to the extension.toml python module list generate_tests: Generate/initialize test files for the node type generated code """ with ExitStack() as stack: ctx = ModuleContexts(stack) self.assertTrue(str(ctx.python_root / ctx.ext_name) in sys.path) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, _CURRENT_VERSIONS, import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, ) exclusions = [] if generate_tests else [ogi.FileType.TEST] exclusions += [ogi.FileType.USD, ogi.FileType.DOCS] ext_contents.add_v1_18_node("OgnTestNode", exclusions) expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ] expected_files += _expected_1_18_module_files(ctx.module_path, "OgnTestNode", exclusions) actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "Created extension contents") ext_ogn_mgr = extension_management_factory(ctx.ext_id, ctx.ext_name, ctx.python_root / ctx.ext_name) self.assertIsNotNone(ext_ogn_mgr) ext_ogn_mgr.scan_for_nodes() ext_ogn_mgr.ensure_files_up_to_date() (ogn_module, ogn_test_module) = ext_ogn_mgr.ensure_required_modules_exist() self.assertIsNotNone(ogn_module) if generate_tests: self.assertIsNotNone(ogn_test_module) else: self.assertIsNone(ogn_test_module) # -------------------------------------------------------------------------------------------------------------- async def test_extension_modules(self): """Metatest that the utility to create a test extension creates the proper modules for all configurations""" for test_configuration in [0b000, 0b100, 0b110, 0b001, 0b101, 0b111]: import_ogn = test_configuration & 0b100 != 0 import_ogn_tests = test_configuration & 0b010 != 0 generate_tests = test_configuration & 0b001 != 0 with self.subTest(import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, generate_tests=generate_tests): await self._test_extension_modules( import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, generate_tests=generate_tests ) # -------------------------------------------------------------------------------------------------------------- async def _test_extension_imports(self, import_ogn: bool, import_ogn_tests: bool, generate_tests: bool): """Metatest that the utility to create a test extension creates the proper imports for a single configuration Args: import_ogn: Add the ogn submodule to the extension.toml python module list import_ogn: Add the ogn.tests submodule to the extension.toml python module list generate_tests: Generate/initialize test files for the node type generated code """ test_config = f"import_ogn={import_ogn}, import_ogn_tests={import_ogn_tests}" with ExitStack() as stack: ctx = ModuleContexts(stack) self.assertTrue(str(ctx.python_root / ctx.ext_name) in sys.path) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, _CURRENT_VERSIONS, import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, ) exclusions = [] if generate_tests else [ogi.FileType.TEST] exclusions += [ogi.FileType.USD, ogi.FileType.DOCS] ext_contents.add_v1_18_node("OgnTestNode", exclusions) expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ] expected_files += _expected_1_18_module_files(ctx.module_path, "OgnTestNode", exclusions) actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, f"Created extension contents using {test_config}") ext_ogn_mgr = extension_management_factory(ctx.ext_id, ctx.ext_name, ctx.python_root / ctx.ext_name) self.assertIsNotNone(ext_ogn_mgr, test_config) ext_ogn_mgr.scan_for_nodes() ext_ogn_mgr.ensure_files_up_to_date() # Ensure that the OGN submodules could be found in the newly created extension (ogn_module, ogn_test_module) = ext_ogn_mgr.ensure_required_modules_exist() self.assertIsNotNone(ogn_module, test_config) self.assertTrue(not generate_tests or ogn_test_module is not None, test_config) (ogn_module, ogn_test_module) = ext_ogn_mgr.do_python_imports() # Do it twice because the second time it should just pick it up from sys.modules (ogn_module_2, ogn_test_module_2) = ext_ogn_mgr.do_python_imports() self.assertEqual(ogn_module, ogn_module_2, test_config) self.assertEqual(ogn_test_module, ogn_test_module_2, test_config) # Check the contents of the ogn submodule to make sure the node class and database were imported self.assertIsNotNone(ogn_module, test_config) self.assertTrue(hasattr(ogn_module, ext_ogn_mgr.NODE_STORAGE_OBJECT), test_config) self.assertTrue(getattr(ogn_module, ext_ogn_mgr.NODE_STORAGE_OBJECT), test_config) self.assertTrue(hasattr(ogn_module, "OgnTestNodeDatabase"), test_config) ogn_module_file_path = ogi.get_module_path(ogn_module) self.assertIsNotNone(ogn_module_file_path, test_config) self.assertTrue(ctx.module_path in ogn_module_file_path.parents, test_config) # If tests were requested then confirm the generated tests was imported into the ogn.tests submodule if generate_tests: self.assertIsNotNone(ogn_test_module, test_config) self.assertTrue(hasattr(ogn_test_module, "TestOgnTestNode"), test_config) ogn_test_module_file_path = ogi.get_module_path(ogn_test_module) self.assertIsNotNone(ogn_test_module_file_path, test_config) self.assertTrue(ctx.module_path in ogn_test_module_file_path.parents, test_config) else: self.assertIsNone(ogn_test_module, test_config) # -------------------------------------------------------------------------------------------------------------- async def test_extension_imports(self): """Metatest that the utility to create a test extension imports the proper modules for all configurations""" for test_configuration in [0b000, 0b100, 0b110, 0b001, 0b101, 0b111]: import_ogn = test_configuration & 0b100 != 0 import_ogn_tests = test_configuration & 0b010 != 0 generate_tests = test_configuration & 0b001 != 0 with self.subTest(import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, generate_tests=generate_tests): await self._test_extension_imports( import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, generate_tests=generate_tests ) # -------------------------------------------------------------------------------------------------------------- async def _test_extension_cached_imports( self, import_ogn: bool, import_ogn_tests: bool, generate_tests: bool, use_prebuilt_cache: bool, ): """Metatest that the utility to create a test extension creates the proper imports for a single configuration Args: import_ogn: Add the ogn submodule to the extension.toml python module list import_ogn: Add the ogn.tests submodule to the extension.toml python module list generate_tests: Generate/initialize test files for the node type generated code use_prebuilt_cache: If True then prebuild the up-to-date cache files, otherwise generate old ones to ignore """ # ogi.set_registration_logging("stdout") # Uncomment for test debugging information test_config = ( f"import_ogn={import_ogn}, import_ogn_tests={import_ogn_tests}, " f"tests={generate_tests}, prebuilt={use_prebuilt_cache}" ) with ExitStack() as stack: ctx = ModuleContexts(stack) self.assertTrue(str(ctx.python_root / ctx.ext_name) in sys.path, test_config) # Create an old cache to make sure it gets ignored as well exclusions = [] if generate_tests else [ogi.FileType.TEST] exclusions += [ogi.FileType.USD, ogi.FileType.DOCS] ext_contents_incompatible = _TestExtensionManager( ctx.python_root, ctx.ext_name, ogi.GenerationVersions(ogi.Compatibility.Incompatible), import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, ) ext_contents_incompatible.add_v1_18_node("OgnTestNode", exclusions) compatibility = ogi.Compatibility.FullyCompatible if use_prebuilt_cache else ogi.Compatibility.Incompatible cache_versions = ogi.GenerationVersions(compatibility) current_cache_directory = ogi.full_cache_path(cache_versions, ctx.ext_id, ctx.module_name) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, cache_versions, import_ogn=import_ogn, import_ogn_tests=import_ogn_tests, ) ext_contents.add_cache_for_node("OgnTestNode", exclusions) cached_files = _expected_cache_contents(current_cache_directory, "OgnTestNode", exclusions) # If using the obsolete cache then add in the ones that will be built when the generator runs if not use_prebuilt_cache: current_cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name) cached_files += _expected_cache_contents(current_cache_directory, "OgnTestNode", exclusions) expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", # Not in the cache ] expected_files += _expected_1_18_module_files(ctx.module_path, "OgnTestNode", exclusions) expected_files += cached_files ext_ogn_mgr = extension_management_factory(ctx.ext_id, ctx.ext_name, ctx.python_root / ctx.ext_name) self.assertIsNotNone(ext_ogn_mgr, test_config) ext_ogn_mgr.scan_for_nodes() ext_ogn_mgr.ensure_files_up_to_date() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, f"Created extension contents with {test_config}") # Ensure that the OGN submodules could be found in the newly created extension (ogn_module, ogn_test_module) = ext_ogn_mgr.do_python_imports() # Do it twice because the second time it should just pick it up from sys.modules (ogn_module_2, ogn_test_module_2) = ext_ogn_mgr.do_python_imports() self.assertEqual(ogn_module, ogn_module_2, test_config) self.assertEqual(ogn_test_module, ogn_test_module_2, test_config) # Check the contents of the ogn submodule to make sure the node class and database were imported self.assertIsNotNone(ogn_module, test_config) self.assertTrue(hasattr(ogn_module, ext_ogn_mgr.NODE_STORAGE_OBJECT), test_config) self.assertTrue(getattr(ogn_module, ext_ogn_mgr.NODE_STORAGE_OBJECT), test_config) self.assertTrue(hasattr(ogn_module, "OgnTestNodeDatabase"), test_config) ogn_module_file_path = ogi.get_module_path(ogn_module.OgnTestNodeDatabase) self.assertIsNotNone(ogn_module_file_path, test_config) self.assertTrue( current_cache_directory in ogn_module_file_path.parents, f"Cache {current_cache_directory} not in {ogn_module_file_path} - {test_config}", ) # If tests were requested then confirm the generated tests was imported into the ogn.tests submodule if generate_tests: self.assertIsNotNone(ogn_test_module, test_config) self.assertTrue(hasattr(ogn_test_module, "TestOgnTestNode"), test_config) ogn_test_module_file_path = ogi.get_module_path(ogn_test_module) self.assertIsNotNone(ogn_test_module_file_path, test_config) self.assertTrue( current_cache_directory in ogn_module_file_path.parents, f"Cache {current_cache_directory} not in {ogn_module_file_path} - {test_config}", ) else: self.assertIsNone(ogn_test_module, test_config) # -------------------------------------------------------------------------------------------------------------- async def test_extension_cached_imports_ffff(self): """Metatest that the utility to create a test extension that requires building a cache imports the proper modules for all configurations from that cache. These all have to run as separate tests in order to avoid stomping on each other's import spaces and cache directories. """ await self._test_extension_cached_imports(False, False, False, False) async def test_extension_cached_imports_tfff(self): await self._test_extension_cached_imports(True, False, False, False) async def test_extension_cached_imports_ttff(self): await self._test_extension_cached_imports(True, True, False, False) async def test_extension_cached_imports_fftf(self): await self._test_extension_cached_imports(False, False, True, False) async def test_extension_cached_imports_tftf(self): await self._test_extension_cached_imports(True, False, True, False) async def test_extension_cached_imports_tttf(self): await self._test_extension_cached_imports(True, True, True, False) async def test_extension_cached_imports_ffft(self): await self._test_extension_cached_imports(False, False, False, True) async def test_extension_cached_imports_tfft(self): await self._test_extension_cached_imports(True, False, False, True) async def test_extension_cached_imports_ttft(self): await self._test_extension_cached_imports(True, True, False, True) async def test_extension_cached_imports_fftt(self): await self._test_extension_cached_imports(False, False, True, True) async def test_extension_cached_imports_tftt(self): await self._test_extension_cached_imports(True, False, True, True) async def test_extension_cached_imports_tttt(self): await self._test_extension_cached_imports(True, True, True, True) # -------------------------------------------------------------------------------------------------------------- def __confirm_module_contents(self, expected_modules_and_contents: list[tuple[str, str]]): """Asserts if the module does not contain at least all of the expected symbols. Args: expected_modules_and_contents: List of (MODULE_NAME, EXPECTED_SYMBOLS) to verify """ for expected_name, symbols in expected_modules_and_contents: self.assertTrue(expected_name in sys.modules, f"Looking for module {expected_name}") actual_contents = dir(sys.modules[expected_name]) for expected_symbol in symbols: self.assertTrue( expected_symbol in actual_contents, f"Looking for symbol {expected_symbol} in {expected_name}" ) # -------------------------------------------------------------------------------------------------------------- async def test_raw_extension_creation(self): """Metatest that the utility to create a test extension using the generated files and successfully load a file of the generated type into a scene. """ with ExitStack() as stack: ctx = ModuleContexts(stack) self.assertTrue(str(ctx.python_root / ctx.ext_name) in sys.path) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, _CURRENT_VERSIONS, import_ogn=False, import_ogn_tests=False, ) ext_contents.add_v1_18_node("OgnTestNode") ext_ogn_mgr = extension_management_factory(ctx.ext_id, ctx.ext_name, ctx.python_root / ctx.ext_name) self.assertIsNotNone(ext_ogn_mgr) ext_ogn_mgr.scan_for_nodes() ext_ogn_mgr.ensure_files_up_to_date() (ogn_module, ogn_test_module) = ext_ogn_mgr.do_python_imports() self.assertIsNotNone(ogn_module) self.assertIsNotNone(ogn_test_module) ext_ogn_mgr.do_registration() # Enable the extension inside Kit await ext_contents.enable() # Confirm that the test node type now exists and can be instantiated (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) # Confirm that the modules were correctly created expected_modules_and_contents = [ (ctx.ext_name, ["_PublicExtension"]), (f"{ctx.ext_name}.ogn", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.OgnTestNodeDatabase", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.nodes.OgnTestNode", ["OgnTestNode"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnTestNode", ["TestOgn"]), ] self.__confirm_module_contents(expected_modules_and_contents) # Clear the scene and disable the extension await omni.usd.get_context().new_stage_async() await ext_contents.disable() # Confirm that the test node type no longer exists with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {og.Controller.Keys.CREATE_NODES: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) # -------------------------------------------------------------------------------------------------------------- async def test_cache_generation(self): """Test that an extension with no prebuilt files registers and is seen correctly. This entails enabling the test extension and then looking at the modules to ensure that: - the database exists and can be imported - the node type was correctly registered - the generated test was correctly registered - the database, node type, and generated test are removed when the extension is disabled """ with ExitStack() as stack: ctx = ModuleContexts(stack) cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, ogi.GenerationVersions(), import_ogn=False, import_ogn_tests=False, ) ext_contents.add_standalone_node("OgnTestNode") expected_cache_files = _expected_cache_contents(cache_directory, "OgnTestNode") expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ] expected_files += _expected_standalone_module_files(ctx.module_path, "OgnTestNode") expected_files += expected_cache_files # Register the extension and enable it try: await ext_contents.enable() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "Rebuilt cached extension") # Confirm that the test node type now exists and can be instantiated key_create = og.Controller.Keys.CREATE_NODES (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) # Confirm that the modules were correctly created expected_modules_and_contents = [ (ctx.ext_name, ["_PublicExtension"]), (f"{ctx.ext_name}.nodes.OgnTestNode", ["OgnTestNode"]), (f"{ctx.ext_name}.ogn", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.OgnTestNodeDatabase", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnTestNode", ["TestOgn"]), ] self.__confirm_module_contents(expected_modules_and_contents) # Double check the imported database file to make sure it is using the cached one db_object = getattr(sys.modules[f"{ctx.ext_name}.ogn.OgnTestNodeDatabase"], "OgnTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) ogn_module_file_path = ogi.get_module_path(sys.modules[f"{ctx.ext_name}.ogn"]) self.assertIsNotNone(ogn_module_file_path) self.assertTrue(cache_directory in ogn_module_file_path.parents) # Clear the scene and disable the extension await omni.usd.get_context().new_stage_async() finally: await ext_contents.disable() # Confirm that the test node type no longer exists with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) # -------------------------------------------------------------------------------------------------------------- async def test_cache_generation_from_old_build(self): """Test that an extension with prebuilt files that are out of date registers and is seen correctly. This entails enabling the test extension and then looking at the modules to ensure that: - the database exists and can be imported - the node type was correctly registered - the generated test was correctly registered - the database, node type, and generated test are removed when the extension is disabled """ with ExitStack() as stack: ctx = ModuleContexts(stack) cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, ogi.GenerationVersions(ogi.Compatibility.Incompatible), import_ogn=False, import_ogn_tests=False, ) ext_contents.add_v1_18_node("OgnTestNode") expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ] expected_files += _expected_cache_contents(cache_directory, "OgnTestNode") expected_files += _expected_1_18_module_files(ctx.module_path, "OgnTestNode") # Register the extension and enable it try: await ext_contents.enable() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "Rebuilt cached extension") # Confirm that the test node type now exists and can be instantiated key_create = og.Controller.Keys.CREATE_NODES (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) # Confirm that the modules were correctly created expected_modules_and_contents = [ (ctx.ext_name, ["_PublicExtension"]), (f"{ctx.ext_name}.ogn", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.nodes.OgnTestNode", ["OgnTestNode"]), (f"{ctx.ext_name}.ogn.OgnTestNodeDatabase", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnTestNode", ["TestOgn"]), ] self.__confirm_module_contents(expected_modules_and_contents) # Double check the version number in the imported database file to make sure it is using the cached one db_module = sys.modules[f"{ctx.ext_name}.ogn.OgnTestNodeDatabase"] db_object = getattr(db_module, "OgnTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) db_module_path = ogi.get_module_path(db_module) self.assertIsNotNone(db_module_path) self.assertTrue(cache_directory in db_module_path.parents) # Clear the scene and disable the extension await omni.usd.get_context().new_stage_async() finally: await ext_contents.disable() # Confirm that the test node type no longer exists with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) # -------------------------------------------------------------------------------------------------------------- async def test_cache_update(self): """Test that an extension with prebuilt files that are from a compatible version but whose .ogn files are out of date correctly notices and rebuilds cached files and registers them correctly. This entails enabling the test extension and then looking at the modules to ensure that: - the database exists and can be imported - the node type was correctly registered - the generated test was correctly registered - the database, node type, and generated test are removed when the extension is disabled """ with ExitStack() as stack: ctx = ModuleContexts(stack) incompatible = ogi.GenerationVersions(ogi.Compatibility.Incompatible) cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name) old_cache_directory = ogi.full_cache_path(incompatible, ctx.ext_id, ctx.module_name) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, _CURRENT_VERSIONS, import_ogn=False, import_ogn_tests=False, ) ext_contents.add_v1_18_node("OgnTestNode") ext_contents_incompatible = _TestExtensionManager( ctx.python_root, ctx.ext_name, incompatible, import_ogn=False, import_ogn_tests=False, ) ext_contents_incompatible.add_cache_for_node("OgnTestNode") expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ] expected_files += _expected_cache_contents(old_cache_directory, "OgnTestNode") expected_files += _expected_1_18_module_files(ctx.module_path, "OgnTestNode") actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "Rebuilt cached extension") ogn_file = ctx.module_path / "ogn" / "nodes" / "OgnTestNode.ogn" ogn_file.touch() # Files that will be built when the cache updates after registration expected_cache_files = _expected_cache_contents(cache_directory, "OgnTestNode") # Register the extension and enable it try: await ext_contents.enable() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files + expected_cache_files, actual_files, "Rebuilt cached extension") # Confirm that the test node type now exists and can be instantiated key_create = og.Controller.Keys.CREATE_NODES (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) # Confirm that the modules were correctly created expected_modules_and_contents = [ (ctx.ext_name, ["_PublicExtension"]), (f"{ctx.ext_name}.ogn", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.nodes.OgnTestNode", ["OgnTestNode"]), (f"{ctx.ext_name}.ogn.OgnTestNodeDatabase", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnTestNode", ["TestOgn"]), ] self.__confirm_module_contents(expected_modules_and_contents) # Double check the version number in the imported database file to make sure it is using the cached one db_module = sys.modules[f"{ctx.ext_name}.ogn.OgnTestNodeDatabase"] db_object = getattr(db_module, "OgnTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) db_module_path = ogi.get_module_path(db_module) self.assertIsNotNone(db_module_path) self.assertTrue(cache_directory in db_module_path.parents) # Double check the path to the registered test to make sure it is using the newly generated cache test_module = sys.modules[f"{ctx.ext_name}.ogn.tests.TestOgnTestNode"] test_module_path = ogi.get_module_path(test_module) self.assertIsNotNone(test_module_path) self.assertTrue(cache_directory in test_module_path.parents) # Clear the scene and disable the extension await omni.usd.get_context().new_stage_async() finally: await ext_contents.disable() # Confirm that the test node type no longer exists with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) # -------------------------------------------------------------------------------------------------------------- async def test_hot_reload(self): """Test that an extension cache is correctly generated when loading, then regenerated after a .ogn change. The .ogn change is such that it can be checked at runtime (adding an attribute). """ with ExitStack() as stack: ctx = ModuleContexts(stack) cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, ogi.GenerationVersions(ogi.Compatibility.Incompatible), import_ogn=False, import_ogn_tests=False, ) ext_contents.add_v1_18_node("OgnTestNode") expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ] expected_files += _expected_cache_contents(cache_directory, "OgnTestNode") expected_files += _expected_1_18_module_files(ctx.module_path, "OgnTestNode") # Register the extension and enable it try: await ext_contents.enable() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "Rebuilt cached extension") # Confirm that the test node type now exists and can be instantiated key_create = og.Controller.Keys.CREATE_NODES (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) await og.Controller.evaluate() self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) # Modify the .ogn to add in a new attribute, then wait for the scene to reattach await ext_contents.add_hot_attribute_to_ogn() # This syncs are to wait for the hot reload to happen await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "After hot reload") # Rebuild the scene. This is necessary because the scene reattach process does not currently update any # modified nodes with their new attributes so the only way to test this is to create a new node and # check that it picks up the new definition. await omni.usd.get_context().new_stage_async() (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) await og.Controller.evaluate() self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) # Confirm that the hot-reloading attribute now exists hot_attribute = og.Controller.attribute("inputs:hot", test_node) self.assertIsNotNone(hot_attribute) self.assertTrue(hot_attribute.is_valid()) # Confirm that the modules were correctly created expected_modules_and_contents = [ (ctx.ext_name, ["_PublicExtension"]), (f"{ctx.ext_name}.ogn", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.nodes.OgnTestNode", ["OgnTestNode"]), (f"{ctx.ext_name}.ogn.OgnTestNodeDatabase", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnTestNode", ["TestOgn"]), ] self.__confirm_module_contents(expected_modules_and_contents) # Double check the imported database file to make sure it is using the cached one db_object = getattr(sys.modules[f"{ctx.ext_name}.ogn.OgnTestNodeDatabase"], "OgnTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) db_file_path = ogi.get_module_path(sys.modules[f"{ctx.ext_name}.ogn.OgnTestNodeDatabase"]) self.assertIsNotNone(db_file_path) self.assertTrue( cache_directory in db_file_path.parents, f"Expected {cache_directory} to be a parent of {db_file_path}", ) # Clear the scene and disable the extension await omni.usd.get_context().new_stage_async() finally: await ext_contents.disable() # Confirm that the test node type no longer exists with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", {key_create: [("TestNode", f"{ctx.ext_name}.OgnTestNode")]} ) # -------------------------------------------------------------------------------------------------------------- async def test_multiple_nodes(self): """Test that a built extension with more than one node correctly imports all of them""" with ExitStack() as stack: ctx = ModuleContexts(stack) cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, _CURRENT_VERSIONS, import_ogn=False, import_ogn_tests=False, ) ext_contents.add_v1_18_node("OgnTestNode") ext_contents.add_v1_18_node("OgnGoodTestNode") expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ] expected_files += _expected_1_18_module_files(ctx.module_path, "OgnTestNode") expected_files += _expected_1_18_module_files(ctx.module_path, "OgnGoodTestNode") expected_files += _expected_cache_contents(cache_directory, "OgnTestNode") expected_files = list(set(expected_files)) # Touch the .ogn file to make it out of date outdated_ogn = ctx.module_path / "ogn" / "nodes" / "OgnTestNode.ogn" outdated_ogn.touch() # Register the extension and enable it try: await ext_contents.enable() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "Rebuilt cached extension") # Confirm that the test node type now exists and can be instantiated key_create = og.Controller.Keys.CREATE_NODES (_, (test_node, test_good_node), _, _) = og.Controller.edit( "/TestGraph", { key_create: [ ("TestNode", f"{ctx.ext_name}.OgnTestNode"), ("GoodTestNode", f"{ctx.ext_name}.OgnGoodTestNode"), ] }, ) self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) self.assertIsNotNone(test_good_node) self.assertTrue(test_good_node.is_valid()) # Confirm that the modules were correctly created expected_modules_and_contents = [ (ctx.ext_name, ["_PublicExtension"]), (f"{ctx.ext_name}.ogn", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.nodes.OgnTestNode", ["OgnTestNode"]), (f"{ctx.ext_name}.ogn.OgnTestNodeDatabase", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnTestNode", ["TestOgn"]), (f"{ctx.ext_name}.ogn.OgnGoodTestNodeDatabase", ["OgnGoodTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnGoodTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnGoodTestNode", ["TestOgn"]), ] self.__confirm_module_contents(expected_modules_and_contents) # Double check the version number in the imported database file to make sure it is using the cached one db_module = sys.modules[f"{ctx.ext_name}.ogn.OgnTestNodeDatabase"] db_object = getattr(db_module, "OgnTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the cached database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) db_module_path = ogi.get_module_path(db_module) self.assertIsNotNone(db_module_path) self.assertTrue(cache_directory in db_module_path.parents) test_module = sys.modules[f"{ctx.ext_name}.ogn.tests.TestOgnTestNode"] test_object = getattr(test_module, "TestOgn", None) self.assertIsNotNone(test_object, "Could not get the cached test from the extension imports") test_module_path = ogi.get_module_path(test_module) self.assertIsNotNone(test_module_path) self.assertTrue(cache_directory in test_module_path.parents) # Check that the node that did not have to be rebuilt imports from the build directory, not the cache db_module = sys.modules[f"{ctx.ext_name}.ogn.OgnGoodTestNodeDatabase"] db_object = getattr(db_module, "OgnGoodTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the built database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) db_module_path = ogi.get_module_path(db_module) self.assertIsNotNone(db_module_path) self.assertTrue(ctx.module_path in db_module_path.parents) test_module = sys.modules[f"{ctx.ext_name}.ogn.tests.TestOgnGoodTestNode"] test_object = getattr(test_module, "TestOgn", None) self.assertIsNotNone(test_object, "Could not get the built test from the extension imports") test_module_path = ogi.get_module_path(test_module) self.assertIsNotNone(test_module_path) self.assertTrue(ctx.module_path in test_module_path.parents) # Clear the scene and disable the extension await omni.usd.get_context().new_stage_async() finally: await ext_contents.disable() # Confirm that the test node type no longer exists with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", { key_create: [ ("TestNode", f"{ctx.ext_name}.OgnTestNode"), ] }, ) with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", { key_create: [ ("GoodTestNode", f"{ctx.ext_name}.OgnGoodTestNode"), ] }, ) # -------------------------------------------------------------------------------------------------------------- async def test_multiple_standalone_nodes(self): """Test that a built extension with more than one node without generation correctly imports all of them""" with ExitStack() as stack: ctx = ModuleContexts(stack) cache_directory = ogi.full_cache_path(_CURRENT_VERSIONS, ctx.ext_id, ctx.module_name) ext_contents = _TestExtensionManager( ctx.python_root, ctx.ext_name, _CURRENT_VERSIONS, import_ogn=False, import_ogn_tests=False, ) ext_contents.add_standalone_node("OgnTestNode") ext_contents.add_standalone_node("OgnGoodTestNode") expected_files = [ ctx.python_root / ctx.ext_name / "config" / "extension.toml", ctx.module_path / "__init__.py", ] expected_files += _expected_standalone_module_files(ctx.module_path, "OgnTestNode") expected_files += _expected_standalone_module_files(ctx.module_path, "OgnGoodTestNode") expected_files += _expected_cache_contents(cache_directory, "OgnTestNode") expected_files += _expected_cache_contents(cache_directory, "OgnGoodTestNode") expected_files = list(set(expected_files)) # Register the extension and enable it try: await ext_contents.enable() actual_files = [] for root, _dirs, files in ogi.walk_with_excludes(ctx.test_directory, ["__pycache__"]): for file in files: actual_files.append(Path(root) / file) self.assertCountEqual(expected_files, actual_files, "Rebuilt cached extension") # Confirm that the test node type now exists and can be instantiated key_create = og.Controller.Keys.CREATE_NODES (_, (test_node, test_good_node), _, _) = og.Controller.edit( "/TestGraph", { key_create: [ ("TestNode", f"{ctx.ext_name}.OgnTestNode"), ("GoodTestNode", f"{ctx.ext_name}.OgnGoodTestNode"), ] }, ) self.assertIsNotNone(test_node) self.assertTrue(test_node.is_valid()) self.assertIsNotNone(test_good_node) self.assertTrue(test_good_node.is_valid()) # Confirm that the modules were correctly created expected_modules_and_contents = [ (ctx.ext_name, ["_PublicExtension"]), (f"{ctx.ext_name}.nodes.OgnTestNode", ["OgnTestNode"]), (f"{ctx.ext_name}.ogn", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.OgnTestNodeDatabase", ["OgnTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnTestNode", ["TestOgn"]), (f"{ctx.ext_name}.nodes.OgnGoodTestNode", ["OgnGoodTestNode"]), (f"{ctx.ext_name}.ogn", ["OgnGoodTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.OgnGoodTestNodeDatabase", ["OgnGoodTestNodeDatabase"]), (f"{ctx.ext_name}.ogn.tests", ["TestOgnGoodTestNode"]), (f"{ctx.ext_name}.ogn.tests.TestOgnGoodTestNode", ["TestOgn"]), ] self.__confirm_module_contents(expected_modules_and_contents) # Double check the version number in the imported database file to make sure it is using the cached one db_module = sys.modules[f"{ctx.ext_name}.ogn.OgnTestNodeDatabase"] db_object = getattr(db_module, "OgnTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the cached database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) db_module_path = ogi.get_module_path(db_module) self.assertIsNotNone(db_module_path) self.assertTrue(cache_directory in db_module_path.parents) test_module = sys.modules[f"{ctx.ext_name}.ogn.tests.TestOgnTestNode"] test_object = getattr(test_module, "TestOgn", None) self.assertIsNotNone(test_object, "Could not get the cached test from the extension imports") test_module_path = ogi.get_module_path(test_module) self.assertIsNotNone(test_module_path) self.assertTrue(cache_directory in test_module_path.parents) # Check that the node that did not have to be rebuilt imports from the build directory, not the cache db_module = sys.modules[f"{ctx.ext_name}.ogn.OgnGoodTestNodeDatabase"] db_object = getattr(db_module, "OgnGoodTestNodeDatabase", None) self.assertIsNotNone(db_object, "Could not get the built database from the extension imports") generator_version = getattr(db_object, ogi.VersionProperties.GENERATOR.value, None) self.assertEqual(generator_version, ogi.get_generator_extension_version()) target_version = getattr(db_object, ogi.VersionProperties.TARGET.value, None) self.assertEqual(target_version, ogi.get_target_extension_version()) db_module_path = ogi.get_module_path(db_module) self.assertIsNotNone(db_module_path) self.assertTrue( cache_directory in db_module_path.parents, f"{db_module_path} must be a child of {cache_directory}" ) test_module = sys.modules[f"{ctx.ext_name}.ogn.tests.TestOgnGoodTestNode"] test_object = getattr(test_module, "TestOgn", None) self.assertIsNotNone(test_object, "Could not get the built test from the extension imports") test_module_path = ogi.get_module_path(test_module) self.assertIsNotNone(test_module_path) self.assertTrue(cache_directory in test_module_path.parents) # Clear the scene and disable the extension await omni.usd.get_context().new_stage_async() finally: await ext_contents.disable() # Confirm that the test node type no longer exists with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", { key_create: [ ("TestNode", f"{ctx.ext_name}.OgnTestNode"), ] }, ) with self.assertRaises(og.OmniGraphError): (_, (test_node,), _, _) = og.Controller.edit( "/TestGraph", { key_create: [ ("GoodTestNode", f"{ctx.ext_name}.OgnGoodTestNode"), ] }, )
60,394
Python
54.561178
120
0.572375
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/_internal_utils.py
"""Helpers for configuring and running local tests, not meant for general use""" from __future__ import annotations import json from collections import defaultdict from pathlib import Path import omni.ext import omni.graph.tools._internal as ogi import omni.graph.tools.ogn as ogn import omni.kit from omni.graph.tools.tests.internal_utils import CreateHelper # ============================================================================================================== class _TestExtensionManager: """Object that lets you create and control a dynamically generated extension Attributes: __root: Path to the directory in which the extension will be created __ext_path: Path to the created extension directory __ext_name: Name of the created extension __ogn_files: Dictionary of class name to .ogn file implementing the class __module_path: Path to the Python module directory inside the extension __exclusions: List of file types to exclude from any generated code __creator: Helper that creates files of various types """ # Dictionary of Path:count that tracks how many test extensions are using a given path, tracked so that the # extension manager's path information can be properly managed. PATHS_ADDED = defaultdict(lambda: 0) def __init__( self, root: Path, ext_name: str, versions: ogi.GenerationVersions, import_ogn: bool, import_ogn_tests: bool, ): """Initialize the temporary extension object, creating the required files. The files will not be deleted by this class, their lifespan must be managed by the caller, e.g. through using a TempDirectory for their location. Args: root: Directory that contains all extensions ext_name: Name of the extension to create (e.g. 'omni.my.extension') versions: Versions to use in any generated code import_ogn: Add a python module spec for the .ogn submodule in the extension.toml import_ogn_tests: Add a python module spec for the .ogn.tests submodule in the extension.toml Raises: AttributeError if there was a problem creating the extension configuration """ ogi.LOG.info("Creating extension %s at %s", ext_name, root) self.__root: Path = root self.__ext_path: Path = root / ext_name self.__ext_name: str = ext_name self.__ogn_files: dict[str, Path] = {} # Class name to .ogn file implementing it self.__module_path: Path = self.__ext_path / ext_name.replace(".", "/") self.__module_path.mkdir(parents=True, exist_ok=True) self.__exclusions: list[ogi.FileType] = [] self.__creator: CreateHelper = CreateHelper(ext_name, self.__root, versions) self.__creator.add_extension_module(self.__root, ext_name, self.__module_path, import_ogn, import_ogn_tests) # -------------------------------------------------------------------------------------------------------------- def add_standalone_node( self, node_type_name: str, exclusions: list[ogi.FileType] = None, ): """Add a node definition for a node with no generated code. See CreateHelper.add_standalone_node for details""" created_files = self.__creator.add_standalone_node(node_type_name, exclusions) self.__exclusions = exclusions for created_file in created_files: if created_file.suffix == ".ogn": self.__ogn_files[node_type_name] = created_file return raise ValueError(f"No .ogn file found in standalone created files {created_files}") # -------------------------------------------------------------------------------------------------------------- def add_v1_18_node( self, node_type_name: str, exclusions: list[ogi.FileType] = None, ): """Add a node definition using the V1.18 and earlier pattern. See CreateHelper.add_v1_18_node for details""" created_files = self.__creator.add_v1_18_node(node_type_name, exclusions) self.__exclusions = exclusions for created_file in created_files: if created_file.suffix == ".ogn": self.__ogn_files[node_type_name] = created_file return raise ValueError(f"No .ogn file found in V1.18 created files {created_files}") # -------------------------------------------------------------------------------------------------------------- def add_v1_19_node( self, node_type_name: str, exclusions: list[ogi.FileType] = None, ): """Add a node definition using the V1.19 pattern. See CreateHelper.add_v1_19_node for details""" created_files = self.__creator.add_v1_19_node(node_type_name, exclusions) self.__exclusions = exclusions for created_file in created_files: if created_file.suffix == ".ogn": self.__ogn_files[node_type_name] = created_file return raise ValueError(f"No .ogn file found in V1.19 created files {created_files}") # -------------------------------------------------------------------------------------------------------------- def add_cache_for_node( self, node_type_name: str, exclusions: list[ogi.FileType] = None, ): """Add a node definition to the cache. See CreateHelper.add_cache_for_node for details""" self.__creator.add_cache_for_node(node_type_name, exclusions) self.__exclusions = exclusions # -------------------------------------------------------------------------------------------------------------- async def add_hot_attribute_to_ogn(self): """Rewrite the .ogn file with a new input attribute "hot_attribute" for hot reload testing""" ogi.LOG.info("!!! Adding hot reload attribute to %s", str(self.__ogn_files)) # Remember the .ogn definitions for use in the generation of sample code ogn_definitions = { class_name: { ogn.NodeTypeKeys.DESCRIPTION: "None", ogn.NodeTypeKeys.VERSION: 1, ogn.NodeTypeKeys.EXCLUDE: self.__exclusions or [], ogn.NodeTypeKeys.LANGUAGE: ogn.LanguageTypeValues.PYTHON, ogn.NodeTypeKeys.INPUTS: { "hot": {"type": "bool", "description": "Additional attribute added for hot reload"} }, } for class_name in self.__ogn_files } ogi.LOG.info("Updated ogn definition(s) in %s", self.__ogn_files) for class_name, ogn_path in self.__ogn_files.items(): ogn_path = CreateHelper.safe_create( self.__module_path / "ogn" / "nodes", class_name, ogi.FileType.OGN, json.dumps({class_name: ogn_definitions[class_name]}), ) self.__ogn_files[class_name] = ogn_path ogi.LOG.info("!!! Attribute added from hot reload") # -------------------------------------------------------------------------------------------------------------- def add_extra_import(self, directory_name: str, file_name: str, object_to_define: str) -> Path: """Add a new file under the ogn/ directory that acts as a proxy for an import that results from the links that the LUA function add_ogn_subdirectory() adds. Returns the path to the newly created file. """ return CreateHelper.safe_create( # self.__module_path / "ogn" / directory_name / file_name, self.__module_path / "ogn" / file_name, None, None, f"{object_to_define} = True\n", ) # -------------------------------------------------------------------------------------------------------------- async def enable(self): """Make the constructed extension visible to the extension manager, if it hasn't yet been, and enable it""" ogi.LOG.info("Enabling extension %s at %s", self.__ext_name, self.__ext_path) manager = omni.kit.app.get_app().get_extension_manager() # Remove and add back to ensure that the path is scanned for the new content manager.remove_path(str(self.__root)) manager.add_path(str(self.__root), omni.ext.ExtensionPathType.COLLECTION_USER) # This sync is to get the manager to refresh its paths await omni.kit.app.get_app().next_update_async() manager.set_extension_enabled(self.__ext_name, True) self.PATHS_ADDED[self.__root] += 1 # This sync is to allow time for executing the extension enabled hooks await omni.kit.app.get_app().next_update_async() # -------------------------------------------------------------------------------------------------------------- async def disable(self): """Disable the constructed extension, if enabled and decrement the accesses to its path""" ogi.LOG.info("Disabling extension %s", self.__ext_name) manager = omni.kit.app.get_app().get_extension_manager() # If this was the last extension to need the path then remove it from the manager's path. Either way the # path is removed first to force the path to be scanned for the remaining content. manager.set_extension_enabled(self.__ext_name, False) # This sync is to ensure the extension is disabled before removing its path await omni.kit.app.get_app().next_update_async() manager.remove_path(str(self.__root)) self.PATHS_ADDED[self.__root] -= 1 # If some other creator exists in the same path then bring the path back for continued use if self.PATHS_ADDED[self.__root] > 0: manager.add_path(str(self.__root), omni.ext.ExtensionPathType.COLLECTION_USER) # This sync is to get the manager to executing the extension disabled hooks and refresh the paths await omni.kit.app.get_app().next_update_async()
10,058
Python
49.044776
119
0.568304
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core as og import omni.graph.core._impl.commands as ogc import omni.graph.core.autonode as autonode import omni.graph.core.typing as ogty import omni.kit from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphApi(omni.kit.test.AsyncTestCase): _UNPUBLISHED = ["bindings", "tests", "omni", "commands"] async def test_api(self): _check_module_api_consistency(og.tests, [], is_test_module=True) # noqa: PLW0212 _check_module_api_consistency(autonode) # noqa: PLW0212 _check_module_api_consistency(ogty) # noqa: PLW0212 _check_module_api_consistency(ogc, ogc._HIDDEN) # noqa: PLW0212 # Since the og module also contains all of the previously exposed objects for backward compatibility, they # have to be added to the list of unpublished elements here as they, rightly, do not appear in __all__ all_unpublished = ( self._UNPUBLISHED + og._HIDDEN # noqa: PLW0212 + ogc._HIDDEN # noqa: PLW0212 + [module_object for module_object in dir(autonode) if not module_object.startswith("_")] + [module_object for module_object in dir(ogty) if not module_object.startswith("_")] ) _check_module_api_consistency(og, all_unpublished) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents( og, [ # noqa: PLW0212 "attribute_value_as_usd", "AttributeDataValueHelper", "AttributeValueHelper", "autonode", "Bundle", "BundleContainer", "BundleContents", "cmds", "Controller", "data_shape_from_type", "Database", "DataView", "DataWrapper", "Device", "Dtype", "DynamicAttributeAccess", "DynamicAttributeInterface", "ExtensionInformation", "get_global_orchestration_graphs", "get_graph_settings", "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", ], self._UNPUBLISHED, only_expected_allowed=False, )
3,295
Python
39.195121
114
0.527769
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/__init__.py
""" Imports from the test module are only recommended for use in OmniGraph tests. 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.tests as ogts dir(ogts) help(ogts.load_test_file) """ # fmt: off # isort: off # Exported interface for testing utilities that are of general use. # (Others exist but are legacy or specific to one use only and imported directly) from ._unittest_support import construct_test_class from ._unittest_support import OmniGraphTestConfiguration from .omnigraph_test_utils import OmniGraphTestCase from .omnigraph_test_utils import OmniGraphTestCaseNoClear from .omnigraph_test_utils import SettingContext from .omnigraph_test_utils import TestContextManager from .expected_error import ExpectedError from .omnigraph_test_utils import create_cone from .omnigraph_test_utils import create_cube from .omnigraph_test_utils import create_grid_mesh from .omnigraph_test_utils import create_input_and_output_grid_meshes from .omnigraph_test_utils import create_sphere from .omnigraph_test_utils import DataTypeHelper from .omnigraph_test_utils import dump_graph from .omnigraph_test_utils import insert_sublayer from .omnigraph_test_utils import load_test_file from .omnigraph_test_utils import test_case_class from .omnigraph_test_utils import verify_connections from .omnigraph_test_utils import verify_node_existence from .omnigraph_test_utils import verify_values from .validation import validate_abi_interface scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases""" # ============================================================================================================== # _____ ______ _____ _____ ______ _____ _______ ______ _____ # | __ \ | ____|| __ \ | __ \ | ____|/ ____| /\ |__ __|| ____|| __ \ # | | | || |__ | |__) || |__) || |__ | | / \ | | | |__ | | | | # | | | || __| | ___/ | _ / | __| | | / /\ \ | | | __| | | | | # | |__| || |____ | | | | \ \ | |____| |____ / ____ \ | | | |____ | |__| | # |_____/ |______||_| |_| \_\|______|\_____|/_/ \_\|_| |______||_____/ # # isort: on # fmt: on
2,342
Python
42.388888
119
0.595218
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_bundle_dirty_id.py
import omni.graph.core as og import omni.graph.core.tests as ogt class BundleTestSetup(ogt.OmniGraphTestCase): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.graph = og.Controller.create_graph("/graph") self.context = self.graph.get_default_graph_context() self.factory = og.IBundleFactory.create() self.assertTrue(self.factory is not None) self.dirty = og._og_unstable.IDirtyID2.create(self.context) # noqa: PLW0212 self.assertTrue(self.dirty is not None) # bundle paths self.bundle2Name = "bundle2" self.bundle3Name = "bundle3" self.attr1Name = "attr1" self.attr1Type = og.Type(og.BaseDataType.INT) self.attr2Name = "attr2" self.attr2Type = og.Type(og.BaseDataType.FLOAT) self.attr3Name = "attr3" self.attr3Type = og.Type(og.BaseDataType.INT, 1, 1) self.attr4Name = "attr4" self.attr4Type = og.Type(og.BaseDataType.INT, 2, 0) class TestBundleDirtyID(BundleTestSetup): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() async def test_create_bundle(self): bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.dirty.setup(bundle1, True) self.dirty.setup(bundle2, True) ids = self.dirty.get([bundle1, bundle2]) self.assertTrue(self.dirty.is_valid(ids[0])) self.assertTrue(self.dirty.is_valid(ids[1])) self.assertNotEqual(ids[0], ids[1]) async def test_create_attribute(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) ids0 = self.dirty.get([bundle]) bundle.create_attribute(self.attr1Name, self.attr1Type) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_create_child_bundle(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle.create_child_bundle(self.bundle2Name) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_remove_attribute(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) bundle.create_attribute(self.attr1Name, self.attr1Type) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle.remove_attribute(self.attr1Name) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_remove_child_bundles(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) bundle2 = bundle.create_child_bundle("child") ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle.remove_child_bundle(bundle2) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_clear_contents(self): """Test if clearing bundle results with new dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle.clear_contents() ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_copy_attribute(self): bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.dirty.setup(bundle1, True) self.dirty.setup(bundle2, True) attr1 = bundle1.create_attribute(self.attr1Name, self.attr1Type) ids0 = self.dirty.get([bundle2]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle2.copy_attribute(attr1) ids1 = self.dirty.get([bundle2]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_copy_child_bundle(self): """Test if CoW reference is resolved.""" bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.dirty.setup(bundle1, True) self.dirty.setup(bundle2, True) ids0 = self.dirty.get([bundle1]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle1.copy_child_bundle(self.bundle2Name, bundle2) ids1 = self.dirty.get([bundle1]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_copy_bundle(self): """Copying bundle creates a shallow copy - a reference. To obtain the dirty id the reference needs to be resolved""" bundle1 = self.factory.create_bundle(self.context, "bundle1") bundle2 = self.factory.create_bundle(self.context, "bundle2") self.dirty.setup(bundle1, True) self.dirty.setup(bundle2, True) ids0 = self.dirty.get([bundle1, bundle2]) self.assertNotEqual(ids0[0], ids0[1]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertTrue(self.dirty.is_valid(ids0[1])) bundle2.copy_bundle(bundle1) ids1 = self.dirty.get([bundle1, bundle2]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertTrue(self.dirty.is_valid(ids1[1])) self.assertEqual(ids1[0], ids1[1]) async def test_get_attribute_by_name(self): """Getting writable attribute data handle does not change dirty id. Only writing to an attribute triggers id to be changed.""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) bundle.create_attribute(self.attr1Name, self.attr1Type) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle.get_attribute_by_name(self.attr1Name) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_get_child_bundle_by_name(self): """Getting writable bundle handle does not change dirty id. Only creating/removing attributes and children triggers id to be changed.""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) bundle.create_child_bundle(self.bundle2Name) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) bundle.get_child_bundle_by_name(self.bundle2Name) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_get_simple_attribute_data(self): """Getting simple attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr1Name, self.attr1Type) attr.set(42) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertEqual(attr.as_read_only().get(), 42) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_get_array_attribute_data(self): """Getting array attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr3Name, self.attr3Type) attr.set([42]) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertEqual(attr.as_read_only().get()[0], 42) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def _get_array_rw_attribute_data(self, on_gpu): """Getting array attribute data for read-write""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr3Name, self.attr3Type) attr.set([42]) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) # no bump attr.as_read_only().get_array(on_gpu=on_gpu, get_for_write=False, reserved_element_count=1) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) # bump attr.get_array(on_gpu=on_gpu, get_for_write=True, reserved_element_count=1) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_get_array_attribute_data_cpu(self): await self._get_array_rw_attribute_data(False) async def test_get_array_attribute_data_gpu(self): await self._get_array_rw_attribute_data(True) async def test_resize_array_attribute(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr3Name, self.attr3Type) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) # no bump attr.size() ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) # bump attr.resize(10) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_get_tuple_attribute_data(self): """Getting array attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr4Name, self.attr4Type) attr.set([42, 24]) ids0 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertEqual(attr.as_read_only().get()[0], 42) self.assertEqual(attr.as_read_only().get()[1], 24) ids1 = self.dirty.get([bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_change_child_and_propagate_changes_to_parent(self): r""" bundle1 \_ child0 \_ child1 \_ child2 <-- create attribute Will propagate dirty id changes up to `bundle1` (child2 -> child1 -> child0 -> bundle1) """ bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) child0 = bundle.create_child_bundle("child0") child1 = child0.create_child_bundle("child1") child2 = child1.create_child_bundle("child2") ids0 = self.dirty.get([bundle, child0, child1]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertTrue(self.dirty.is_valid(ids0[1])) self.assertTrue(self.dirty.is_valid(ids0[2])) # creating attribute automatically bumps parent ids child2.create_attribute(self.attr1Name, self.attr1Type) ids1 = self.dirty.get([bundle, child0, child1]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertTrue(self.dirty.is_valid(ids1[1])) self.assertTrue(self.dirty.is_valid(ids1[2])) self.assertNotEqual(ids0[0], ids1[0]) self.assertNotEqual(ids0[1], ids1[1]) self.assertNotEqual(ids0[2], ids1[2]) class TestAttributeDirtyID(BundleTestSetup): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() async def test_create_attribute(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr1 = bundle.create_attribute(self.attr1Name, self.attr1Type) ids0 = self.dirty.get([attr1]) self.assertTrue(self.dirty.is_valid(ids0[0])) attr2 = bundle.create_attribute(self.attr2Name, self.attr2Type) ids1 = self.dirty.get([attr2]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_create_same_attribute(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr1 = bundle.create_attribute(self.attr1Name, self.attr1Type) ids0 = self.dirty.get([attr1]) self.assertTrue(self.dirty.is_valid(ids0[0])) attr2 = bundle.create_attribute(self.attr1Name, self.attr1Type) ids1 = self.dirty.get([attr2]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_create_same_attribute_new_size(self): bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) n = "attr" t = og.Type(og.BaseDataType.INT, 1, 1) attr = bundle.create_attribute(n, t, 100) ids0 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids0[0])) # same size does not bump dirty ids attr = bundle.create_attribute(n, t, 100) ids1 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) # new size bumps dirty ids attr = bundle.create_attribute(n, t, 10) ids1 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertNotEqual(ids0[0], ids1[0]) async def test_get_simple_attribute_data(self): """Getting simple attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr1Name, self.attr1Type) attr.set(42) ids0 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertEqual(attr.as_read_only().get(), 42) ids1 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_get_array_attribute_data(self): """Getting array attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr3Name, self.attr3Type) attr.set([42]) ids0 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertEqual(attr.as_read_only().get()[0], 42) ids1 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_get_tuple_attribute_data(self): """Getting tuple attribute data should not change dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr4Name, self.attr4Type) attr.set([42, 24]) ids0 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertEqual(attr.as_read_only().get()[0], 42) self.assertEqual(attr.as_read_only().get()[1], 24) ids1 = self.dirty.get([attr]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertEqual(ids0[0], ids1[0]) async def test_set_simple_attribute_data(self): """Setting simple attribute data changes dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr1Name, self.attr1Type) ids0 = self.dirty.get([attr, bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertTrue(self.dirty.is_valid(ids0[1])) attr.set(42) ids1 = self.dirty.get([attr, bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertTrue(self.dirty.is_valid(ids1[1])) self.assertNotEqual(ids0[0], ids1[0]) self.assertNotEqual(ids0[1], ids1[1]) async def test_set_array_attribute_data(self): """Setting array attribute data changes dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr3Name, self.attr3Type) ids0 = self.dirty.get([attr, bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertTrue(self.dirty.is_valid(ids0[1])) attr.set([42]) ids1 = self.dirty.get([attr, bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertTrue(self.dirty.is_valid(ids1[1])) self.assertNotEqual(ids0[0], ids1[0]) self.assertNotEqual(ids0[1], ids1[1]) async def test_set_tuple_attribute_data(self): """Setting tuple attribute data changes dirty id""" bundle = self.factory.create_bundle(self.context, "bundle") self.dirty.setup(bundle, True) attr = bundle.create_attribute(self.attr4Name, self.attr4Type) ids0 = self.dirty.get([attr, bundle]) self.assertTrue(self.dirty.is_valid(ids0[0])) self.assertTrue(self.dirty.is_valid(ids0[1])) attr.set([42, 24]) ids1 = self.dirty.get([attr, bundle]) self.assertTrue(self.dirty.is_valid(ids1[0])) self.assertTrue(self.dirty.is_valid(ids1[1])) self.assertNotEqual(ids0[0], ids1[0]) self.assertNotEqual(ids0[1], ids1[1])
18,506
Python
38.62955
99
0.635199
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_unittest_support.py
"""Tests that exercise the capabilities provided for OmniGraph unit testing""" from contextlib import asynccontextmanager, contextmanager import carb import omni.graph.core.tests as ogts import omni.graph.tools as ogt import omni.kit.test import omni.usd # Name of a fake setting that will be used for testing TEST_SETTING = "/not/a/setting" # ============================================================================================================== class TestOmniGraphTestFeatures(omni.kit.test.AsyncTestCase): """Run targeted tests on the test helper functions and classes directly, not as part of the test definition""" async def test_configuration_class(self): """Tests the functionality of customized OmniGraphTestConfiguration objects""" settings = carb.settings.get_settings() with ogts.OmniGraphTestConfiguration(settings={TEST_SETTING: True}): self.assertEqual(settings.get(TEST_SETTING), True) self.assertEqual(settings.get(TEST_SETTING), None) # -------------------------------------------------------------------------------------------------------------- CONTEXT_FLAG = 0 async def test_custom_contexts(self): """Tests the functionality of providing my own custom contexts via the contextmanager decorator""" @contextmanager def context_add_1(): TestOmniGraphTestFeatures.CONTEXT_FLAG = TestOmniGraphTestFeatures.CONTEXT_FLAG + 1 try: yield True finally: TestOmniGraphTestFeatures.CONTEXT_FLAG = TestOmniGraphTestFeatures.CONTEXT_FLAG - 1 @asynccontextmanager async def async_context_add_10(): TestOmniGraphTestFeatures.CONTEXT_FLAG = TestOmniGraphTestFeatures.CONTEXT_FLAG + 10 try: yield True finally: TestOmniGraphTestFeatures.CONTEXT_FLAG = TestOmniGraphTestFeatures.CONTEXT_FLAG - 10 my_configuration = ogts.OmniGraphTestConfiguration( contexts=[context_add_1], async_contexts=[async_context_add_10] ) self.assertEqual(TestOmniGraphTestFeatures.CONTEXT_FLAG, 0) with my_configuration: self.assertEqual(TestOmniGraphTestFeatures.CONTEXT_FLAG, 1) self.assertEqual(TestOmniGraphTestFeatures.CONTEXT_FLAG, 0) async with my_configuration: self.assertEqual(TestOmniGraphTestFeatures.CONTEXT_FLAG, 11) self.assertEqual(TestOmniGraphTestFeatures.CONTEXT_FLAG, 0) # -------------------------------------------------------------------------------------------------------------- async def test_construct_test_class(self): """Tests the ability to create a base class using the construct_test_class() function""" # Test the deprecated keyword message = "I am deprecated" deprecated_class = ogts.construct_test_class(deprecated=message) self.assertTrue(omni.kit.test.AsyncTestCase in deprecated_class.__bases__) with ogt.DeprecateMessage.NoLogging(): instance = deprecated_class() await instance.setUp() messages_logged = ogt.DeprecateMessage.messages_logged() self.assertTrue(message in messages_logged, f"'{message}' not in {messages_logged}") # Test the base_class keyword class BaseTestClass(omni.kit.test.AsyncTestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.i_exist = True derived_class = ogts.construct_test_class(base_class=BaseTestClass) instance = derived_class() self.assertTrue(hasattr(instance, "i_exist") and instance.i_exist, f"No 'i_exist' in {dir(instance)}") self.assertTrue(isinstance(instance, BaseTestClass)) # Test the configure keyword configuration = ogts.OmniGraphTestConfiguration(settings={TEST_SETTING: True}) configured_class = ogts.construct_test_class(configuration=configuration) instance = configured_class() self.assertEqual(type(configuration), type(instance._OmniGraphCustomTestCase__configuration)) # noqa PLW0212 with self.assertRaises(TypeError): _ = ogts.construct_test_class(configuration=3) # Test the extensions_enabled keyword test_extension = "omni.graph.scriptnode" manager = omni.kit.app.get_app().get_extension_manager() was_enabled = manager.is_extension_enabled(test_extension) manager.set_extension_enabled_immediate(test_extension, False) configuration = ogts.OmniGraphTestConfiguration(extensions_enabled=[test_extension]) with configuration: self.assertTrue(manager.is_extension_enabled(test_extension)) manager.set_extension_enabled_immediate(test_extension, was_enabled) # Test the extensions_disabled keyword manager.set_extension_enabled_immediate(test_extension, True) configuration = ogts.OmniGraphTestConfiguration(extensions_disabled=[test_extension]) with configuration: self.assertFalse(manager.is_extension_enabled(test_extension)) manager.set_extension_enabled_immediate(test_extension, was_enabled) # ============================================================================================================== class TestStandardConfiguration(ogts.OmniGraphTestCase): """Run tests using the standard OmniGraph test configuration""" async def setUp(self): await super().setUp() async def tearDown(self): await super().tearDown() async def test_settings(self): """Test that the standard settings are applied by the test case""" # ============================================================================================================== class TestCustomSetUp(omni.kit.test.AsyncTestCase): """Run tests using an OmniGraphTestConfiguration customization using the Kit base class""" async def test_configuration(self): with ogts.OmniGraphTestConfiguration(settings={TEST_SETTING: True}): self.assertTrue(carb.settings.get_settings().get(TEST_SETTING)) # ============================================================================================================== MyTestClass = ogts.construct_test_class(settings={TEST_SETTING: True}) class TestManualConfiguration(MyTestClass): """Run tests using a custom created base test class""" async def test_constructed_base_class(self): self.assertTrue(carb.settings.get_settings().get(TEST_SETTING)) # ============================================================================================================== class TestCustomBaseClass(MyTestClass): """Run tests using a custom created base test class derived from another custom base class""" async def test_constructed_derived_class(self): with self.assertRaises(TypeError): MyDerivedTestClass = ogts.construct_test_class(base_class=MyTestClass) # noqa F841 # ============================================================================================================== class TestOverrideSetUp(ogts.OmniGraphTestCase): """Run tests using a customization that is based on the standard configuration""" async def test_configuration(self): with ogts.OmniGraphTestConfiguration(settings={TEST_SETTING: True}): self.assertTrue(carb.settings.get_settings().get(TEST_SETTING))
7,480
Python
45.465838
117
0.61484
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/_unittest_support.py
"""Support for creating unittest style test cases that use OmniGraph components. Note the leading underscore in the file name, indicating that it should not be imported directly. Instead use this: .. code-block:: python import omni.graph.core.tests as ogts There are three primary workflows for setting up unit test case classes that manage OmniGraph state. If your test case uses OmniGraph and just wants a standard configuration while running then you can use the predefined test case base class :py:class:`omni.graph.core.tests.OmniGraphTestCase`. .. code-block:: python import omni.graph.core.tests as ogts class TestMyStuff(ogts.OmniGraphTestCase): async def test_my_stuff(self): pass # My stuff always works If instead you wish to make use of only a subset of the various OmniGraph configuration values or use your own test base class then you can use :py:class:`omni.graph.core.tests.OmniGraphTestConfiguration` to build up a set of temporary conditions in force while the test runs, such as using an empty scene, defining settings, etc. .. code-block:: python import omni.graph.core.tests as ogts class TestMyStuff(omni.kit.test.AsyncTestCase): async def test_my_stuff(self): with ogts.OmniGraphTestConfiguration(clear_on_start=False): pass # My stuff always works You can also use the test case class constructor to define your own base class that can be used in multiple locations: .. code-block:: python import omni.graph.core.tests as ogts MyDebugTestClass = ogts.test_case_class(clear_on_finish=False, clear_on_start=False) class TestMyStuff(MyDebugTestClass): async def test_my_stuff(self): pass # My stuff always works """ from __future__ import annotations import asyncio import inspect from contextlib import AsyncExitStack, ExitStack, asynccontextmanager, contextmanager import omni.graph.core as og import omni.graph.tools as ogt import omni.kit import omni.usd # ============================================================================================================== class OmniGraphTestConfiguration: """Class to manage testing configuration parameters as a context manager that brackets a test run. You can either use it around a single test to modify configuration for just that test: .. code-block:: python import omni.graph.core.tests as ogts class TestRun(ogts.OmniGraphTestCase): '''By default the tests in this class will clear the scene on start and finish of the test''' async def test_without_clearing(self): async with ogts.OmniGraphTestConfiguration(clear_on_start=False): run_my_test() # Before this particular test the scene will not be cleared before starting See :py:func:`construct_test_class` for a way of applying it to every test in the test case. .. code-block:: python class TestRun(ogts.construct_test_class(clear_on_start=True)): async def test_without_clearing(self): run_my_test() If you can't change your base class you can still use it by adding it to the test case setUp/tearDown .. code-block:: python class TestRun(omni.kit.test.AsyncTestCase): async def setUp(self): self.configuration = ogts.OmniGraphTestConfiguration(clear_on_start=True) await self.configuration.__enter__() async def tearDown(self): await self.configuration.__exit__() async def test_without_clearing(self): run_my_test() It also has the ability to include user-defined contexts as part of the test configuration, which will be unwound in the order added using the standard *contextlib.{A}ExitStack()* functionality. .. code-block:: python @contextmanager def my_context(): resource = acquire_my_resource() try: yield 1 finally: release_my_resource(resource) @asynccontextmanager async def my_async_context(): resource = await acquire_my_async_resource() try: yield 1 finally: await release_my_async_resource(resource) my_configuration = OmniGraphTestConfiguration(contexts=[my_context], async_contexts=[my_async_context]) MyCustomClass = ogts.construct_test_class(configuration=my_configuration) class TestRun(MyCustomClass): async def test_without_clearing(self): run_my_test() """ def __init__(self, **kwargs): """Construct the stack objects that will hold the test contexts Args: clear_on_start (bool=False): Clear the scene before the test starts clear_on_finish (bool=False): Clear the scene after the test ends settings (dict=None): Dictionary of settingName:value to set while the test runs and restore after contexts (list=None): List of contextmanager functions or decorated classes to wrap the test runs async_contexts (list=None): List of asynccontextmanager functions or decorated classes to wrap the test runs extensions_enabled (list=None): List of the names of extensions to temporarily enable for the test extensions_disabled (list=None): List of the names of extensions to temporarily disable for the test Note: Be careful when using the extensions_{en,dis}abled options to ensure that you do not inadvertently force a hot reload of the extension containing the test. """ self.stack = ExitStack() self.async_stack = AsyncExitStack() self.__kwargs = dict(kwargs) # -------------------------------------------------------------------------------------------------------------- def __set_up_stack(self): """Define the parts of the ExitStack requested by the current keyword args""" @contextmanager def __enable_extensions(extensions: list[str]): manager = omni.kit.app.get_app().get_extension_manager() try: for name in extensions: manager.set_extension_enabled_immediate(name, True) yield True finally: pass @contextmanager def __disable_extensions(extensions: list[str]): manager = omni.kit.app.get_app().get_extension_manager() try: for name in extensions: manager.set_extension_enabled_immediate(name, False) yield True finally: pass for key, value in self.__kwargs.items(): if key == "settings": for setting, temporary_value in value.items(): self.stack.enter_context(og.Settings.temporary(setting, temporary_value)) elif key == "extensions_enabled": self.stack.enter_context(__enable_extensions(value)) elif key == "extensions_disabled": self.stack.enter_context(__disable_extensions(value)) elif key == "contexts": if not isinstance(value, list): value = [value] for context in value: self.stack.enter_context(context()) # -------------------------------------------------------------------------------------------------------------- async def __set_up_async_stack(self): """Define the parts of the AsyncExitStack requested by the current keyword args""" @asynccontextmanager async def __clear_scene_on_enter(): try: yield await omni.usd.get_context().new_stage_async() finally: pass @asynccontextmanager async def __clear_scene_on_exit(): try: yield None finally: await omni.usd.get_context().new_stage_async() for key, value in self.__kwargs.items(): if key == "clear_on_start" and value: await self.async_stack.enter_async_context(__clear_scene_on_enter()) if key == "clear_on_finish" and value: await self.async_stack.enter_async_context(__clear_scene_on_exit()) if key == "async_contexts": if not isinstance(value, list): value = [value] for context in value: await self.async_stack.enter_async_context(context()) # -------------------------------------------------------------------------------------------------------------- def __enter__(self): """When used as a context manager this class calls this at the start of a 'with' clause""" self.__set_up_stack() asyncio.ensure_future(self.__set_up_async_stack()) self.stack.__enter__() asyncio.ensure_future(self.async_stack.__aenter__()) def __exit__(self, exc_type=None, exc_value=None, exc_tb=None): """When used as a context manager this class calls this at the end of a 'with' clause""" self.stack.__exit__(exc_type, exc_value, exc_tb) asyncio.ensure_future(self.async_stack.__aexit__(exc_type, exc_value, exc_tb)) # -------------------------------------------------------------------------------------------------------------- async def __aenter__(self): """When used as an async context manager this class calls this at the start of a 'with' clause""" self.__set_up_stack() await self.__set_up_async_stack() self.stack.__enter__() await self.async_stack.__aenter__() async def __aexit__(self, exc_type=None, exc_value=None, exc_tb=None): """When used as an async context manager this class calls this at the end of a 'with' clause""" self.stack.__exit__(exc_type, exc_value, exc_tb) await self.async_stack.__aexit__(exc_type, exc_value, exc_tb) # ============================================================================================================== def construct_test_class(**kwargs): """Construct a new test case base class that configures the test in a predictable way. You can use the same parameters as :py:class:`OmniGraphTestConfiguration` to configure your test class, or you can construct one and pass it in as an argument Args: configuration (OmniGraphTestConfiguration): Full configuration definition deprecated (str | tuple[str, DeprecationLevel]): Used when this instantiation of the class has been deprecated base_class (object): Alternative base class for the test case, defaults to omni.kit.test.AsyncTestCase Other arguments can be seen in the parameters to :py:func:`OmniGraphTestConfiguration.setUp` Raises: TypeError if a base class was specified that is also a constructed class """ # Check to see if an alternative base class was passed in base_class = kwargs.get("base_class", omni.kit.test.AsyncTestCase) # Issue the deprecation message if specified, but continue on deprecation = kwargs.get("deprecated", None) try: configuration = kwargs["configuration"] if not isinstance(configuration, OmniGraphTestConfiguration): raise TypeError(f"configuration only accepts type OmniGraphTestConfiguration, not {type(configuration)}") except KeyError: configuration = OmniGraphTestConfiguration(**kwargs) # -------------------------------------------------------------------------------------------------------------- # Construct the customized test case base class object using the temporary setting and base class information class OmniGraphCustomTestCase(base_class): """A custom constructed test case base class that performs the prescribed setUp and tearDown actions.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__configuration = configuration self.__deprecation = deprecation async def setUp(self): """Set up the test by saving and then setting up all of the action contexts""" # Start with no test failures registered og.set_test_failure(False) if inspect.iscoroutinefunction(super().setUp): await super().setUp() else: super().setUp() if self.__deprecation is not None: if isinstance(self.__deprecation, tuple): if len(self.__deprecation) != 2: raise ValueError( "deprecation argument can only be a message or (message, level) pair" f" - saw {self.__deprecation}" ) ogt.DeprecateMessage.deprecated(self.__deprecation[0], self.__deprecation[1]) else: ogt.DeprecateMessage.deprecated(self.__deprecation) await self.__configuration.__aenter__() # noqa PLC2801 async def tearDown(self): """Complete the test by tearing down all of the action contexts""" await self.__configuration.__aexit__() if inspect.iscoroutinefunction(super().setUp): await super().tearDown() else: super().tearDown() # Recursive class definition is more complicated and can be done other ways if base_class.__name__ == "OmniGraphCustomTestCase": raise TypeError( "Recursive class definition is not supported (construct_test_class(base_class=construct_test_class(...)))" ) # Return the constructed class definition return OmniGraphCustomTestCase
13,880
Python
43.777419
120
0.596974
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_node_type_forwarding.py
"""Tests that exercise the INodeTypeForwarding interface""" import omni.graph.core._unstable as ogu import omni.graph.core.tests as ogts import omni.kit.test import omni.usd # ============================================================================================================== class TestNodeTypeForwarding(omni.kit.test.AsyncTestCase): async def test_bindings(self): """Tests that the bindings for the ABI operate as expected""" interface_class = ogu.INodeTypeForwarding ogts.validate_abi_interface( interface_class, instance_methods=[ "define_forward", "remove_forward", "remove_forwarded_type", ], static_methods=[ "find_forward", "get_forwarding", ], properties=["forward_count"], ) get_interface = ogu.get_node_type_forwarding_interface self.assertIsNotNone(get_interface) interface = get_interface() self.assertIsNotNone(interface) self.assertTrue(isinstance(interface, ogu.INodeTypeForwarding)) try: # Try defining a simple forward original_forwarding = interface.forward_count replacement = ("ReplacementNodeType", 1, "omni.test.extension") original = ("ForwardedNodeType", 2) self.assertTrue(interface.define_forward(*original, *replacement)) self.assertEqual(original_forwarding + 1, interface.forward_count) all_forwarding = interface.get_forwarding() self.assertEqual(all_forwarding[original], replacement) found_forward = interface.find_forward(*original) self.assertEqual(found_forward, replacement) # Define a second forward secondary_replacement = ("SecondNodeType", 4, "omni.test.extension") secondary = ("SomeOtherNodeType", 2) self.assertTrue(interface.define_forward(*secondary, *secondary_replacement)) self.assertEqual(original_forwarding + 2, interface.forward_count) all_forwarding = interface.get_forwarding() self.assertEqual(all_forwarding[original], replacement) self.assertEqual(all_forwarding[secondary], secondary_replacement) # Define a chained forward ("ChainedNodeType", 1) -> ("ReplacementNodeType", 1) -> ("ForwardedNodeType", 2) chained_replacement = ("ChainedNodeType", 1, "omni.test.extension") chained = (replacement[0], replacement[1]) self.assertTrue(interface.define_forward(*chained, *chained_replacement)) found_forward = interface.find_forward(*chained) self.assertEqual(found_forward, chained_replacement) found_forward = interface.find_forward(*original) self.assertEqual(found_forward, chained_replacement) # Define a few forwarding for the same node type at different versions # ("ReplacementNodeType", 1) -> ("ForwardedNodeType", 2, "omni.test.extension") # ("ReplacementNodeType", 3) -> ("BetterNodeType", 1, "omni.borg.extension") # ("ReplacementNodeType", 7) -> ("SecondaryNodeType", 4, "omni.test.extension") better_replacement = ("BetterNodeType", 4, "omni.borg.extension") latest_forward = (replacement[0], replacement[1] + 2) self.assertTrue(interface.define_forward(*latest_forward, *better_replacement)) prototype_forward = (replacement[0], replacement[1] + 6) self.assertTrue(interface.define_forward(*prototype_forward, *secondary_replacement)) # What the "replacement" forward is expected to map to for the version equal to the index of the list... expected_versions = [ chained_replacement, chained_replacement, better_replacement, better_replacement, better_replacement, better_replacement, secondary_replacement, secondary_replacement, secondary_replacement, ] for index, version_to_test in enumerate(expected_versions): self.assertEqual( version_to_test, interface.find_forward(replacement[0], index + 1), f"Checking {replacement[0]}-{index + 1} maps to {version_to_test}", ) # Ensure that attempting to look up a version earlier than the first forward returns nothing early_version = (replacement[0], 0) with self.assertRaises(ValueError): interface.find_forward(*early_version) # Attempt to define a circular forward, which should not be allowed circular = (chained_replacement[0], chained_replacement[1]) with ogts.ExpectedError(): self.assertFalse(interface.define_forward(*circular, *chained_replacement)) # Attempt to define a multiple-step circular forward, which should not be allowed # ("ChainedNodeType", 1) -> ("ReplacementNodeType", 1) -> ("ForwardedNodeType", 2) -> ("ChainedNodeType", 1) with ogts.ExpectedError(): self.assertFalse(interface.define_forward(*chained, original[0], original[1], "omni.test.extension")) # Attempt to redefine the same forward, which should not be allowed with ogts.ExpectedError(): self.assertFalse(interface.define_forward(*chained, *chained_replacement)) finally: # Remove all of the forwarding, in reverse order so that earlier failures clean up after themselves self.assertTrue(interface.remove_forward(*prototype_forward)) self.assertTrue(interface.remove_forward(*latest_forward)) self.assertTrue(interface.remove_forward(*chained)) self.assertTrue(interface.remove_forward(*secondary)) self.assertTrue(interface.remove_forward(*original)) self.assertEqual(original_forwarding, interface.forward_count)
6,172
Python
50.016529
120
0.613901
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_extension_unloads.py
""" Tests related to omnigraph state/api when extensions get unloaded. """ from contextlib import suppress import carb import omni.graph.core as og import omni.graph.core.tests as ogt import omni.kit.app import omni.kit.commands import omni.kit.test import omni.usd # ====================================================================== class TestExtensionUnloads(ogt.OmniGraphTestCase): # ----------------------------------------------------------------------- async def test_nodetype_when_extension_unloads(self): """Tests that nodes lose their node type when their extension unloads""" node_type = "omni.graph.examples.cpp.Simple" examples_cpp_extension = "omni.graph.examples.cpp" manager = omni.kit.app.get_app_interface().get_extension_manager() # If the extension is not found then the test cannot run examples_cpp_extension_id = None with suppress(Exception): examples_cpp_extension_id = manager.get_extension_id_by_module(examples_cpp_extension) if not examples_cpp_extension_id: carb.log_warn( f"test_nodetype_when_extension_unloads cannot run since {examples_cpp_extension} was not found" ) return examples_cpp_enabled = manager.is_extension_enabled(examples_cpp_extension) try: manager.set_extension_enabled_immediate(examples_cpp_extension, True) # create a graph with a node from the extension keys = og.Controller.Keys controller1 = og.Controller() (_, nodes, _, _) = controller1.edit( "/World/Graph", { keys.CREATE_NODES: [ ("Node", node_type), ], }, ) self.assertTrue(nodes[0].get_node_type().is_valid()) self.assertEquals(nodes[0].get_node_type().get_node_type(), node_type) # disable the extension, and validate the node type changes to a default type # the type is still valid, but is a default type manager.set_extension_enabled_immediate(examples_cpp_extension, False) self.assertTrue(nodes[0].get_node_type().is_valid()) self.assertEquals(nodes[0].get_node_type().get_node_type(), None) # re-enable the extension and validate the node type is restored manager.set_extension_enabled_immediate(examples_cpp_extension, True) self.assertTrue(nodes[0].get_node_type().is_valid()) self.assertEquals(nodes[0].get_node_type().get_node_type(), node_type) finally: manager.set_extension_enabled_immediate(examples_cpp_extension, examples_cpp_enabled)
2,765
Python
40.283581
111
0.594575
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/expected_error.py
# -------------------------------------------------------------------------------------------------------------- class ExpectedError: """ Helper class used to prefix any pending error messages with [Expected Error] stdoutFailPatterns.exclude (defined in extension.toml) will cause these errors to be ignored when running tests. Note that it will prepend only the first error. Usage: with ExpectedError(): function_that_produced_error_output() """ def __enter__(self): # Preflush any output, otherwise it may be appended to the next statement. print("", flush=True) # Output the prefix string without a newline so that the error to be ignored will appear on # the same line. We do NOT want to flush this because that could allow output from another thread # to appear between the prefix and the error message. print("[Ignore this error/warning] ", end="", flush=False) def __exit__(self, exit_type, value, traceback): # Print a newline, to avoid actual errors being ignored. print("", flush=True)
1,122
Python
39.107141
112
0.600713
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_bundle_hierarchy.py
import omni.graph.core as og import omni.graph.core.tests as ogt class BundleTestSetup(ogt.OmniGraphTestCase): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.graph = og.Controller.create_graph("/graph") self.context = self.graph.get_default_graph_context() self.factory = og.IBundleFactory.create() self.assertTrue(self.factory is not None) # bundle paths self.bundle1Name = "bundle1" self.bundle2Name = "bundle2" self.bundle3Name = "bundle3" self.bundle4Name = "bundle4" # attribute names self.attr1Name = "attr1" self.attr2Name = "attr2" # attribute types self.attr1Type = og.Type(og.BaseDataType.INT) self.attr2Type = og.Type(og.BaseDataType.FLOAT) self.bundle1 = self.factory.create_bundle(self.context, self.bundle1Name) self.assertTrue(self.bundle1.valid) # ------------------------------------------------------------------ # # FOLLOWING TESTS ARE IMPLEMENTATION DETAILS AND MUST NOT BE USED! # # ------------------------------------------------------------------ # class TestBundleHierarchyCleanup(BundleTestSetup): """This tests exercises cleanup of internals of the bundles.""" async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() def test_recursive_child_bundle_removal(self): # create hierarchy of bundles b0 = self.bundle1 b1 = b0.create_child_bundle(self.bundle2Name) b2 = b1.create_child_bundle(self.bundle3Name) self.assertTrue(b0) self.assertTrue(b1) self.assertTrue(b2) p0 = f"{self.bundle1Name}" p1 = f"{self.bundle1Name}/{self.bundle2Name}" p2 = f"{self.bundle1Name}/{self.bundle2Name}/{self.bundle3Name}" self.assertTrue(self.factory.get_const_bundle_from_path(self.context, p0)) self.assertTrue(self.factory.get_const_bundle_from_path(self.context, p1)) self.assertTrue(self.factory.get_const_bundle_from_path(self.context, p2)) b0.clear_contents() # p0 is not removed, only the descendants will be gone self.assertTrue(self.factory.get_const_bundle_from_path(self.context, p0)) self.assertFalse(self.factory.get_const_bundle_from_path(self.context, p1)) self.assertFalse(self.factory.get_const_bundle_from_path(self.context, p2)) def test_recursive_child_bundle_metadata_removal(self): b0 = self.bundle1 b1 = b0.create_child_bundle(self.bundle2Name) # create bundle metadata b0.create_bundle_metadata(self.attr1Name, self.attr1Type) b1.create_bundle_metadata(self.attr1Name, self.attr1Type) # create bundle attributes b0.create_attribute(self.attr1Name, self.attr1Type) b1.create_attribute(self.attr1Name, self.attr1Type) # create attribute metadata b0.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) b1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) # TODO: Investigate why passing c-string does not work. The conversion from c-string to PathC produces different ids. p0 = f"{self.bundle1Name}/__metadata__bundle__" p1 = f"{self.bundle1Name}/__metadata__bundle__/{self.attr1Name}" p2 = f"{self.bundle1Name}/{self.bundle2Name}/__metadata__bundle__" p3 = f"{self.bundle1Name}/{self.bundle2Name}/__metadata__bundle__/{self.attr1Name}" get = self.factory.get_const_bundle_from_path self.assertTrue(get(self.context, p0)) self.assertTrue(get(self.context, p1)) self.assertTrue(get(self.context, p2)) self.assertTrue(get(self.context, p3)) b0.clear_contents() self.assertFalse(get(self.context, p0)) self.assertFalse(get(self.context, p1)) self.assertFalse(get(self.context, p2)) self.assertFalse(get(self.context, p3)) def test_recursive_child_remove_with_cow(self): child_names = [self.bundle2Name, self.bundle3Name] b0 = self.bundle1 children = b0.create_child_bundles(child_names) # Copy-on-Write child bundles b1 = self.factory.create_bundle(self.context, self.bundle4Name) b1.copy_child_bundles(child_names, children) # check content get = self.factory.get_const_bundle_from_path # original bundle p0 = f"{self.bundle1Name}" p1 = f"{self.bundle1Name}/{self.bundle2Name}" p2 = f"{self.bundle1Name}/{self.bundle3Name}" self.assertTrue(get(self.context, p0)) self.assertTrue(get(self.context, p1)) self.assertTrue(get(self.context, p2)) # copied children p0 = f"{self.bundle4Name}" p1 = f"{self.bundle4Name}/{self.bundle2Name}" p2 = f"{self.bundle4Name}/{self.bundle3Name}" self.assertTrue(get(self.context, p0)) self.assertTrue(get(self.context, p1)) self.assertTrue(get(self.context, p2)) # remove shallow copies, but not the original location b1.clear_contents() # shallow children are gone self.assertTrue(get(self.context, p0)) self.assertFalse(get(self.context, p1)) self.assertFalse(get(self.context, p2)) # but original location stays intact p0 = f"{self.bundle1Name}" p1 = f"{self.bundle1Name}/{self.bundle2Name}" p2 = f"{self.bundle1Name}/{self.bundle3Name}" self.assertTrue(get(self.context, p0)) self.assertTrue(get(self.context, p1)) self.assertTrue(get(self.context, p2))
5,734
Python
36.980132
125
0.637077
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/validation.py
"""Support for validation of content""" import inspect from enum import Enum # ============================================================================================================== class _FunctionType(Enum): """Enumeration to make an easy tag type for function type definitions""" FUNCTION = "function" """Type is an untethered function""" STATIC = "staticmethod" """Type is a static method of a class""" CLASS = "classmethod" """Type is a class method (with cls) of a class""" INSTANCE = "instancemethod" """Type is an instance method (with self) of a class""" NOT_A_FUNCTION = "unknown" """Type is not a recognized function type""" # ============================================================================================================== def _get_pybind_function_type(func: any) -> _FunctionType: """Check to see if the object is a function type of some kind. The way to check if a function from a pybind interface is static or not is quite different from how you would check regular functions. The regular methods are instancemethod types, as expected, but the static methods are classified as builtin methods. The parent class is always PyCapsule so the assumption has to be made that anything passed in here already belongs to the interface being tested. Args: func (any): The object to inspect Returns: _FunctionType|None: The type of function @p func is or None if it is not a function """ if not inspect.isroutine(func): return None function_type = type(func) if func.__name__ == func.__qualname__ or ".<locals>" in func.__qualname__: return _FunctionType.FUNCTION if function_type.__name__ == "builtin_function_or_method": return _FunctionType.STATIC if function_type.__name__ == "instancemethod": return _FunctionType.INSTANCE return _FunctionType.CLASS # ============================================================================================================== def validate_abi_interface( interface: any, instance_methods: list[str] = None, static_methods: list[str] = None, class_methods: list[str] = None, properties: list[str] = None, constants: list[tuple[str, any]] = None, ): """Validate an ABI interface's expected contents Args: interface (any): The interface object to validate instance_methods (list[str]): Names of interface members expected to be regular object functions static_methods (list[str]): Names of interface members expected to be static object functions class_methods (list[str]): Names of interface members expected to be class level functions properties (list[str]): Names of interface members expected to be object properties constants (list[str]): Names and types of interface members expected to be constant object values Raises: ValueError: if the interface was not consistent with the expected contents """ # Convert members to forms easier to compare actual_members = {function_name for function_name in dir(interface) if not function_name.startswith("_")} expected_instance_method_names = set(instance_methods or []) expected_static_method_names = set(static_methods or []) expected_class_method_names = set(class_methods or []) expected_property_names = set(properties or []) expected_constant_definitions = set(constants or []) expected_members = ( expected_instance_method_names.union(expected_property_names) .union(expected_static_method_names) .union(expected_class_method_names) .union(name for (name, _) in expected_constant_definitions) ) unexpected = actual_members - expected_members not_found = expected_members - actual_members errors = [] if unexpected: errors.append(f"Unexpected interface members found - {unexpected}") if not_found: errors.append(f"Expected interface members not found - {not_found}") def _validate_function_type(function_names: list[str], expected_type: _FunctionType): """Check that a list of function names have the given type, adding to 'errors' if not""" for function_name in function_names: function = getattr(interface, function_name, None) if not callable(function): errors.append(f"Expected function {function_name} was not a callable function, it was {type(function)}") return function_type = _get_pybind_function_type(function) if function_type != expected_type: errors.append(f"Expected function {function_name} to be {expected_type.value}, it was {function_type}") # Validate the expected functions _validate_function_type(expected_instance_method_names, _FunctionType.INSTANCE) _validate_function_type(expected_class_method_names, _FunctionType.CLASS) _validate_function_type(expected_static_method_names, _FunctionType.STATIC) # Validate the expected properties for property_name in expected_property_names: property_member = getattr(interface, property_name, None) if not isinstance(property_member, property): errors.append(f"Expected property {property_name} was not a property, it was {type(property_member)}") # The constants are already known to be present, now their types must be checked for constant_name, constant_type in expected_constant_definitions: constant_member = getattr(interface, constant_name, None) if not isinstance(constant_member, constant_type): errors.append( f"Expected constant {constant_name} to be type {constant_type}, it was {type(constant_member)}" ) # Raise an exception if any errors were found if errors: formatted_errors = "\n ".join(errors) raise ValueError(f"Errors with interface {interface}\n {formatted_errors}")
5,999
Python
45.875
120
0.647441
omniverse-code/kit/exts/omni.graph/omni/graph/core/tests/test_bundles.py
import omni.core as oc import omni.graph.core as og import omni.graph.core.tests as ogt class BundleTestCase(ogt.OmniGraphTestCase): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.graph = og.Controller.create_graph("/graph") self.context = self.graph.get_default_graph_context() self.factory = og.IBundleFactory.create() self.assertTrue(self.factory is not None) # bundle paths self.bundle1Name = "bundle1" self.bundle2Name = "bundle2" self.bundle3Name = "bundle3" self.bundle4Name = "bundle4" self.bundle5Name = "bundle5" # attribute names self.attr1Name = "attr1" self.attr2Name = "attr2" self.attr3Name = "attr3" self.attr4Name = "attr4" # attribute types self.attr1Type = og.Type(og.BaseDataType.INT) self.attr2Type = og.Type(og.BaseDataType.FLOAT) self.attr3Type = og.Type(og.BaseDataType.DOUBLE, 1, 1) self.attr4Type = og.Type(og.BaseDataType.BOOL, 1, 1) self.bundle1 = self.factory.create_bundle(self.context, self.bundle1Name) self.assertTrue(self.bundle1.valid) async def test_create_bundle(self): # Check bundle1 does not have a parent bundle. parent1 = self.bundle1.get_parent_bundle() self.assertFalse(parent1.valid) # Check bundle path. self.assertEqual(self.bundle1.get_path(), self.bundle1Name) # Test state of attributes. self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(len(self.bundle1.get_attribute_names()), 0) self.assertEqual(len(self.bundle1.get_attribute_types()), 0) self.assertEqual(len(self.bundle1.get_attributes()), 0) # Test state of child bundles. self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(len(self.bundle1.get_child_bundles()), 0) async def test_create_child_bundle(self): # Create bundle hierarchy: bundle1/bundle2/bundle3. bundle2 = self.bundle1.create_child_bundle(self.bundle2Name) self.assertTrue(bundle2.valid) self.assertEqual(bundle2.get_name(), self.bundle2Name) # Check number of children. self.assertEqual(self.bundle1.get_child_bundle_count(), 1) self.assertEqual(bundle2.get_child_bundle_count(), 0) # leaf, no children self.assertEqual(len(self.bundle1.get_child_bundles()), 1) self.assertEqual(len(bundle2.get_child_bundles()), 0) async def test_create_child_bundles(self): # Create bundle hierarchy: bundle1/bundle2/bundle3. bundle_paths = [self.bundle2Name, self.bundle3Name] self.bundle1.create_child_bundles(bundle_paths) self.assertEqual(self.bundle1.get_child_bundle_count(), 2) async def test_bundle_parent(self): # Create hierarchy: bundle1/bundle2/bundle3. bundle2 = self.bundle1.create_child_bundle(self.bundle2Name) self.assertTrue(bundle2.valid) # Check children paths. self.assertEqual(bundle2.get_path(), "/".join([self.bundle1Name, self.bundle2Name])) # Check parents paths. bundle2_parent = bundle2.get_parent_bundle() self.assertTrue(bundle2_parent.valid) self.assertEqual(bundle2_parent.get_path(), self.bundle1.get_path()) async def test_remove_child_bundle(self): # Create hierarchy: bundle1/bundle2/bundle3. bundle2 = self.bundle1.create_child_bundle(self.bundle2Name) self.assertTrue(bundle2.valid) bundle3 = bundle2.create_child_bundle(self.bundle3Name) self.assertTrue(bundle3.valid) # We can only remove intermediate children, remove children from bundle1 must fail. # Disabled because of: OM-48629. Re-enable after OM-48828 is solved. # with ExpectedError(): # self.assertEqual(self.bundle1.remove_all_child_bundles(), 0) # remove bundle2 from bundle1 # bundle3 is not an intermediate child of bundle1. self.assertFalse(self.bundle1.remove_child_bundle(bundle3)) self.assertEqual(bundle2.remove_child_bundle(bundle3), oc.Result.SUCCESS) self.assertEqual(self.bundle1.remove_child_bundle(bundle2), oc.Result.SUCCESS) async def test_remove_child_bundles(self): # Create bundle hierarchy. bundle2 = self.bundle1.create_child_bundle(self.bundle2Name) self.assertTrue(bundle2.valid) bundle3 = self.bundle1.create_child_bundle(self.bundle3Name) self.assertTrue(bundle3.valid) # Get child bundles. bundles = self.bundle1.get_child_bundles() self.assertEqual(len(bundles), 2) # Remove all child bundles that are in the array. self.bundle1.remove_child_bundles(bundles) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) async def test_remove_child_bundles_by_name(self): _ = self.bundle1.create_child_bundle(self.bundle2Name) _ = self.bundle1.create_child_bundle(self.bundle3Name) _ = self.bundle1.create_child_bundle(self.bundle4Name) self.bundle1.remove_child_bundles_by_name([self.bundle2Name, self.bundle4Name]) self.assertEqual(self.bundle1.get_child_bundle_count(), 1) children = self.bundle1.get_child_bundles() self.assertEqual(len(children), 1) self.assertEqual(children[0].get_path(), "{}/{}".format(self.bundle1Name, self.bundle3Name)) async def test_copy_child_bundle(self): child = self.bundle1.create_child_bundle("child") new_bundle = self.factory.create_bundle(self.context, "new_bundle") new_bundle.copy_child_bundle(child) self.assertEqual(new_bundle.get_child_bundle_count(), 1) new_child = new_bundle.get_child_bundle_by_name("child") self.assertTrue(new_child.valid) async def test_copy_child_bundle_with_name(self): child = self.bundle1.create_child_bundle("child") new_bundle = self.factory.create_bundle(self.context, "new_bundle") new_bundle.copy_child_bundle(child, name="foo") self.assertEqual(new_bundle.get_child_bundle_count(), 1) new_child = new_bundle.get_child_bundle_by_name("child") self.assertFalse(new_child.valid) new_child = new_bundle.get_child_bundle_by_name("foo") self.assertTrue(new_child.valid) async def test_copy_child_bundles(self): children = self.bundle1.create_child_bundles(["childA", "childB"]) new_bundle = self.factory.create_bundle(self.context, "new_bundle") new_bundle.copy_child_bundles(children) self.assertEqual(new_bundle.get_child_bundle_count(), 2) new_children = new_bundle.get_child_bundles_by_name(["childA", "childB"]) self.assertEqual(len(new_children), 2) self.assertTrue(new_children[0].valid) self.assertTrue(new_children[1].valid) async def test_copy_child_bundles_with_names(self): children = self.bundle1.create_child_bundles(["childA", "childB"]) new_bundle = self.factory.create_bundle(self.context, "new_bundle") new_bundle.copy_child_bundles(children, names=["foo", "bar"]) self.assertEqual(new_bundle.get_child_bundle_count(), 2) new_children = new_bundle.get_child_bundles_by_name(["foo", "bar"]) self.assertEqual(len(new_children), 2) self.assertTrue(new_children[0].valid) self.assertTrue(new_children[1].valid) async def test_get_child_bundles_by_name(self): _ = self.bundle1.create_child_bundle(self.bundle2Name) _ = self.bundle1.create_child_bundle(self.bundle3Name) search = [self.bundle2Name, self.bundle3Name, self.bundle4Name] bundles = self.bundle1.get_child_bundles_by_name(search) self.assertTrue(bundles[0].valid) self.assertTrue(bundles[1].valid) self.assertFalse(bundles[2].valid) async def test_get_child_bundle_by_name(self): _ = self.bundle1.create_child_bundle(self.bundle2Name) _ = self.bundle1.create_child_bundle(self.bundle3Name) b2 = self.bundle1.get_child_bundle_by_name(self.bundle2Name) self.assertTrue(b2.valid) b3 = self.bundle1.get_child_bundle_by_name(self.bundle3Name) self.assertTrue(b3.valid) b4 = self.bundle1.get_child_bundle_by_name(self.bundle4Name) self.assertFalse(b4.valid) async def test_create_and_get_attribute(self): # Create each attribute individually. _ = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.assertEqual(self.bundle1.get_attribute_count(), 1) attr = self.bundle1.get_attribute_by_name(self.attr1Name) self.assertFalse(attr is None) self.assertEqual(attr.get_name(), self.attr1Name) async def test_create_and_get_attributes(self): # Create attributes by providing array of names and types. names = [self.attr1Name, self.attr2Name, self.attr3Name] types = [self.attr1Type, self.attr2Type, self.attr3Type] self.bundle1.create_attributes(names, types) self.assertEqual(self.bundle1.get_attribute_count(), 3) # Get all attributes. attrs = self.bundle1.get_attributes() self.assertEqual(len(attrs), 3) attrs = {x.get_name(): x for x in attrs if x.is_valid()} self.assertEqual(len(attrs), 3) self.assertTrue(self.attr1Name in attrs) self.assertTrue(self.attr2Name in attrs) self.assertTrue(self.attr3Name in attrs) # Find existing attributes. attrs_query = [self.attr1Name, self.attr3Name] attrs = self.bundle1.get_attributes_by_name(attrs_query) self.assertEqual(len(attrs), 2) attrs = {x.get_name(): x for x in attrs if x} self.assertEqual(len(attrs), 2) self.assertTrue(self.attr1Name in attrs) self.assertTrue(self.attr3Name in attrs) self.assertTrue(attrs[self.attr1Name]) self.assertTrue(attrs[self.attr3Name]) # Attempt to find not existing attributes. attrs_query = [self.attr4Name] attrs = self.bundle1.get_attributes_by_name(attrs_query) self.assertEqual(len(attrs), 1) attrs = {x.get_name(): x for x in attrs if x} self.assertEqual(len(attrs), 0) async def test_create_array_attribute(self): # Create array attribute. attr3 = self.bundle1.create_attribute(self.attr3Name, self.attr3Type, 1000) self.assertTrue(attr3) self.assertEqual(attr3.size(), 1000) attr3 = self.bundle1.create_attribute(self.attr3Name, self.attr3Type, 0) self.assertEqual(attr3.size(), 0) async def test_create_attribute_like(self): attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) # Create new bundle and create attribute like. bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) like_attr1 = bundle2.create_attribute_like(attr1) self.assertTrue(like_attr1) self.assertEqual(like_attr1.get_name(), self.attr1Name) self.assertEqual(like_attr1.get_type(), self.attr1Type) async def test_create_attributes_like(self): # Create attributes in bundle1. names = [self.attr1Name, self.attr2Name] types = [self.attr1Type, self.attr2Type] attrs = self.bundle1.create_attributes(names, types) # Create bundle2 and create attributes like those from bundle1. bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) like_attrs = bundle2.create_attributes_like(attrs) like_attrs = {x.get_name(): x for x in like_attrs if x} self.assertEqual(len(like_attrs), 2) self.assertTrue(self.attr1Name in like_attrs) self.assertTrue(self.attr2Name in like_attrs) async def test_remove_attributes(self): # Create attributes in bundle1. attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) attr2 = self.bundle1.create_attribute(self.attr2Name, self.attr2Type) # Remove one attribute from bundle. self.assertEqual(self.bundle1.remove_attribute(attr2), oc.Result.SUCCESS) self.assertEqual(self.bundle1.get_attribute_count(), 1) # Try to remove non existing attributes. bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) self.assertEqual(bundle2.remove_attributes([attr1, attr2]), 0) async def test_remove_attributes_by_name(self): _ = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) _ = self.bundle1.create_attribute(self.attr2Name, self.attr2Type) _ = self.bundle1.create_attribute(self.attr3Name, self.attr3Type) self.bundle1.remove_attributes_by_name([self.attr1Name, self.attr3Name]) self.assertEqual(self.bundle1.get_attribute_count(), 1) names = self.bundle1.get_attribute_names() self.assertEqual(len(names), 1) self.assertEqual(names[0], self.attr2Name) async def test_copy_attribute(self): attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.assertTrue(attr1) # Create bundle2 and copy attr1 from bundle1. bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) cpy_attr1 = bundle2.copy_attribute(attr1) self.assertTrue(cpy_attr1) self.assertEqual(cpy_attr1.get_type(), self.attr1Type) async def test_copy_attributes(self): # Create attributes. names = [self.attr1Name, self.attr2Name] types = [self.attr1Type, self.attr2Type] src_attrs1 = self.bundle1.create_attributes(names, types) names = [self.attr3Name, self.attr4Name] types = [self.attr3Type, self.attr4Type] bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) src_attrs2 = bundle2.create_attributes(names, types) # Create bundle3 and copy attributes from bundle1 and bundle2. bundle3 = self.factory.create_bundle(self.context, self.bundle3Name) src_attrs = src_attrs2 + src_attrs1 # reversed elements cpy_attrs = bundle3.copy_attributes(src_attrs) self.assertEqual(len(cpy_attrs), 4) # Check if attributes are valid. cpy_attrs = {x.get_name(): x for x in cpy_attrs if x} self.assertEqual(len(cpy_attrs), 4) # Get copied attributes by name. cpy_attr1 = bundle3.get_attribute_by_name(self.attr1Name) cpy_attr2 = bundle3.get_attribute_by_name(self.attr2Name) cpy_attr3 = bundle3.get_attribute_by_name(self.attr3Name) cpy_attr4 = bundle3.get_attribute_by_name(self.attr4Name) # Copied attributes must be valid. self.assertTrue(cpy_attr1.is_valid()) self.assertTrue(cpy_attr2.is_valid()) self.assertTrue(cpy_attr3.is_valid()) self.assertTrue(cpy_attr4.is_valid()) # Check copied attributes types. self.assertEqual(cpy_attr1.get_type(), self.attr1Type) self.assertEqual(cpy_attr2.get_type(), self.attr2Type) self.assertEqual(cpy_attr3.get_type(), self.attr3Type) self.assertEqual(cpy_attr4.get_type(), self.attr4Type) async def test_copy_attributes_override(self): # create double on bundle1 d_attr = self.bundle1.create_attribute(self.attr1Name, og.Type(og.BaseDataType.DOUBLE, 1, 1), 1000) self.assertEqual(d_attr.size(), 1000) # create bool on bundle2 bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) b_attr = bundle2.create_attribute(self.attr1Name, og.Type(og.BaseDataType.BOOL, 1, 1), 10) self.assertEqual(b_attr.size(), 10) # try copy double attr = bundle2.copy_attribute(d_attr, overwrite=False) self.assertFalse(attr.is_valid()) # try copy double attr = bundle2.copy_attribute(d_attr, overwrite=True) self.assertTrue(attr.is_valid()) self.assertEqual(attr.size(), 1000) self.assertEqual(attr.get_type().base_type, self.attr3Type.base_type) async def test_get_path(self): # Create hierarchy: bundle1/bundle2/bundle3. bundle1 = self.bundle1 bundle2 = bundle1.create_child_bundle(self.bundle2Name) self.assertTrue(bundle2.valid) async def test_create_private_attribute(self): # This functionality is an implementation detail and should not be abused bundle = self.factory.create_bundle(self.context, "bundle") attrib = bundle.create_attribute("__bundle__private__attrib", og.Type(og.BaseDataType.INT)) self.assertTrue(attrib.is_valid()) self.assertEqual(bundle.get_attribute_count(), 0) async def test_target_attribute_type(self): target_type = og.Type(og.BaseDataType.RELATIONSHIP, 1, 0, og.AttributeRole.TARGET) bundle = self.bundle1 bundle.create_attribute("targets", target_type) self.assertEqual(bundle.get_attribute_count(), 1) attrib = bundle.get_attributes()[0] self.assertTrue(attrib.is_valid()) self.assertEqual(attrib.get_type().base_type, og.BaseDataType.RELATIONSHIP) self.assertEqual(attrib.get_type().role, og.AttributeRole.TARGET) class TestBundleMetadata(ogt.OmniGraphTestCase): """Test bundle metadata management""" async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.graph = og.Controller.create_graph("/graph") self.context = self.graph.get_default_graph_context() self.factory = og.IBundleFactory.create() self.assertTrue(self.factory is not None) # bundle paths self.bundle1Name = "bundle1" self.bundle2Name = "bundle2" self.bundle3Name = "bundle3" self.bundle4Name = "bundle4" self.bundle5Name = "bundle5" # attribute names self.attr1Name = "attr1" self.attr2Name = "attr2" self.attr3Name = "attr3" self.attr4Name = "attr4" # attribute types self.attr1Type = og.Type(og.BaseDataType.INT) self.attr2Type = og.Type(og.BaseDataType.FLOAT) self.attr3Type = og.Type(og.BaseDataType.DOUBLE, 1, 1) self.attr4Type = og.Type(og.BaseDataType.BOOL, 1, 1) self.bundle1 = self.factory.create_bundle(self.context, self.bundle1Name) self.assertTrue(self.bundle1.valid) async def test_bundle_metadata_create(self): # check content self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) # create bundle metadata field1 = self.bundle1.create_bundle_metadata(self.attr1Name, self.attr1Type) field2 = self.bundle1.create_bundle_metadata(self.attr2Name, self.attr2Type) # check content self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 2) self.assertTrue(field1.is_valid()) self.assertTrue(field2.is_valid()) # create attributes self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.bundle1.create_attribute(self.attr2Name, self.attr2Type) # check content self.assertEqual(self.bundle1.get_attribute_count(), 2) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 2) # create children self.bundle1.create_child_bundle(self.bundle2Name) self.bundle1.create_child_bundle(self.bundle3Name) self.assertEqual(self.bundle1.get_attribute_count(), 2) self.assertEqual(self.bundle1.get_child_bundle_count(), 2) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 2) async def test_bundle_metadata_remove_bulk(self): self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.bundle1.create_bundle_metadata([self.attr1Name, self.attr2Name], [self.attr1Type, self.attr2Type]) self.assertEqual(self.bundle1.get_attribute_count(), 1) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 2) self.bundle1.remove_bundle_metadata([self.attr1Name, self.attr2Name]) self.assertEqual(self.bundle1.get_attribute_count(), 1) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) async def test_bundle_metadata_remove_single(self): self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.bundle1.create_bundle_metadata(self.attr1Name, self.attr1Type) self.bundle1.create_bundle_metadata(self.attr2Name, self.attr2Type) self.assertEqual(self.bundle1.get_attribute_count(), 1) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 2) self.bundle1.remove_bundle_metadata(self.attr1Name) self.assertEqual(self.bundle1.get_attribute_count(), 1) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 1) self.bundle1.remove_bundle_metadata(self.attr2Name) self.assertEqual(self.bundle1.get_attribute_count(), 1) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) async def test_bundle_metadata_remove_none(self): self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) self.bundle1.remove_bundle_metadata(self.attr1Name) self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) async def test_bundle_metadata_info(self): """ Counting number of attributes in metadata bundle. """ self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) self.assertEqual(len(self.bundle1.get_bundle_metadata_names()), 0) self.assertEqual(len(self.bundle1.get_bundle_metadata_types()), 0) # create two metadata attributes _ = self.bundle1.create_bundle_metadata(self.attr1Name, self.attr1Type) _ = self.bundle1.create_bundle_metadata(self.attr2Name, self.attr2Type) # check bundle metadata self.assertEqual(len(set(self.bundle1.get_bundle_metadata_names())), 2) self.assertEqual(len(set(self.bundle1.get_bundle_metadata_types())), 2) self.assertTrue(self.attr1Name in self.bundle1.get_bundle_metadata_names()) self.assertTrue(self.attr2Name in self.bundle1.get_bundle_metadata_names()) async def test_bundle_metadata_child_by_index(self): """ Metadata bundle can not be returned in a list of children. This test confirms that get_child_bundle does not return metadata bundle. """ # create two attributes _ = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) _ = self.bundle1.create_attribute(self.attr2Name, self.attr2Type) # create children ref_paths = [self.bundle2Name, self.bundle3Name, self.bundle4Name, self.bundle5Name] for i, ref_path in enumerate(ref_paths): self.bundle1.create_child_bundle(ref_path) ref_paths[i] = "{}/{}".format(self.bundle1Name, ref_path) # get child by index unique_paths = set() for index in range(len(ref_paths)): child = self.bundle1.get_child_bundle(index) unique_paths.add(child.get_path()) self.assertTrue(child.get_path()) self.assertTrue(child.get_path() in ref_paths) self.assertEqual(len(unique_paths), 4) async def test_bundle_metadata_by_name(self): """ Get bundle metadata by name. """ # create two metadata attributes self.bundle1.create_bundle_metadata(self.attr1Name, self.attr1Type) self.bundle1.create_bundle_metadata(self.attr2Name, self.attr2Type) self.assertTrue(self.bundle1.get_bundle_metadata_count(), 2) attrs = self.bundle1.get_bundle_metadata_by_name([self.attr1Name, self.attr2Name]) self.assertEqual(len(attrs), 2) self.assertEqual(attrs[0].get_name(), self.attr1Name) self.assertEqual(attrs[1].get_name(), self.attr2Name) async def test_metadata_bundle_create_many_fields(self): self.bundle1.create_bundle_metadata([self.attr1Name, self.attr2Name], [self.attr1Type, self.attr2Type]) self.assertTrue(self.bundle1.get_bundle_metadata_count(), 2) attrs = self.bundle1.get_bundle_metadata_by_name([self.attr1Name, self.attr2Name]) self.assertEqual(len(attrs), 2) self.assertEqual(attrs[0].get_name(), self.attr1Name) self.assertEqual(attrs[1].get_name(), self.attr2Name) async def test_metadata_bundle_create_single_field(self): self.bundle1.create_bundle_metadata(self.attr1Name, self.attr1Type) self.bundle1.create_bundle_metadata(self.attr2Name, self.attr2Type) self.assertTrue(self.bundle1.get_bundle_metadata_count(), 2) attrs = self.bundle1.get_bundle_metadata_by_name([self.attr1Name, self.attr2Name]) self.assertEqual(len(attrs), 2) self.assertEqual(attrs[0].get_name(), self.attr1Name) self.assertEqual(attrs[1].get_name(), self.attr2Name) async def test_attribute_metadata_create(self): # check content self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 0) # Create attribute metadata for not existing attribute should fail # Disabled because of: OM-48629. Re-enable after OM-48828 is solved. # field2 = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) # field3 = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) # self.assertFalse(field2.is_valid()) # self.assertFalse(field3.is_valid()) # check content self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 0) # create attribute and metadata for existing attribute self.bundle1.create_attribute(self.attr1Name, self.attr1Type) field2 = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) field3 = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) # check content self.assertEqual(self.bundle1.get_attribute_count(), 1) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 2) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr2Name), 0) self.assertTrue(field2.is_valid()) self.assertTrue(field3.is_valid()) async def test_attribute_metadata_create_with_ns(self): # create attribute self.bundle1.create_attribute(self.attr1Name, self.attr1Type) # create metadata for attribute that contains namespace in it name = "node:type" _ = self.bundle1.create_attribute_metadata(self.attr1Name, name, self.attr2Type) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 1) names = self.bundle1.get_attribute_metadata_names(self.attr1Name) self.assertTrue(name in names) async def test_attribute_metadata_names_and_types(self): self.bundle1.create_attribute(self.attr1Name, self.attr1Type) _ = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) _ = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) names = self.bundle1.get_attribute_metadata_names(self.attr1Name) types = self.bundle1.get_attribute_metadata_types(self.attr1Name) self.assertEqual(len(names), 2) self.assertEqual(len(types), 2) self.assertTrue(self.attr2Name in names) self.assertTrue(self.attr3Name in names) async def test_attribute_metadata_by_name(self): self.bundle1.create_attribute(self.attr1Name, self.attr1Type) # not existing field1 = self.bundle1.get_attribute_metadata_by_name(self.attr1Name, self.attr2Name) self.assertFalse(field1.is_valid()) # create and query field1 = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) self.assertTrue(field1.is_valid()) field1 = self.bundle1.get_attribute_metadata_by_name(self.attr1Name, self.attr2Name) self.assertTrue(field1.is_valid()) async def test_attribute_metadata_remove(self): self.bundle1.create_attribute(self.attr1Name, self.attr1Type) # create self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 2) # remove single self.bundle1.remove_attribute_metadata(self.attr1Name, self.attr2Name) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 1) self.bundle1.remove_attribute_metadata(self.attr1Name, self.attr3Name) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 0) # create self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 2) # remove bulk self.bundle1.remove_attribute_metadata(self.attr1Name, (self.attr2Name, self.attr3Name)) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 0) async def test_attribute_remove_with_metadata(self): attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 2) # remove attribute should remove metadata self.bundle1.remove_attribute(attr1) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 0) async def test_bundle_array_metadata(self): met1 = self.bundle1.create_bundle_metadata(self.attr3Name, self.attr3Type, 1000) self.assertTrue(met1) self.assertEqual(met1.size(), 1000) async def test_attribute_array_metadata(self): self.bundle1.create_attribute(self.attr1Name, self.attr1Type) met1 = self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type, 1000) self.assertTrue(met1) self.assertEqual(met1.size(), 1000) async def test_copy_attributes_with_metadata(self): attr1 = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) self.assertTrue(attr1) # Create bundle2 and copy attr1 from bundle1 bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) cpy_attr1 = bundle2.copy_attribute(attr1) self.assertTrue(cpy_attr1) self.assertEqual(cpy_attr1.get_type(), self.attr1Type) # metadata check self.assertEqual(bundle2.get_attribute_metadata_count(self.attr1Name), 2) names = bundle2.get_attribute_metadata_names(self.attr1Name) types = bundle2.get_attribute_metadata_types(self.attr1Name) self.assertEqual(len(names), 2) self.assertEqual(len(types), 2) self.assertTrue(self.attr2Name in names) self.assertTrue(self.attr3Name in names) async def test_copy_bundle(self): # create bundle metadata self.bundle1.create_bundle_metadata(self.attr2Name, self.attr2Type) self.bundle1.create_bundle_metadata(self.attr3Name, self.attr3Type) self.bundle1.create_bundle_metadata(self.attr4Name, self.attr4Type) # create attribute metadata self.bundle1.create_attribute(self.attr1Name, self.attr1Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr2Name, self.attr2Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) # Create bundle2 and copy attr1 from bundle1 bundle2 = self.factory.create_bundle(self.context, self.bundle2Name) bundle2.copy_bundle(self.bundle1) # bundle metadata check self.assertEqual(bundle2.get_bundle_metadata_count(), 3) names = bundle2.get_bundle_metadata_names() types = bundle2.get_bundle_metadata_names() self.assertTrue(self.attr2Name in names) self.assertTrue(self.attr3Name in names) self.assertTrue(self.attr4Name in names) self.assertEqual(len(types), 3) # attribute metadata check self.assertEqual(bundle2.get_attribute_metadata_count(self.attr1Name), 2) names = bundle2.get_attribute_metadata_names(self.attr1Name) types = bundle2.get_attribute_metadata_types(self.attr1Name) self.assertTrue(self.attr2Name in names) self.assertTrue(self.attr3Name in names) self.assertEqual(len(types), 2) async def init_for_clear_contents(self): # attributes 3 _ = self.bundle1.create_attribute(self.attr1Name, self.attr1Type) _ = self.bundle1.create_attribute(self.attr2Name, self.attr2Type) _ = self.bundle1.create_attribute(self.attr3Name, self.attr3Type) # children 2 _ = self.bundle1.create_child_bundle(self.bundle2Name) _ = self.bundle1.create_child_bundle(self.bundle3Name) # bundle metadata 4 self.bundle1.create_bundle_metadata(self.attr1Name, self.attr1Type) self.bundle1.create_bundle_metadata(self.attr2Name, self.attr2Type) self.bundle1.create_bundle_metadata(self.attr3Name, self.attr3Type) self.bundle1.create_bundle_metadata(self.attr4Name, self.attr4Type) # attr1 metadata 2 self.bundle1.create_attribute_metadata(self.attr1Name, self.attr3Name, self.attr3Type) self.bundle1.create_attribute_metadata(self.attr1Name, self.attr4Name, self.attr4Type) # attr2 metadata 1 self.bundle1.create_attribute_metadata(self.attr2Name, self.attr4Name, self.attr4Type) async def test_clear_contents(self): await self.init_for_clear_contents() self.assertEqual(self.bundle1.get_bundle_metadata_count(), 4) # metadata is not destroyed by default self.bundle1.clear_contents() # confirm bundle is clear self.assertEqual(self.bundle1.get_attribute_count(), 0) self.assertEqual(self.bundle1.get_child_bundle_count(), 0) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) # metadata IS destroyed by default self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr1Name), 0) self.assertEqual(self.bundle1.get_attribute_metadata_count(self.attr2Name), 0) self.assertTrue(self.bundle1.valid) async def test_clear_contents_bundle_metadata(self): await self.init_for_clear_contents() self.assertEqual(self.bundle1.get_bundle_metadata_count(), 4) self.bundle1.clear_contents(bundle_metadata=True) self.assertEqual(self.bundle1.get_bundle_metadata_count(), 0) async def test_clear_contents_attributes(self): await self.init_for_clear_contents() self.assertEqual(self.bundle1.get_attribute_count(), 3) self.bundle1.clear_contents(attributes=False) self.assertEqual(self.bundle1.get_attribute_count(), 3) async def test_clear_contents_child_bundles(self): await self.init_for_clear_contents() self.assertEqual(self.bundle1.get_child_bundle_count(), 2) self.bundle1.clear_contents(child_bundles=False) self.assertEqual(self.bundle1.get_child_bundle_count(), 2) class TestBundleFactoryInterface(ogt.OmniGraphTestCase): async def setUp(self): """Set up test environment, to be torn down when done""" await super().setUp() self.graph = og.Controller.create_graph("/graph") self.context = self.graph.get_default_graph_context() self.factory = og.IBundleFactory.create() self.assertTrue(self.factory is not None) self.bundle1Name = "bundle1" self.bundle2Name = "bundle2" def test_bundle_conversion_method(self): """The factory used to allow the conversion from old Py_Bundle to new I(Const)Bundle interface. Depending on writability of Py_Bundle, IConstBundle2 or IBundle2 was returned. When Py_Bundle was removed backwards compatibility conversion methods were kept. As reported in OM-84762 factory fails to pass through IBundle2, and converts IBundle2 to IConstBundle2. Eventually this test should be removed in next release when get_bundle conversion method is hard deprecated. """ bundle1 = self.factory.create_bundle(self.context, self.bundle1Name) bundle2 = self.factory.get_bundle(bundle1.get_context(), bundle1) self.assertTrue(isinstance(bundle2, og.IBundle2))
38,021
Python
44.426523
116
0.683122