file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_post_quit_hang.py
import omni.kit.test from .test_base import KitLaunchTest from pathlib import Path import omni class TestPostQuitHang(KitLaunchTest): """Test for https://nvidia-omniverse.atlassian.net/browse/OM-34203""" async def test_post_quit_api(self): kit_file = "[dependencies]\n" kit_file += '"omni.usd" = {}\n' kit_file += '"omni.kit.renderer.core" = {}\n' kit_file += '"omni.kit.loop-default" = {}\n' kit_file += '"omni.kit.mainwindow" = {}\n' kit_file += '"omni.kit.uiapp" = {}\n' kit_file += '"omni.kit.menu.file" = {}\n' kit_file += '"omni.kit.selection" = {}\n' kit_file += '"omni.kit.stage_templates" = {}\n' kit_file += """ # Register extension folder from this repo in kit [settings.app.exts] folders.'++' = ["${app}/../exts" ] [settings.app.extensions] enabledDeprecated = [ ] """ script = f""" import omni.usd import omni.kit.app import asyncio from pxr import Sdf, Usd async def main(): usd_context = omni.usd.get_context() for i in range(10): root_layer = Sdf.Layer.CreateAnonymous("test.usd") stage = Usd.Stage.Open(root_layer) await usd_context.attach_stage_async(stage) stage = usd_context.get_stage() if stage: prim = stage.DefinePrim("/World") stage.SetDefaultPrim(prim) prim = stage.GetDefaultPrim() prim.CreateAttribute("testing", Sdf.ValueTypeNames.String).Set("test") await usd_context.save_stage_async() omni.kit.app.get_app().post_quit() asyncio.ensure_future(main()) """ await self._run_kit_with_script(script, args=["--no-window"], kit_file=kit_file)
1,765
Python
29.982456
88
0.580737
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/app_startup.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["app_startup_time", "app_startup_warning_count"] import json import time from typing import Tuple import carb import carb.settings import omni.kit.app def app_startup_time(test_id: str) -> float: """Get startup time - send to nvdf""" test_start_time = time.time() startup_time = omni.kit.app.get_app().get_time_since_start_s() test_result = {"startup_time_s": startup_time} print(f"App Startup time: {startup_time}") _post_to_nvdf(test_id, test_result, time.time() - test_start_time) return startup_time def app_startup_warning_count(test_id: str) -> Tuple[int, int]: """Get the count of warnings during startup - send to nvdf""" test_start_time = time.time() warning_count = 0 error_count = 0 log_file_path = carb.settings.get_settings().get("/log/file") with open(log_file_path, "r") as file: for line in file: if "[Warning]" in line: warning_count += 1 elif "[Error]" in line: error_count += 1 test_result = {"startup_warning_count": warning_count, "startup_error_count": error_count} print(f"App Startup Warning count: {warning_count}") print(f"App Startup Error count: {error_count}") _post_to_nvdf(test_id, test_result, time.time() - test_start_time) return warning_count, error_count # TODO: should call proper API from Kit def _post_to_nvdf(test_id: str, test_result: dict, test_duration: float): """Send results to nvdf""" try: from omni.kit.test.nvdf import _can_post_to_nvdf, _get_ci_info, _post_json, get_app_info, to_nvdf_form if not _can_post_to_nvdf(): return data = {} data["ts_created"] = int(time.time() * 1000) data["app"] = get_app_info() data["ci"] = _get_ci_info() data["test"] = { "passed": True, "skipped": False, "unreliable": False, "duration": test_duration, "test_id": test_id, "ext_test_id": "omni.create.tests", "test_type": "unittest", } data["test"].update(test_result) project = "omniverse-kit-tests-results-v2" json_str = json.dumps(to_nvdf_form(data), skipkeys=True) _post_json(project, json_str) # print(json_str) # uncomment to debug except Exception as e: carb.log_warn(f"Exception occurred: {e}") if __name__ == "__main__": app_startup_time() app_startup_warning_count() omni.kit.app.get_app().post_quit(0)
2,969
Python
32.75
110
0.626474
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/extensions_load.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["validate_extensions_load"] import omni.kit.app import omni.kit.test def validate_extensions_load(): failures = [] manager = omni.kit.app.get_app().get_extension_manager() for ext in manager.get_extensions(): ext_id = ext["id"] ext_name = ext["name"] info = manager.get_extension_dict(ext_id) enabled = ext.get("enabled", False) if not enabled: continue failed = info.get("state/failed", False) if failed: failures.append(ext_name) if len(failures) == 0: print("\n[success] All extensions loaded successfuly!\n") else: print("") print(f"[error] Found {len(failures)} extensions that could not load:") for count, ext in enumerate(failures): print(f" {count+1}: {ext}") print("") return len(failures) if __name__ == "__main__": result = validate_extensions_load() omni.kit.app.get_app().post_quit(result)
1,415
Python
29.782608
79
0.650883
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/extensions_tests.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["validate_extensions_tests"] import omni.kit.app import omni.kit.test import carb.settings EXCLUSION_LIST = [] def validate_extensions_tests(exclusion_list=[]): """Return the number of enabled extensions without python tests""" failures = [] EXCLUSION_LIST.extend(exclusion_list) settings = carb.settings.get_settings() manager = omni.kit.app.get_app().get_extension_manager() for ext in manager.get_extensions(): ext_id = ext["id"] ext_name = ext["name"] info = manager.get_extension_dict(ext_id) # No apps if info.get("isKitFile", False): print(f"[ ok ] {ext_name} is an app") continue # Exclusion list if ext_name in EXCLUSION_LIST: print(f"[ ok ] {ext_name} is in the exclusion list") continue waiver = False reason = "" cpp_tests = False test_info = info.get("test", None) if isinstance(test_info, list) or isinstance(test_info, tuple): for t in test_info: if "waiver" in t: reason = t.get("waiver", "") waiver = True if "cppTests" in t: cpp_tests = True if waiver: print(f"[ ok ] {ext_name} has a waiver: {reason}") continue enabled = ext.get("enabled", False) if not enabled: print(f"[ ok ] {ext_name} is not enabled") continue # another test will report that the extension failed to load failed = info.get("state/failed", False) if failed: print(f"[ !! ] {ext_name} failed to load") continue include_tests = [] python_dict = info.get("python", {}) python_modules = python_dict.get("module", []) + python_dict.get("modules", []) for m in python_modules: module = m.get("name") if module: include_tests.append("{}.*".format(module)) settings.set("/exts/omni.kit.test/includeTests", include_tests) print(f"[ .. ] {ext_name} get tests...") test_count = omni.kit.test.get_tests() if len(test_count) > 0: print(f"[ ok ] {ext_name} has {len(test_count)} tests") elif cpp_tests: print(f"[ ok ] {ext_name} has cpp tests") else: failures.append(ext_name) print(f"[fail] {ext_name} has {len(test_count)} tests") if len(failures) == 0: print("\n[success] All extensions have tests or waiver!\n") else: print("") print(f"[error] Found {len(failures)} extensions without tests or waiver:") for count, ext in enumerate(failures): print(f" {count+1}: {ext}") print("") return len(failures) if __name__ == "__main__": result = validate_extensions_tests() omni.kit.app.get_app().post_quit(result)
3,375
Python
32.425742
87
0.576593
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/config/extension.toml
[package] title = "Audio Oscilloscope" category = "Audio" feature = true version = "0.1.0" description = "Displays the waveform of Kit's audio output." authors = ["NVIDIA"] keywords = ["audio", "debug"] [dependencies] "carb.audio" = {} "omni.usd.libs" = {} "omni.usd" = {} "omni.ui" = {} "omni.usd.schema.semantics" = {} "omni.usd.schema.audio" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.audio.oscilloscope" [[python.module]] name = "omni.kit.audio.oscilloscope" [[test]] # Just go with default timeout unless you're testing locally. # What takes 3 seconds locally could take 3 minutes in CI. #timeout = 30 args = [ # Use the null device backend so we have a consistent backend channel count, # since that'll affect the generated image. "--/audio/deviceBackend=null", # This is needed or `omni.kit.ui_test.get_menubar().find_menu("Window")` # will return `None`. "--/app/menu/legacy_mode=false", # omni.kit.property.audio causes kit to add a "do you want to save your changes" # dialogue when kit is exiting unless this option is specified. "--/app/file/ignoreUnsavedOnExit=true", # disable DPI scaling & use no-window "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.property.audio", # needed for the (manual) USD test "omni.kit.mainwindow", # needed for omni.kit.ui_test "omni.kit.ui_test", ] stdoutFailPatterns.exclude = [ "*" # I don't want these but OmniUiTest forces me to use them, so ignore all! ]
1,589
TOML
26.413793
84
0.670233
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/__init__.py
from .oscilloscope import *
28
Python
13.499993
27
0.785714
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/oscilloscope.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.audio import omni.kit.audio.oscilloscope import omni.kit.ui import omni.ui import threading import time import re import asyncio class OscilloscopeWindowExtension(omni.ext.IExt): """Audio Recorder Window Extension""" def _menu_callback(self, a, b): self._window.visible = not self._window.visible def _read_callback(self, event): img = self._oscilloscope.get_image(); self._waveform_image_provider.set_bytes_data(img, [self._waveform_width, self._waveform_height]) def _record_clicked(self): if self._recording: self._record_button.set_style({"image_url": "resources/glyphs/audio_record.svg"}) self._recording = False; self._oscilloscope.stop() else: self._record_button.set_style({"image_url": "resources/glyphs/timeline_stop.svg"}) self._recording = True self._oscilloscope.start() def on_startup(self): self._timer = None self._waveform_width = 512; self._waveform_height = 460; try: self._oscilloscope = omni.kit.audio.oscilloscope.create_oscilloscope(self._waveform_width, self._waveform_height); except Exception as e: return; self._window = omni.ui.Window("Audio Oscilloscope", width=512, height=540) self._recording = False with self._window.frame: with omni.ui.VStack(height=0, spacing=8): # waveform with omni.ui.HStack(height=460): omni.ui.Spacer() self._waveform_image_provider = omni.ui.ByteImageProvider() self._waveform_image = omni.ui.ImageWithProvider( self._waveform_image_provider, width=omni.ui.Percent(100), height=omni.ui.Percent(100), fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, ) omni.ui.Spacer() # buttons with omni.ui.HStack(): 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() self._sub = self._oscilloscope.get_event_stream().create_subscription_to_pop(self._read_callback) self._menuEntry = omni.kit.ui.get_editor_menu().add_item("Window/Oscilloscope", self._menu_callback) self._window.visible = False def on_shutdown(self): # pragma: no cover self._sub = None self._recorder = None self._window = None self._menuEntry = None self._oscilloscope = None menu = omni.kit.ui.get_editor_menu() if menu is not None: menu.remove_item("Window/Oscilloscope")
3,436
Python
37.188888
126
0.592549
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/tests/test_window_audio_oscilloscope.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.kit.ui_test import omni.ui as ui import omni.usd import omni.timeline import carb.tokens import omni.usd.audio from omni.ui.tests.test_base import OmniUiTest import pathlib import asyncio; class TestOscilloscopeWindow(OmniUiTest): # pragma: no cover async def _dock_window(self): await self.docked_test_window( window=self._win.window, width=512, height=540) # Before running each test async def setUp(self): await super().setUp() import omni.kit.material.library # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.audio.oscilloscope}") 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 oscilloscope window to open it oscilloscope_menu = omni.kit.ui_test.get_menubar().find_menu("Oscilloscope") self.assertIsNotNone(oscilloscope_menu) await oscilloscope_menu.click() self._win = omni.kit.ui_test.find("Audio Oscilloscope") self.assertIsNotNone(self._win) self._record_button = self._win.find("**/Button[*]") self.assertIsNotNone(self._record_button) # After running each test async def tearDown(self): self._win = None await super().tearDown() async def _test_just_opened(self): await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_just_opened.png") async def _test_recording(self): # docking the window breaks the UI system entirely for some reason #await self._dock_window() await self._record_button.click() # the user hit the record button await asyncio.sleep(4.0) # wait for the bar to fill up await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_recording.png") await self._record_button.click() # the user hit stop await asyncio.sleep(0.25) # wait so the window will be updated await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_stopped.png") async def _test_real_audio(self): # Comment this out to run the test. # Since this test is timing dependent, it'll never work 100% and we don't # have any sort of smart comparison that could handle a shift in the image. # It works about 80% of the time. return context = omni.usd.get_context() self.assertIsNotNone(context) context.new_stage() stage = context.get_stage() self.assertIsNotNone(stage) audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(audio) prim_path = "/test_sound" prim = stage.DefinePrim(prim_path, "OmniSound") self.assertIsNotNone(prim) prim.GetAttribute("filePath").Set(str(self._test_path / "1hz.oga")) prim.GetAttribute("auralMode").Set("nonSpatial") i = 0 while audio.get_sound_asset_status(prim) == omni.usd.audio.AssetLoadStatus.IN_PROGRESS: await asyncio.sleep(0.001) if i > 5000: raise Exception("asset load timed out") i += 1 await self._record_button.click() # the user hit the record button # use a voice to bypass the timeline voice = audio.spawn_voice(prim) i = 0 while voice.is_playing(): await asyncio.sleep(0.001) i += 1 if (i == 5000): self.assertFalse("test timed out") await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_real_audio.png") # tests need to be run sequentially, so we can only have 1 test function in this module async def test_all(self): await self._test_just_opened() await self._test_recording() await self._test_real_audio()
4,929
Python
34.724637
109
0.653479
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/tests/__init__.py
from .test_window_audio_oscilloscope import * # pragma: no cover
66
Python
32.499984
65
0.757576
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/audio/oscilloscope/__init__.py
from ._oscilloscope import *
29
Python
13.999993
28
0.758621
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_path.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import os import omni.kit.app import omni.usd import carb from omni.kit.test.teamcity import is_running_in_teamcity import sys import unittest from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper PERSISTENT_SETTINGS_PREFIX = "/persistent" class DragDropFileViewportPath(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await open_stage(get_test_data_path(__name__, "empty_stage.usda")) # After running each test async def tearDown(self): await wait_stage_loading() carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") async def test_l1_drag_drop_path_viewport_absolute(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") usd_context = omni.usd.get_context() stage = usd_context.get_stage() viewport_window = ui_test.find("Viewport") await viewport_window.focus() # drag/drop from content browser to stage window async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "materials/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=viewport_window.center) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertTrue(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_viewport_relative(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative") usd_context = omni.usd.get_context() stage = usd_context.get_stage() viewport_window = ui_test.find("Viewport") await viewport_window.focus() # drag/drop from content browser to stage window async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "materials/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=viewport_window.center) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertFalse(os.path.isabs(asset.path)) @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_l1_drag_drop_hilighting(self): from pathlib import Path import omni.kit.test from omni.kit.viewport.utility.tests.capture import capture_viewport_and_compare from carb.input import MouseEventType from carb.tokens import get_tokens_interface await ui_test.find("Content").focus() viewport_window = ui_test.find("Viewport") await viewport_window.focus() await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "shapes").replace("\\", "/") await content_browser_helper.toggle_grid_view_async(False) selections = await content_browser_helper.select_items_async(usd_path, ["basic_cube.usda"]) self.assertIsNotNone(selections) widget = await content_browser_helper.get_treeview_item_async(selections[-1].name) self.assertIsNotNone(widget) start_pos = widget.center pos_0 = viewport_window.center pos_1 = ui_test.Vec2(50, pos_0.y + 75) pos_2 = ui_test.Vec2(viewport_window.size.x - 50, pos_0.y - 25) wait_delay = 4 drag_delay = 12 await ui_test.input.emulate_mouse(MouseEventType.MOVE, start_pos) await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN) await ui_test.human_delay(wait_delay) await ui_test.input.emulate_mouse_slow_move(start_pos, pos_0, human_delay_speed=drag_delay) await ui_test.human_delay(wait_delay) await ui_test.input.emulate_mouse_slow_move(pos_0, pos_1, human_delay_speed=drag_delay) await ui_test.human_delay(wait_delay) await ui_test.input.emulate_mouse_slow_move(pos_1, pos_2, human_delay_speed=drag_delay) await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP) await ui_test.human_delay(wait_delay) EXTENSION_ROOT = Path(get_tokens_interface().resolve("${omni.kit.test_suite.viewport}")).resolve().absolute() GOLDEN_IMAGES = EXTENSION_ROOT.joinpath("data", "tests", "images") OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) passed, fail_msg = await capture_viewport_and_compare(image_name="test_l1_drag_drop_hilighting.png", output_img_dir=OUTPUTS_DIR, golden_img_dir=GOLDEN_IMAGES) self.assertTrue(passed, msg=fail_msg)
6,013
Python
46.730158
119
0.673374
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/__init__.py
from .viewport_assign_material_single import * from .viewport_assign_material_multi import * from .select_bound_objects_viewport import * from .drag_drop_material_viewport import * from .drag_drop_usd_viewport_item import * from .viewport_setup import * from .drag_drop_path import * from .drag_drop_external_audio_viewport import *
333
Python
36.111107
48
0.786787
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/viewport_setup.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportSetup"] import omni.kit.test from omni.kit.test.async_unittest import AsyncTestCase import omni.usd import carb from pxr import UsdGeom class ViewportSetup(AsyncTestCase): # Before running each test async def setUp(self): super().setUp() async def test_camera_startup_values(self): usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 18.147562, places=5) self.assertEqual(persp.GetFStopAttr().Get(), 0) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) self.assertEqual(top.GetHorizontalApertureAttr().Get(), 5000) # Legacy Viewport does some legacy hi-jinks based on resolution # self.assertEqual(top.GetVerticalApertureAttr().Get(), 5000) # Test typed-defaults and creation settings = carb.settings.get_settings() try: perps_key = '/persistent/app/primCreation/typedDefaults/camera' ortho_key = '/persistent/app/primCreation/typedDefaults/orthoCamera' settings.set(perps_key + '/focalLength', 150) settings.set(perps_key + '/fStop', 22) settings.set(perps_key + '/horizontalAperture', 1234) settings.set(ortho_key + '/horizontalAperture', 1000) settings.set(ortho_key + '/verticalAperture', 2000) await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 150) self.assertAlmostEqual(persp.GetFStopAttr().Get(), 22) self.assertAlmostEqual(persp.GetHorizontalApertureAttr().Get(), 1234) # Legacy Viewport does some legacy hi-jinks based on resolution # self.assertFalse(persp.GetVerticalApertureAttr().IsAuthored()) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) # Legacy Viewport does some legacy hi-jinks based on resolution # self.assertAlmostEqual(top.GetHorizontalApertureAttr().Get(), 1000) # self.assertAlmostEqual(top.GetVerticalApertureAttr().Get(), 2000) finally: # Reset now for all other tests settings.destroy_item(perps_key) settings.destroy_item(ortho_key)
3,154
Python
40.513157
85
0.671528
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_usd_viewport_item.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import asyncio import os import carb import omni.usd import omni.kit.app from omni.kit.async_engine import run_coroutine import concurrent.futures from typing import List from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Tf, Usd, Sdf from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, wait_stage_loading, delete_prim_path_children, arrange_windows ) from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class DragDropUsdViewportItem(AsyncTestCase): # Before running each test async def setUp(self): carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") await arrange_windows("Stage", 512) await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) await delete_prim_path_children("/World") self._usd_path = get_test_data_path(__name__, "shapes").replace("\\", "/") # After running each test async def tearDown(self): await wait_stage_loading() carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") def assertPathsEqual(self, path_a: str, path_b: str): # Make drive comparison case insensitive on Windows drive_a, path_a = os.path.splitdrive(path_a) drive_b, path_b = os.path.splitdrive(path_b) self.assertEqual(path_a, path_b) self.assertEqual(drive_a.lower(), drive_b.lower()) async def wait_for_import(self, stage, prim_paths, drag_drop_fn): # create future future_test = asyncio.Future() all_expected_prim_paths = set(prim_paths) def on_objects_changed(notice, sender, future_test): for p in notice.GetResyncedPaths(): if p.pathString in all_expected_prim_paths: all_expected_prim_paths.discard(p.pathString) if not all_expected_prim_paths: async def future_test_complete(future_test): await omni.kit.app.get_app().next_update_async() future_test.set_result(True) if not self._test_complete: self._test_complete = run_coroutine(future_test_complete(future_test)) break async def wait_for_event(future_test): await future_test # create listener self._test_complete = None listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, lambda n, s, : on_objects_changed(n, s, future_test), stage) # do drag/drop if asyncio.isfuture(drag_drop_fn()): await drag_drop_fn() else: concurrent.futures.wait(drag_drop_fn()) # wait for Tf.Notice event try: await asyncio.wait_for(wait_for_event(future_test), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_import timeout") # release listener listener.Revoke() def _verify(self, stage, prim_path, usd, reference): prim = stage.GetPrimAtPath(prim_path) self.assertIsNotNone(prim) payloads = omni.usd.get_composed_payloads_from_prim(prim) references = omni.usd.get_composed_references_from_prim(prim) if reference: items = references self.assertEqual(payloads, []) self.assertEqual(len(references), 1) else: items = payloads self.assertEqual(len(payloads), 1) self.assertEqual(references, []) for (ref, layer) in items: # unlike stage_window this ref.assetPath is not absoloute abs_path = get_test_data_path(__name__, f"{ref.assetPath}").replace("\\", "/") self.assertPathsEqual(abs_path, usd) async def _drag_drop_usd_items(self, usd_path: str, usd_names: List[str], reference: bool = False): await ui_test.find("Content").focus() viewport_window = ui_test.find("Viewport") await viewport_window.focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() await wait_stage_loading() # set dragDropImport import_method = "reference" if reference else "payload" carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", import_method) all_expected_prim_paths = [] for usd_name in usd_names: prim_name, _ = os.path.splitext(os.path.basename(usd_name)) all_expected_prim_paths.append(f"/World/{prim_name}") # drag/drop content_browser_helper = ContentBrowserTestHelper() await self.wait_for_import(stage, all_expected_prim_paths, lambda: run_coroutine(content_browser_helper.drag_and_drop_tree_view( usd_path, names=usd_names, drag_target=viewport_window.center )) ) await wait_stage_loading() # verify for usd_name, prim_path in zip(usd_names, all_expected_prim_paths): self._verify(stage, prim_path, f"{usd_path}/{usd_name}", reference) async def test_l1_drag_drop_usd_stage_item_reference(self): await self._drag_drop_usd_items(self._usd_path, ["basic_sphere.usda"], reference=True) async def test_l1_drag_drop_usd_viewport_item_payload(self): await self._drag_drop_usd_items(self._usd_path, ["basic_cone.usda"], reference=False) async def test_l1_drag_drop_multiple_usd_stage_items_reference(self): usd_names = ["basic_cube.usda", "basic_cone.usda", "basic_sphere.usda"] await self._drag_drop_usd_items(self._usd_path, usd_names, reference=True) async def test_l1_drag_drop_multiple_usd_viewport_items_payload(self): usd_names = ["basic_cube.usda", "basic_cone.usda", "basic_sphere.usda"] await self._drag_drop_usd_items(self._usd_path, usd_names, reference=False)
6,423
Python
39.658228
125
0.640822
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.7] - 2022-09-21 ### Added - Test for drag drop usd file across mulitple objects in Viewport ## [1.0.6] - 2022-08-03 ### Changes - Added external drag/drop audio file tests ## [1.0.5] - 2022-07-25 ### Changes - Refactored unittests to make use of content_browser test helpers ## [1.0.4] - 2022-06-14 ### Added - Fixed drag/drop test for viewport next ## [1.0.3] - 2022-06-09 ### Added - Test new default startup values ## [1.0.2] - 2022-06-04 ### Changes - Make path comparisons case insensitive for Windows drive - Remove extra timeout for tests not running with RTX ## [1.0.1] - 2022-05-23 ### Changes - Add missing explicit dependencies ## [1.0.0] - 2022-02-09 ### Changes - Created
796
Markdown
20.54054
80
0.674623
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/README.md
# omni.kit.test_suite.viewport ## omni.kit.test_suite.viewport Test Suite
78
Markdown
8.874999
31
0.730769
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/index.rst
omni.kit.test_suite.viewport ############################ viewport tests .. toctree:: :maxdepth: 1 CHANGELOG
118
reStructuredText
10.899999
28
0.525424
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/capture.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.kit.app import asyncio from typing import Any, Callable, Sequence class Capture: '''Base capture delegate''' def __init__(self, *args, **kwargs): self.__future = asyncio.Future() def capture(self, aov_map, frame_info, hydra_texture, result_handle): carb.log_error(f'Capture used, but capture was not overriden') async def wait_for_result(self, completion_frames: int = 2): await self.__future while completion_frames: await omni.kit.app.get_app().next_update_async() completion_frames = completion_frames - 1 return self.__future.result() def _set_completed(self, value: Any = True): if not self.__future.done(): self.__future.set_result(value) class RenderCapture(Capture): '''Viewport capturing delegate that iterates over multiple aovs and calls user defined capture_aov method for all of interest''' def __init__(self, aov_names: Sequence[str], per_aov_data: Sequence[Any] = None, *args, **kwargs): super().__init__(*args, **kwargs) # Accept a 1:1 mapping a 1:0 mapping or a N:1 mapping of AOV to data if per_aov_data is None: self.__aov_mapping = {aov:None for aov in aov_names} elif len(aov_names) == len(per_aov_data): self.__aov_mapping = {aov:data for aov, data in zip(aov_names, per_aov_data)} else: if len(per_aov_data) != 1: assert len(aov_names) == len(per_aov_data), f'Mismatch between {len(aov_names)} aovs and {len(per_aov_data)} per_aov_data' self.__aov_mapping = {aov:per_aov_data for aov in aov_names} self.__frame_info = None self.__hydra_texture = None self.__result_handle = None self.__render_capture = None @property def aov_data(self): return self.__aov_mapping.values() @property def aov_names(self): return self.__aov_mapping.keys() @property def resolution(self): return self.__frame_info.get('resolution') @property def view(self): return self.__frame_info.get('view') @property def projection(self): return self.__frame_info.get('projection') @property def frame_number(self): return self.__frame_info.get('frame_number') @property def viewport_handle(self): return self.__frame_info.get('viewport_handle') @property def hydra_texture(self): return self.__hydra_texture @property def result_handle(self): return self.__result_handle @property def frame_info(self): return self.__frame_info @property def render_capture(self): if not self.__render_capture: try: import omni.renderer_capture self.__render_capture = omni.renderer_capture.acquire_renderer_capture_interface() except ImportError: carb.log_error(f'omni.renderer_capture extension must be loaded to use this interface') raise return self.__render_capture def capture(self, aov_map, frame_info, hydra_texture, result_handle): try: self.__hydra_texture = hydra_texture self.__result_handle = result_handle self.__frame_info = frame_info color_data, color_data_set = None, False completed = [] for aov_name, user_data in self.__aov_mapping.items(): aov_data = aov_map.get(aov_name) if aov_data: self.capture_aov(user_data, aov_data) completed.append(aov_name) elif aov_name == '': color_data, color_data_set = user_data, True if color_data_set: aov_name = 'LdrColor' aov_data = aov_map.get(aov_name) if aov_data is None: aov_name = 'HdrColor' aov_data = aov_map.get(aov_name) if aov_data: self.capture_aov(color_data, aov_data) completed.append(aov_name) except: raise finally: self.__hydra_texture = None self.__result_handle = None self.__render_capture = None self._set_completed(completed) def capture_aov(self, user_data, aov: dict): carb.log_error('RenderCapture used, but capture_aov was not overriden') def save_aov_to_file(self, file_path: str, aov: dict, format_desc: dict = None): if format_desc: if hasattr(self.render_capture, 'capture_next_frame_rp_resource_to_file'): self.render_capture.capture_next_frame_rp_resource_to_file(file_path, aov['texture']['rp_resource'], format_desc=format_desc, metadata = self.__frame_info.get('metadata')) return carb.log_error('Format description provided to capture, but not honored') self.render_capture.capture_next_frame_rp_resource(file_path, aov['texture']['rp_resource'], metadata = self.__frame_info.get('metadata')) def deliver_aov_buffer(self, callback_fn: Callable, aov: dict): self.render_capture.capture_next_frame_rp_resource_callback(callback_fn, aov['texture']['rp_resource'], metadata = self.__frame_info.get('metadata')) def save_product_to_file(self, file_path: str, render_product: str): self.render_capture.capture_next_frame_using_render_product(self.viewport_handle, file_path, render_product) class MultiAOVFileCapture(RenderCapture): '''Class to capture multiple AOVs into multiple files''' def __init__(self, aov_names: Sequence[str], file_paths: Sequence[str], format_desc: dict = None, *args, **kwargs): super().__init__(aov_names, file_paths, *args, **kwargs) self.__format_desc = format_desc @property def format_desc(self): return self.__format_desc @format_desc.setter def format_desc(self, value: dict): self.__format_desc = value def capture_aov(self, file_path: str, aov: dict, format_desc: dict = None): self.save_aov_to_file(file_path, aov, self.__format_desc) class MultiAOVByteCapture(RenderCapture): '''Class to deliver multiple AOVs buffer/bytes to a callback function''' def __init__(self, aov_names: Sequence[str], callback_fns: Sequence[Callable] = None, *args, **kwargs): super().__init__(aov_names, callback_fns, *args, **kwargs) def capture_aov(self, callback_fn: Callable, aov: dict): self.deliver_aov_buffer(callback_fn or self.on_capture_completed, aov) def on_capture_completed(buffer, buffer_size, width, height, format): pass class FileCapture(MultiAOVFileCapture): '''Class to capture a single AOVs (defaulting to color) into one file''' def __init__(self, file_path: str, aov_name: str = '', *args, **kwargs): super().__init__([aov_name], [file_path], *args, **kwargs) class ByteCapture(MultiAOVByteCapture): '''Class to capture a single AOVs (defaulting to color) to a user callback''' def __init__(self, callback_fn: Callable = None, aov_name: str = '', *args, **kwargs): super().__init__([aov_name], [callback_fn], *args, **kwargs)
7,872
Python
38.365
157
0.609756
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/extension.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportWidgetExtension'] import omni.ext class ViewportWidgetExtension(omni.ext.IExt): def on_startup(self): pass def on_shutdown(self): from .widget import ViewportWidget from .impl.utility import _report_error for instance in ViewportWidget.get_instances(): # pragma: no cover try: instance.destroy() except Exception: _report_error()
884
Python
33.03846
76
0.704751
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/__init__.py
from .extension import ViewportWidgetExtension # Expose our public classes for from omni.kit.widget.viewport import ViewportWidget __all__ = ['ViewportWidget'] from .widget import ViewportWidget
197
Python
27.28571
83
0.807107
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/api.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportAPI'] import omni.usd import carb from .impl.utility import _report_error from .capture import Capture from pxr import Usd, UsdGeom, Sdf, Gf, CameraUtil from typing import Callable, Optional, Sequence, Tuple, Union import weakref import asyncio class ViewportAPI(): class __ViewportSubscription: def __init__(self, fn: Callable, callback_container: set): self.__callback_container = callback_container self.__callback = fn self.__callback_container.add(self.__callback) def destroy(self): if not self.__callback_container: return # Clear out self of references early, and then operate on the re-scoped objects scoped_container = self.__callback_container scoped_callback = self.__callback self.__callback_container, self.__callback = None, None try: scoped_container.remove(scoped_callback) except KeyError: # pragma: no cover pass def __del__(self): self.destroy() def __init__(self, usd_context_name: str, viewport_id: str, viewport_changed_fn: Optional[Callable]): self.__usd_context_name = usd_context_name self.__viewport_id = viewport_id self.__viewport_changed = viewport_changed_fn self.__viewport_texture, self.__hydra_texture = None, None self.__aspect_ratios = (1, 1) self.__projection = Gf.Matrix4d(1) self.__flat_rendered_projection = self.__flatten_matrix(self.__projection) self.__transform = Gf.Matrix4d(1) self.__view = Gf.Matrix4d(1) self.__ndc_to_world = None self.__world_to_ndc = None self.__time = Usd.TimeCode.Default() self.__view_changed = set() self.__frame_changed = set() self.__render_settings_changed = set() self.__fill_frame = False self.__lock_to_render_result = True self.__first_synch = True self.__updates_enabled = True self.__freeze_frame = False self.__scene_views = [] # Attribute to store the requirement status of the scene camera model. # We initialize it to None and will only fetch the status when needed. self.__requires_scene_camera_model = None # Attribute to flag whether importing the SceneCameraModel failed or not. # We use this to avoid continuously trying to import an unavailable or failing module. self.__scene_camera_model_import_failed = False # This stores the instance of SceneCameraModel if it's required and successfully imported. # We initialize it to None as we don't need it immediately at initialization time. self.__scene_camera_model = None settings = carb.settings.get_settings() self.__accelerate_rtx_picking = bool(settings.get("/exts/omni.kit.widget.viewport/picking/rtx/accelerate")) self.__accelerate_rtx_picking_sub = settings.subscribe_to_node_change_events( "/exts/omni.kit.widget.viewport/picking/rtx/accelerate", self.__accelerate_rtx_changed ) def __del__(self): sub, self.__accelerate_rtx_picking_sub = self.__accelerate_rtx_picking_sub, None if sub: settings = carb.settings.get_settings() settings.unsubscribe_to_change_events(sub) def add_scene_view(self, scene_view): '''Add an omni.ui.scene.SceneView to push view and projection changes to. The provided scene_view will be saved as a weak-ref.''' if not scene_view: # pragma: no cover raise RuntimeError('Provided scene_view is invalid') self.__clean_weak_views() self.__scene_views.append(weakref.ref(scene_view, self.__clean_weak_views)) _scene_camera_model = self._scene_camera_model if _scene_camera_model: scene_view.model = _scene_camera_model # Sync the model immediately model = scene_view.model model.set_floats('view', self.__flatten_matrix(self.__view)) model.set_floats('projection', self.__flatten_matrix(self.__projection)) def remove_scene_view(self, scene_view): '''Remove an omni.ui.scene.SceneView that was receiving view and projection changes.''' if not scene_view: raise RuntimeError('Provided scene_view is invalid') for sv in self.__scene_views: if sv() == scene_view: self.__scene_views.remove(sv) break self.__clean_weak_views() def subscribe_to_view_change(self, callback: Callable): return self.__subscribe_to_change(callback, self.__view_changed, 'subscribe_to_view_change') def subscribe_to_frame_change(self, callback: Callable): return self.__subscribe_to_change(callback, self.__frame_changed, 'subscribe_to_frame_change') def subscribe_to_render_settings_change(self, callback: Callable): return self.__subscribe_to_change(callback, self.__render_settings_changed, 'subscribe_to_render_settings_change') def request_pick(self, *args, **kwargs): return self.__hydra_texture.request_pick(*args, **kwargs) if self.__hydra_texture else None def request_query(self, mouse, *args, **kwargs): if self.__accelerate_rtx_picking and kwargs.get("view") is None: # If using scene_camera_model, pull view and projection from that and # avoid the flattening stage as well. if False: # self.__scene_camera_model: kwargs["view"] = self.__scene_camera_model.view kwargs["projection"] = self.__scene_camera_model.projection else: kwargs["view"] = self.__flatten_matrix(self.__view) kwargs["projection"] = self.__flat_rendered_projection return self.__hydra_texture.request_query(mouse, *args, **kwargs) if self.__hydra_texture else None def schedule_capture(self, delegate: Capture) -> Capture: if self.__viewport_texture: return self.__viewport_texture.schedule_capture(delegate) async def wait_for_render_settings_change(self): future = asyncio.Future() def rs_changed(*args): nonlocal scoped_sub scoped_sub = None if not future.done(): future.set_result(True) scoped_sub = self.subscribe_to_render_settings_change(rs_changed) return await future async def wait_for_rendered_frames(self, additional_frames: int = 0): future = asyncio.Future() def frame_changed(*args): nonlocal additional_frames, scoped_sub additional_frames = additional_frames - 1 if (additional_frames <= 0) and (not future.done()): future.set_result(True) scoped_sub = None scoped_sub = self.subscribe_to_frame_change(frame_changed) return await future # Deprecated def pick(self, *args, **kwargs): # pragma: no cover carb.log_warn('ViewportAPI.pick is deprecated, use request_pick') return self.__hydra_texture.pick(*args, **kwargs) if self.__hydra_texture else None def query(self, mouse, *args, **kwargs): # pragma: no cover carb.log_warn('ViewportAPI.query is deprecated, use request_query') return self.__hydra_texture.query(mouse, *args, **kwargs) if self.__hydra_texture else None def set_updates_enabled(self, enabled: bool = True): # pragma: no cover carb.log_warn('ViewportAPI.set_updates_enabled is deprecated, use updates_enabled') self.updates_enabled = enabled @property def hydra_engine(self): '''Get the name of the active omni.hydra.engine for this Viewport''' return self.__viewport_texture.hydra_engine if self.__viewport_texture else None @hydra_engine.setter def hydra_engine(self, hd_engine: str): '''Set the name of the active omni.hydra.engine for this Viewport''' if self.__viewport_texture: self.__viewport_texture.hydra_engine = hd_engine @property def render_mode(self): '''Get the render-mode for the active omni.hydra.engine used in this Viewport''' return self.__viewport_texture.render_mode if self.__viewport_texture else None @render_mode.setter def render_mode(self, render_mode: str): '''Set the render-mode for the active omni.hydra.engine used in this Viewport''' if self.__viewport_texture: self.__viewport_texture.render_mode = render_mode @property def set_hd_engine(self): '''Set the active omni.hydra.engine for this Viewport, and optionally its render-mode''' return self.__viewport_texture.set_hd_engine if self.__viewport_texture else None @property def camera_path(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' return self.__viewport_texture.camera_path if self.__viewport_texture else None @camera_path.setter def camera_path(self, camera_path: Union[Sdf.Path, str]): '''Set the active rendering camera from an Sdf.Path''' if self.__viewport_texture: self.__viewport_texture.camera_path = camera_path @property def resolution(self) -> Tuple[float, float]: '''Return a tuple of (resolution_x, resolution_y) this Viewport is rendering at, accounting for scale.''' return self.__viewport_texture.resolution if self.__viewport_texture else None @resolution.setter def resolution(self, value: Tuple[float, float]): '''Set the resolution to render with (resolution_x, resolution_y). The provided resolution should be full resolution, as any texture scaling will be applied to it.''' if self.__viewport_texture: self.__viewport_texture.resolution = value @property def resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' return self.__viewport_texture.resolution_scale if self.__viewport_texture else None @resolution_scale.setter def resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' if self.__viewport_texture: self.__viewport_texture.resolution_scale = value @property def full_resolution(self) -> Tuple[float, float]: '''Return a tuple of the full (full_resolution_x, full_resolution_y) this Viewport is rendering at, not accounting for scale.''' return self.__viewport_texture.full_resolution if self.__viewport_texture else None @property def render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' if self.__hydra_texture: render_product = self.__hydra_texture.get_render_product_path() if render_product and (not render_product.startswith('/')): render_product = '/Render/RenderProduct_' + render_product return render_product @render_product_path.setter def render_product_path(self, prim_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' if self.__hydra_texture: prim_path = str(prim_path) name = self.__hydra_texture.get_name() if prim_path == f'/Render/RenderProduct_{name}': prim_path = name return self.__hydra_texture.set_render_product_path(prim_path) @property def fps(self) -> float: '''Return the frames-per-second this Viewport is running at''' return self.frame_info.get('fps', 0) @property def frame_info(self) -> dict: return self.__viewport_texture.frame_info if self.__viewport_texture else {} @property def fill_frame(self) -> bool: return self.__fill_frame @fill_frame.setter def fill_frame(self, value: bool): value = bool(value) if self.__fill_frame != value: self.__fill_frame = value stage = self.stage if stage: self.viewport_changed(self.camera_path, stage) @property def lock_to_render_result(self) -> bool: return self.__lock_to_render_result @lock_to_render_result.setter def lock_to_render_result(self, value: bool): value = bool(value) if self.__lock_to_render_result != value: self.__lock_to_render_result = value if self.__viewport_texture: self.__viewport_texture._render_settings_changed() @property def freeze_frame(self) -> bool: return self.__freeze_frame @freeze_frame.setter def freeze_frame(self, value: bool): self.__freeze_frame = bool(value) @property def updates_enabled(self) -> bool: return self.__updates_enabled @updates_enabled.setter def updates_enabled(self, value: bool): value = bool(value) if self.__updates_enabled != value: self.__updates_enabled = value if self.__hydra_texture: self.__hydra_texture.set_updates_enabled(value) @property def viewport_changed(self): return self.__viewport_changed if self.__viewport_changed else lambda c, s: None @property def id(self) -> str: return self.__viewport_id @property def usd_context_name(self) -> str: '''Return the name of the omni.usd.UsdContext this Viewport is attached to''' return self.__usd_context_name @property def usd_context(self): '''Return the omni.usd.UsdContext this Viewport is attached to''' return omni.usd.get_context(self.__usd_context_name) @property def stage(self) -> Usd.Stage: '''Return the Usd.Stage of the omni.usd.UsdContext this Viewport is attached to''' return self.usd_context.get_stage() @property def projection(self) -> Gf.Matrix4d: '''Return the projection of the UsdCamera in terms of the ui element it sits in.''' return Gf.Matrix4d(self.__projection) @property def transform(self) -> Gf.Matrix4d: '''Return the world-space transform of the UsdGeom.Camera being used to render''' return Gf.Matrix4d(self.__transform) @property def view(self) -> Gf.Matrix4d: '''Return the inverse of the world-space transform of the UsdGeom.Camera being used to render''' return Gf.Matrix4d(self.__view) @property def time(self) -> Usd.TimeCode: '''Return the Usd.TimeCode this Viewport is using''' return self.__time @property def world_to_ndc(self) -> Gf.Matrix4d: if not self.__world_to_ndc: self.__world_to_ndc = self.view * self.projection return Gf.Matrix4d(self.__world_to_ndc) @property def ndc_to_world(self) -> Gf.Matrix4d: if not self.__ndc_to_world: self.__ndc_to_world = self.world_to_ndc.GetInverse() return Gf.Matrix4d(self.__ndc_to_world) @property def _scene_camera_model(self) -> "SceneCameraModel": """ This property fetches and returns the instance of SceneCameraModel. If the instance has not been fetched before, it fetches and stores it. If the instance was fetched previously, it retrieves it from the cache. Returns: Instance of SceneCameraModel, or None if it fails to fetch or not required. """ if self.__scene_camera_model is None: self.__scene_camera_model = self.__create_scene_camera_model() return self.__scene_camera_model def __create_scene_camera_model(self) -> "SceneCameraModel": """ Creates SceneCameraModel based on the requirement from app settings. If a scene camera model is required, it imports and initializes the SceneCameraModel. Returns: Instance of SceneCameraModel if required and successfully imported, else None. """ if self.__is_requires_scene_camera_model() and not self.__scene_camera_model_import_failed: # Determine viewport handle by checking if __viewport_texture exists # and has a viewport_handle attribute. if not self.__viewport_texture or not self.__viewport_texture.viewport_handle: viewport_handle = -1 else: viewport_handle = self.__viewport_texture.viewport_handle try: from omni.kit.viewport.scene_camera_model import SceneCameraModel return SceneCameraModel(self.usd_context_name, viewport_handle) except ImportError: # pragma: no cover carb.log_error("omni.kit.viewport.scene_camera_model must be enabled for singleCameraModel") self.__scene_camera_model_import_failed = True return None def __is_requires_scene_camera_model(self) -> bool: """ Determines if the SceneCameraModel is required based on app settings. If the setting has not been checked before, it fetches from the app settings and stores the boolean value. Returns: Boolean indicating whether or not the SceneCameraModel is required. """ if self.__requires_scene_camera_model is None: settings = carb.settings.acquire_settings_interface() self.__requires_scene_camera_model = bool( settings.get("/ext/omni.kit.widget.viewport/sceneView/singleCameraModel/enabled") ) return self.__requires_scene_camera_model def map_ndc_to_texture(self, mouse: Sequence[float]) -> Tuple[Tuple[float, float], 'ViewportAPI']: ratios = self.__aspect_ratios # Move into viewport's NDC-space: [-1, 1] bound by viewport mouse = (mouse[0] / ratios[0], mouse[1] / ratios[1]) # Move from NDC space to texture-space [-1, 1] to [0, 1] def check_bounds(coord): return coord >= -1 and coord <= 1 return tuple((x + 1.0) * 0.5 for x in mouse), self if (check_bounds(mouse[0]) and check_bounds(mouse[1])) else None def map_ndc_to_texture_pixel(self, mouse: Sequence[float]) -> Tuple[Tuple[float, float], 'ViewportAPI']: # Move into viewport's uv-space: [0, 1] mouse, viewport = self.map_ndc_to_texture(mouse) # Then scale by resolution flipping-y resolution = self.resolution return (int(mouse[0] * resolution[0]), int((1.0 - mouse[1]) * resolution[1])), viewport def __get_conform_policy(self): ''' TODO: Need python exposure via UsdContext or HydraTexture import carb conform_setting = carb.settings.get_settings().get("/app/hydra/aperture/conform") if (conform_setting is None) or (conform_setting == 1) or (conform_setting == 'horizontal'): return CameraUtil.MatchHorizontally if (conform_setting == 0) or (conform_setting == 'vertical'): return CameraUtil.MatchVertically if (conform_setting == 2) or (conform_setting == 'fit'): return CameraUtil.Fit if (conform_setting == 3) or (conform_setting == 'crop'): return CameraUtil.Crop if (conform_setting == 4) or (conform_setting == 'stretch'): return CameraUtil.DontConform ''' return CameraUtil.MatchHorizontally def _conform_projection(self, policy, camera: UsdGeom.Camera, image_aspect: float, canvas_aspect: float, projection: Sequence[float] = None): '''For the given camera (or possible incoming projection) return a projection matrix that matches the rendered image but keeps NDC co-ordinates for the texture bound to [-1, 1]''' if projection is None: # If no projection is provided, conform the camera based on settings # This wil adjust apertures on the gf_camera gf_camera = camera.GetCamera(self.__time) if policy == CameraUtil.DontConform: # For DontConform, still have to conform for the final canvas if image_aspect < canvas_aspect: gf_camera.horizontalAperture = gf_camera.horizontalAperture * (canvas_aspect / image_aspect) else: gf_camera.verticalAperture = gf_camera.verticalAperture * (image_aspect / canvas_aspect) else: CameraUtil.ConformWindow(gf_camera, policy, image_aspect) projection = gf_camera.frustum.ComputeProjectionMatrix() self.__flat_rendered_projection = self.__flatten_matrix(projection) else: self.__flat_rendered_projection = projection projection = Gf.Matrix4d(*projection) # projection now has the rendered image projection # Conform again based on canvas size so projection extends with the Viewport sits in the UI if image_aspect < canvas_aspect: self.__aspect_ratios = (image_aspect / canvas_aspect, 1) policy2 = CameraUtil.MatchVertically else: self.__aspect_ratios = (1, canvas_aspect / image_aspect) policy2 = CameraUtil.MatchHorizontally if policy != CameraUtil.DontConform: projection = CameraUtil.ConformedWindow(projection, policy2, canvas_aspect) return projection def _sync_viewport_api(self, camera: UsdGeom.Camera, canvas_size: Sequence[int], time: Usd.TimeCode = Usd.TimeCode.Default(), view: Sequence[float] = None, projection: Sequence[float] = None, force_update: bool = False): '''Sync the ui and viewport state, and inform any view-scubscribers if a change occured''' # Early exit if the Viewport is locked to a rendered image, not updates to SceneViews or internal state if not self.__updates_enabled or self.__freeze_frame: return # Store the current time if time: self.__time = time # When locking to render, allow one update to push initial USD state into Viewport # Otherwise, if locking to render results and no View provided, wait for next frame to deliver it. if self.__first_synch: self.__first_synch = False elif not force_update and (self.__lock_to_render_result and not view): return # If forcing UI resolution to match Viewport, set the resolution now if it needs to be updated. # Early exit in this case as it will trigger a subsequent UI -> Viewport sync. resolution = self.full_resolution canvas_size = (int(canvas_size[0]), int(canvas_size[1])) # We want to be careful not to resize to 0, 0 in the case the canvas is 0, 0 if self.__fill_frame and (canvas_size[0] and canvas_size[1]): if (resolution[0] != canvas_size[0]) or (resolution[1] != canvas_size[1]): self.resolution = canvas_size return prev_xform, prev_proj = self.__transform, self.__projection if view: self.__view = Gf.Matrix4d(*view) self.__transform = self.__view.GetInverse() else: self.__transform = camera.ComputeLocalToWorldTransform(self.__time) self.__view = self.__transform.GetInverse() image_aspect = resolution[0] / resolution[1] if resolution[1] else 1 canvas_aspect = canvas_size[0] / canvas_size[1] if canvas_size[1] else 1 policy = self.__get_conform_policy() self.__projection = self._conform_projection(policy, camera, image_aspect, canvas_aspect, projection) view_changed = self.__transform != prev_xform proj_changed = self.__projection != prev_proj if view_changed or proj_changed: self.__ndc_to_world = None self.__world_to_ndc = None self.__notify_scene_views(view_changed, proj_changed) self.__notify_objects(self.__view_changed) return True # Legacy methods that we also support def get_active_camera(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' return self.camera_path def set_active_camera(self, camera_path: Sdf.Path): '''Set the active rendering camera from an Sdf.Path''' self.camera_path = camera_path def get_render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' return self.render_product_path def set_render_product_path(self, product_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' self.render_product_path = product_path def get_texture_resolution(self) -> Tuple[float, float]: '''Return a tuple of (resolution_x, resolution_y)''' return self.resolution def set_texture_resolution(self, value: Tuple[float, float]): '''Set the resolution to render with (resolution_x, resolution_y)''' self.resolution = value def get_texture_resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' return self.resolution_scale def set_texture_resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' self.resolution_scale = value def get_full_texture_resolution(self) -> Tuple[float, float]: '''Return a tuple of (full_resolution_x, full_resolution_y)''' return self.full_resolution # Semi Private access, do not assume these will always be available by guarding usage and access. @property def display_render_var(self) -> str: if self.__viewport_texture: return self.__viewport_texture.display_render_var @display_render_var.setter def display_render_var(self, name: str): if self.__viewport_texture: self.__viewport_texture.display_render_var = str(name) @property def _settings_path(self) -> str: return self.__hydra_texture.get_settings_path() if self.__hydra_texture else None @property def _hydra_texture(self): return self.__hydra_texture @property def _viewport_texture(self): return self.__viewport_texture def _notify_frame_change(self): self.__notify_objects(self.__frame_changed) def _notify_render_settings_change(self): self.__notify_objects(self.__render_settings_changed) # Very Private methods def __set_hydra_texture(self, viewport_texture, hydra_texture): # Transfer any local state this instance is carying if hydra_texture: hydra_texture.set_updates_enabled(self.__updates_enabled) _scene_camera_model = self._scene_camera_model if _scene_camera_model: if not viewport_texture or not viewport_texture.viewport_handle: _scene_camera_model.set_viewport_handle(-1) else: _scene_camera_model.set_viewport_handle(viewport_texture.viewport_handle) # Replace the references this instance has self.__viewport_texture = viewport_texture self.__hydra_texture = hydra_texture def __callback_args(self, fn_container: Sequence): # Send a proxy so nobody can retain the instance directly vp_api = weakref.proxy(self) if id(fn_container) == id(self.__render_settings_changed): return (self.camera_path, self.resolution, vp_api) return (vp_api,) def __subscribe_to_change(self, callback: Callable, container: set, name: str): if not callable(callback): raise ValueError(f'ViewportAPI {name} requires a callable object') # If we're in a valid state, invoke the callback now. # If it throws we leave it up to the caller to figure out why and re-subscribe if self.__viewport_texture and self.__hydra_texture: callback(*self.__callback_args(container)) return ViewportAPI.__ViewportSubscription(callback, container) def __notify_objects(self, fn_container: Sequence): if fn_container: args = self.__callback_args(fn_container) for fn in fn_container.copy(): try: fn(*args) except Exception: # pragma: no cover _report_error() def __notify_scene_views(self, view: bool, proj: bool): if not self.__scene_views: return # Since these are weak-refs, prune any objects that may have gone out of date active_views = [] # Flatten these once for the loop below if view: view = [self.__view[0][0], self.__view[0][1], self.__view[0][2], self.__view[0][3], self.__view[1][0], self.__view[1][1], self.__view[1][2], self.__view[1][3], self.__view[2][0], self.__view[2][1], self.__view[2][2], self.__view[2][3], self.__view[3][0], self.__view[3][1], self.__view[3][2], self.__view[3][3]] if proj: proj = [self.__projection[0][0], self.__projection[0][1], self.__projection[0][2], self.__projection[0][3], self.__projection[1][0], self.__projection[1][1], self.__projection[1][2], self.__projection[1][3], self.__projection[2][0], self.__projection[2][1], self.__projection[2][2], self.__projection[2][3], self.__projection[3][0], self.__projection[3][1], self.__projection[3][2], self.__projection[3][3]] for sv_ref in self.__scene_views: scene_view = sv_ref() if scene_view: active_views.append(sv_ref) try: sv_model = scene_view.model view_item, proj_item = None, None _scene_camera_model = self._scene_camera_model if _scene_camera_model is None and view: view_item = sv_model.get_item('view') sv_model.set_floats(view_item, view) if proj: proj_item = sv_model.get_item('projection') sv_model.set_floats(proj_item, proj) # Update both or just a single item sv_model._item_changed(None if (view_item and proj_item) else (view_item or proj_item)) except Exception: # pragma: no cover _report_error() self.__scene_views = active_views def __clean_weak_views(self, *args): self.__scene_views = [sv for sv in self.__scene_views if sv()] def __accelerate_rtx_changed(self, *args, **kwargs): settings = carb.settings.get_settings() self.__accelerate_rtx_picking = bool(settings.get("/exts/omni.kit.widget.viewport/picking/rtx/accelerate")) @staticmethod def __flatten_matrix(m): # Pull individual Gf.Vec4 for each row, then index each component of those individually. m0, m1, m2, m3 = m[0], m[1], m[2], m[3] return [m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3]]
31,558
Python
43.701133
419
0.627575
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/display_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportDisplayDelegate'] import omni.ui as ui class ViewportDisplayDelegate: def __init__(self, viewport_api): self.__zstack = None self.__image_provider = None self.__image = None def __del__(self): self.destroy() def destroy(self): if self.__zstack: self.__zstack.clear() self.__zstack.destroy() self.__zstack = None if self.__image: self.__image.destroy() self.__image = None if self.__image_provider: self.__image_provider = None @property def image_provider(self): return self.__image_provider @image_provider.setter def image_provider(self, image_provider: ui.ImageProvider): if not isinstance(image_provider, ui.ImageProvider): raise RuntimeError('ViewportDisplayDelegate.image_provider must be an omni.ui.ImageProvider') # Clear any existing ui.ImageWithProvider # XXX: ui.ImageWithProvider should have a method to swap this out if self.__image: self.__image.destroy() self.__image = None self.__image_provider = image_provider self.__image = ui.ImageWithProvider(self.__image_provider, style_type_name_override='ViewportImage', name='Color') def create(self, ui_frame, prev_delegate, *args, **kwargs): # Save the previous ImageProvider early to keep it alive image_provider = prev_delegate.image_provider if prev_delegate else None self.destroy() with ui_frame: self.__zstack = ui.ZStack() with self.__zstack: if not image_provider: image_provider = ui.ImageProvider(name='ViewportImageProvider') self.image_provider = image_provider return self.__zstack def update(self, viewport_api, texture, view, projection, presentation_key=None): self.__image_provider.set_image_data(texture, presentation_key=presentation_key) return self.size @property def size(self): return (int(self.__image.computed_width), int(self.__image.computed_height)) class OverlayViewportDisplayDelegate(ViewportDisplayDelegate): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__overlay_image = None self.__overlay_provider = None def __del__(self): self.destroy() def destroy(self): if self.__overlay_image: self.__overlay_image.destroy() self.__overlay_image = None if self.__overlay_provider: self.__overlay_provider = None super().destroy() def create(self, ui_frame, prev_delegate, *args, **kwargs): # Grab the last image and put to push as the last element in the parent ui.Stack prev_provider = prev_delegate.image_provider if prev_delegate else None # Build the default ui for the Viewports display, but don't pass along any previous delegate/image ui_stack = super().create(ui_frame, None, *args, **kwargs) if ui_stack and prev_provider: with ui_stack: self.__overlay_provider = prev_provider self.__overlay_image = ui.ImageWithProvider(self.__overlay_provider, style_type_name_override='ViewportImageOverlay', name='Overlay') return ui_stack def set_overlay_alpha(self, overlay_alpha: float): self.__overlay_image.set_style({ 'ViewportImageOverlay': { 'color': ui.color(1.0, 1.0, 1.0, overlay_alpha) } })
4,262
Python
36.725663
108
0.600657
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/widget.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportWidget'] from .api import ViewportAPI from .impl.texture import ViewportTexture from .impl.utility import init_settings, save_implicit_cameras, StageAxis from .display_delegate import ViewportDisplayDelegate from omni.kit.async_engine import run_coroutine import omni.ui as ui import omni.usd import carb.events import carb.settings from pxr import Usd, UsdGeom, Sdf, Tf from typing import Optional, Tuple, Union import weakref import asyncio import concurrent.futures class ViewportWidget: """The Viewport Widget Simplest implementation of a viewport which you must control 100% """ __g_instances = [] @classmethod def get_instances(cls): for inst in cls.__g_instances: yield inst @classmethod def __clean_instances(cls, dead, self=None): active = [] for p in ViewportWidget.__g_instances: try: if p and p != self: active.append(p) except ReferenceError: pass ViewportWidget.__g_instances = active @property def viewport_api(self): return self.__proxy_api @property def name(self): return self.__ui_frame.name @property def visible(self): return self.__ui_frame.visible @visible.setter def visible(self, value): self.__ui_frame.visible = bool(value) def __init__(self, usd_context_name: str = '', camera_path: Optional[str] = None, resolution: Optional[tuple] = None, hd_engine: Optional[str] = None, viewport_api: Union[ViewportAPI, str, None] = None, hydra_engine_options: Optional[dict] = None, *ui_args, **ui_kwargs): """ViewportWidget contructor Args: usd_context_name (str): The name of a UsdContext this Viewport will be viewing. camera_path (str): The path to a UsdGeom.Camera to render with. resolution: (x,y): The size of the backing texture that is rendered into (or 'fill_frame' to lock to UI size). viewport_api: (ViewportAPI, str) A ViewportAPI instance that users have access to via .viewport_api property or a unique string id used to create a default ViewportAPI instance. """ self.__ui_frame: ui.Frame = ui.Frame(*ui_args, **ui_kwargs) self.__viewport_texture: Optional[ViewportTexture] = None self.__display_delegate: Optional[ViewportDisplayDelegate] = None self.__g_instances.append(weakref.proxy(self, ViewportWidget.__clean_instances)) self.__stage_listener = None self.__rsettings_changed = None if not viewport_api or not isinstance(viewport_api, ViewportAPI): viewport_id = viewport_api if viewport_api else str(id(self)) self.__vp_api: ViewportAPI = ViewportAPI(usd_context_name, viewport_id, self._viewport_changed) else: self.__vp_api: ViewportAPI = viewport_api # This object or it's parent-scope instantiator own the API, so hand out a weak-ref proxy self.__proxy_api = weakref.proxy(self.__vp_api) self.__update_api_texture = self.__vp_api._ViewportAPI__set_hydra_texture self.__stage_up: Optional[StageAxis] = None self.__size_changed: bool = False self.__resize_future: Optional[asyncio.Future] = None self.__resize_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None self.__push_ui_to_viewport: bool = False self.__expand_viewport_to_ui: bool = False self.__full_resolution: Tuple[float, float] = (0.0, 0.0) # Whether to account for DPI when driving the Viewport resolution self.__resolution_uses_dpi: bool = True resolution = self.__resolve_resolution(resolution) # Save any arguments to send to HydraTexture in a local kwargs dict self.__hydra_engine_options = hydra_engine_options # TODO: Defer ui creation until stage open self.__build_ui(usd_context_name, camera_path, resolution, hd_engine) def on_usd_context_event(event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.OPENED): self.__on_stage_opened(self.__ensure_usd_stage(), camera_path, resolution, hd_engine) elif event.type == int(omni.usd.StageEventType.CLOSING): self.__remove_notifications() elif event.type == int(omni.usd.StageEventType.SETTINGS_SAVING): # XXX: This might be better handled at a higher level or allow opt into implicit camera saving if carb.settings.get_settings().get("/app/omni.usd/storeCameraSettingsToUsdStage"): if self.__vp_api: time, camera = self.__vp_api.time, str(self.__vp_api.camera_path) else: time, camera = None, None save_implicit_cameras(self.__ensure_usd_stage(), time, camera) usd_context = self.__ensure_usd_context() self.__stage_subscription = usd_context.get_stage_event_stream().create_subscription_to_pop( on_usd_context_event, name=f'ViewportWidget {self.name} on_usd_context_event' ) stage = usd_context.get_stage() if stage: self.__on_stage_opened(stage, camera_path, resolution, hd_engine) elif usd_context and carb.settings.get_settings().get("/exts/omni.kit.widget.viewport/autoAttach/mode") == 2: # Initialize the auto-attach now, but watch for all excpetions so that constructor returns properly and this # ViewportWidget is valid and fully constructed in order to try and re-setup on next stage open try: resolution, tx_resolution = self.__get_texture_resolution(resolution) self.__viewport_texture = ViewportTexture(usd_context_name, camera_path, tx_resolution, hd_engine, hydra_engine_options=self.__hydra_engine_options, update_api_texture=self.__update_api_texture) self.__update_api_texture(self.__viewport_texture, None) self.__viewport_texture._on_stage_opened(self.__set_image_data, camera_path, self.__is_first_instance()) except Exception: import traceback carb.log_error(traceback.format_exc()) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ # Clean ourself from the instance list ViewportWidget.__clean_instances(None, self) self.__stage_subscription = None self.__remove_notifications() if self.__vp_api: clear_engine = self.__vp_api.set_hd_engine if clear_engine: clear_engine(None) self.__update_api_texture(None, None) self.__destroy_ui() self.__vp_api = None self.__proxy_api = None self.__resize_task_or_future = None @property def usd_context_name(self): return self.__vp_api.usd_context_name @property def display_delegate(self): return self.__display_delegate @display_delegate.setter def display_delegate(self, display_delegate: ViewportDisplayDelegate): if not isinstance(display_delegate, ViewportDisplayDelegate): raise RuntimeError('display_delegate must be a ViewportDisplayDelegate, {display_delegate} is not') # Store the previous delegate for return value and comparison wtether anything is actually changing prev_delegate = self.__display_delegate # If the delegate is different, call the create method and change this instance's value if succesful if prev_delegate != display_delegate: self.__ui_frame.clear() display_delegate.create(self.__ui_frame, prev_delegate) self.__display_delegate = display_delegate # Return the previous delegate so callers can swap and restore return prev_delegate def _viewport_changed(self, camera_path: Sdf.Path, stage: Usd.Stage, time: Usd.TimeCode = Usd.TimeCode.Default()): # During re-open camera_path can wind up in an empty state, so be careful around getting the UsdGeom.Camera prim = stage.GetPrimAtPath(camera_path) if (camera_path and stage) else None camera = UsdGeom.Camera(prim) if prim else None if not camera: return None, None, None canvas_size = self.__display_delegate.size force_update = self.__size_changed self.__vp_api._sync_viewport_api(camera, canvas_size, time, force_update=force_update) return camera, canvas_size, time def __ensure_usd_context(self, usd_context: omni.usd.UsdContext = None): if not usd_context: usd_context = self.__vp_api.usd_context if not usd_context: raise RuntimeError(f'omni.usd.UsdContext "{self.usd_context_name}" does not exist') return usd_context def __ensure_usd_stage(self, usd_context: omni.usd.UsdContext = None): stage = self.__ensure_usd_context(usd_context).get_stage() if stage: return stage raise RuntimeError(f'omni.usd.UsdContext "{self.usd_context_name}" has no stage') def __remove_notifications(self): # Remove notifications that are -transient- or related to a stage and can be easily setup if self.__stage_listener: self.__stage_listener.Revoke() self.__stage_listener = None if self.__rsettings_changed and self.__viewport_texture: self.__viewport_texture._remove_render_settings_changed_fn(self.__rsettings_changed) self.__rsettings_changed = None if self.__ui_frame: self.__ui_frame.set_computed_content_size_changed_fn(None) # self.set_build_fn(None) def __setup_notifications(self, stage: Usd.Stage, hydra_texture): # Remove previous -soft- notifications self.__remove_notifications() # Proxy these two object so as not to extend their lifetime the API object if hydra_texture and not isinstance(hydra_texture, weakref.ProxyType): hydra_texture = weakref.proxy(hydra_texture) assert hydra_texture is None or isinstance(hydra_texture, weakref.ProxyType), "Not sending a proxied object" self.__update_api_texture(weakref.proxy(self.__viewport_texture), hydra_texture) # Stage changed notification (Tf.Notice) def stage_changed_notice(notice, sender): camera_path = self.__vp_api.camera_path if not camera_path: return first_instance = self.__is_first_instance() camera_path_str = camera_path.pathString for p in notice.GetChangedInfoOnlyPaths(): if p == Sdf.Path.absoluteRootPath: if self.__stage_up.update(sender, self.__vp_api.time, self.usd_context_name, first_instance): self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage()) break prim_path = p.GetPrimPath() # If it is the camera path, assume any property change can affect view/projection if prim_path != camera_path: # Not the camera path, but any transform change to any parent also affects view is_child = camera_path_str.startswith(prim_path.pathString) if not is_child or not UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name): continue self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage()) break # omni.ui notification that the widget size has changed def update_size(): try: self.__size_changed = True self.__root_size_changed() self.__vp_api.viewport_changed(self.__vp_api.camera_path, self.__ensure_usd_stage()) finally: self.__size_changed = False # async version to ellide intermediate resize event async def resize_future(n_frames: int, mouse_wait: int, mouse_up: bool, update_projection: bool = False): import omni.appwindow import omni.kit.app import carb.input if update_projection: prim = stage.GetPrimAtPath(self.__vp_api.camera_path) camera = UsdGeom.Camera(prim) if prim else None if not camera: update_projection = False app = omni.kit.app.get_app() async def skip_frame(): await app.next_update_async() if update_projection: self.__vp_api._sync_viewport_api(camera, self.__display_delegate.size, force_update=True) if mouse_wait or mouse_up: iinput = carb.input.acquire_input_interface() app_window = omni.appwindow.get_default_app_window() mouse = app_window.get_mouse() mouse_value = iinput.get_mouse_value(mouse, carb.input.MouseInput.LEFT_BUTTON) frames_waited, mouse_static, prev_mouse = 0, 0, None while mouse_value: await skip_frame() frames_waited = frames_waited + 1 # Check mouse up no matter what, up cancels even if waiting for mouse paused mouse_value = iinput.get_mouse_value(mouse, carb.input.MouseInput.LEFT_BUTTON) if mouse_wait and mouse_value: if mouse_static > mouse_wait: # Else if the mouse has been on same pixel for more than required time, done break else: # Compare current and previous mouse locations cur_mouse = iinput.get_mouse_coords_pixel(mouse) if prev_mouse: if (cur_mouse[0] == prev_mouse[0]) and (cur_mouse[1] == prev_mouse[1]): mouse_static = mouse_static + 1 else: mouse_static = 0 prev_mouse = cur_mouse # Make sure to wait the miniumum nuber of frames as well if n_frames: n_frames = max(0, n_frames - frames_waited) for _ in range(n_frames): await skip_frame() # Check it hasn't been handled alredy once more if self.__resize_future.done(): return # Finally flag it as handled and push the size change self.__resize_future.set_result(True) update_size() def size_changed_notification(*args, **kwargs): # Ellide intermediate resize events when pushing ui size to Viewport if self.__push_ui_to_viewport or self.__expand_viewport_to_ui or self.__vp_api.fill_frame: if self.__resize_future and not self.__resize_future.done(): return # Setting that controls the number of ui-frame delay settings = carb.settings.get_settings() f_delay = settings.get("/exts/omni.kit.widget.viewport/resize/textureFrameDelay") mouse_pause = settings.get("/exts/omni.kit.widget.viewport/resize/waitForMousePaused") mouse_up = settings.get("/exts/omni.kit.widget.viewport/resize/waitForMouseUp") update_proj = settings.get("/exts/omni.kit.widget.viewport/resize/updateProjection") if f_delay or mouse_pause or mouse_up: self.__resize_future = asyncio.Future() self.__resize_task_or_future = run_coroutine(resize_future(f_delay, mouse_pause, mouse_up, update_proj)) return update_size() # hydra_texture notification that the render-settings have changed (we only care about camera and resolution) def render_settings_changed(camera_path, resolution): # Notify everything else in the chain self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage()) self.__vp_api._notify_render_settings_change() self.__stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, lambda n, s: stage_changed_notice(n, s), stage) self.__rsettings_changed = self.__viewport_texture._add_render_settings_changed_fn(render_settings_changed) self.__ui_frame.set_computed_content_size_changed_fn(size_changed_notification) # self.set_build_fn(update_size) # Update now if the widget is layed out if self.__ui_frame.computed_height: update_size() def __resolve_resolution(self, resolution): # XXX: ViewportWindow handles the de-serialization of saved Viewport resolution. # This means clients of ViewportWidget only must handle startup resolution themselves. if resolution is None: # Support legacy settings to force fit-viewport settings = carb.settings.get_settings() width, height = settings.get('/app/renderer/resolution/width'), settings.get('/app/renderer/resolution/height') # If both are set to values above 0, that is the default resolution for a Viewport # If either of these being zero or below causes autmoatic resolution to fill the UI frame if ((width is not None) and (width > 0)) and ((height is not None) and (height > 0)): resolution = (width, height) elif ((width is not None) and (width <= 0)) or ((height is not None) and (height <= 0)): resolution = 'fill_frame' # Allow a 'fill_frame' constant to be used for resolution # Any constant zero or below also fills frame (support legacy behavior) if (resolution is not None) and ((isinstance(resolution, str) and resolution == 'fill_frame') or int(resolution[0]) <= 0 or int(resolution[1]) <= 0): resolution = 'fill_frame' self.__vp_api.fill_frame = True # Allow a 'fill_frame' constant to be used for resolution # Any constant zero or below also fills frame (support legacy behavior) if (resolution is not None): if (isinstance(resolution, str) and resolution == 'fill_frame') or int(resolution[0]) <= 0 or int(resolution[1]) <= 0: resolution = 'fill_frame' self.__push_ui_to_viewport = True self.__vp_api.fill_frame = True else: self.__full_resolution = resolution return resolution def __get_texture_resolution(self, resolution: Union[str, tuple]): # Don't pass 'fill_frame' to ViewportTexture if it was requested, that will be done during layout anyway if resolution == 'fill_frame': return ((0, 0), None) return resolution, resolution def __build_ui(self, usd_context_name: str, camera_path: str, resolution: Union[str, tuple], hd_engine: str): # Required for a lot of things (like selection-color) to work! init_settings() resolution, tx_resolution = self.__get_texture_resolution(resolution) # the viewport texture is the base background inmage that is drive by the Hydra_Texture object self.__viewport_texture = ViewportTexture(usd_context_name, camera_path, tx_resolution, hd_engine, hydra_engine_options=self.__hydra_engine_options, update_api_texture=self.__update_api_texture) self.__update_api_texture(self.__viewport_texture, None) self.display_delegate = ViewportDisplayDelegate(self.__proxy_api) # Pull the current Viewport full resolution now (will call __root_size_changed) self.set_resolution(resolution) def __destroy_ui(self): self.__display_delegate.destroy() if self.__viewport_texture: self.__viewport_texture.destroy() self.__viewport_texture = None if self.__ui_frame: self.__ui_frame.destroy() self.__ui_frame = None def __is_first_instance(self) -> bool: for vp_instance in self.__g_instances: if vp_instance == self: # vpinstance is this object, and no other instances attached to named UsdContext has been seen return True elif vp_instance.usd_context_name == self.usd_context_name: # vpinstance is NOT this object, but vpinstance is attached to same UsdContext return False # Should be unreachable, but would be True in the event neither case above was triggered return True def __set_image_data(self, texture, presentation_key = 0): vp_api = self.__vp_api prim = self.__ensure_usd_stage().GetPrimAtPath(vp_api.camera_path) camera = UsdGeom.Camera(prim) if prim else None frame_info = vp_api.frame_info lock_to_render = vp_api.lock_to_render_result view = frame_info.get('view', None) if lock_to_render else None # omni.ui.scene may not handle RTX projection yet, so calculate from USD camera projection = None # frame_info.get('projection', None) if lock_to_render else None canvas_size = self.__display_delegate.update(viewport_api=vp_api, texture=texture, view=view, projection=projection, presentation_key=presentation_key) vp_api._sync_viewport_api(camera, canvas_size, vp_api.time, view, projection, force_update=True) vp_api._notify_frame_change() def __on_stage_opened(self, stage: Usd.Stage, camera_path: str, resolution: tuple, hd_engine: str): """Called when opening a new stage""" # We support creation of ViewportWidget with an explicit path. # If that path was not given or does not exists, fall-back to ov-metadata if camera_path: cam_prim = stage.GetPrimAtPath(camera_path) if not cam_prim or not UsdGeom.Camera(cam_prim): camera_path = False if not camera_path: # TODO: 104 Put in proper namespace and per viewport # camera_path = stage.GetMetadataByDictKey("customLayerData", f"cameraSettings:{self.__vp_api.id}:boundCamera") or # Fallback to < 103.1 boundCamera try: # Wrap in a try-catch so failure reading metadata does not cascade to caller. camera_path = stage.GetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera") except Tf.ErrorException as e: carb.log_error(f"Error reading Usd.Stage's boundCamera metadata {e}") # Cache the known up-axis to watch for changes self.__stage_up = StageAxis(stage) if self.__viewport_texture is None: self.__build_ui(self.usd_context_name, camera_path, resolution, hd_engine) else: self.__viewport_texture.camera_path = camera_path hydra_texture = self.__viewport_texture._on_stage_opened(self.__set_image_data, camera_path, self.__is_first_instance()) self.__setup_notifications(stage, hydra_texture) # XXX: Temporary API for driving Viewport resolution based on UI. These may be removed. @property def resolution_uses_dpi(self) -> bool: """Whether to account for DPI when driving the Viewport texture resolution""" return self.__resolution_uses_dpi @property def fill_frame(self) -> bool: """Whether the ui object containing the Viewport texture expands both dimensions of resolution based on the ui size""" return self.__push_ui_to_viewport @property def expand_viewport(self) -> bool: """Whether the ui object containing the Viewport texture expands one dimension of resolution to cover the full ui size""" return self.__expand_viewport_to_ui @resolution_uses_dpi.setter def resolution_uses_dpi(self, value: bool) -> None: """Tell the ui object whether to use DPI scale when driving the Viewport texture resolution""" value = bool(value) if self.__resolution_uses_dpi != value: self.__resolution_uses_dpi = value self.__root_size_changed() @fill_frame.setter def fill_frame(self, value: bool) -> None: """Tell the ui object containing the Viewport texture to expand both dimensions of resolution based on the ui size""" value = bool(value) if self.__push_ui_to_viewport != value: self.__push_ui_to_viewport = value if not self.__root_size_changed(): self.__vp_api.resolution = self.__full_resolution @expand_viewport.setter def expand_viewport(self, value: bool) -> None: """Tell the ui object containing the Viewport texture to expand one dimension of resolution to cover the full ui size""" value = bool(value) if self.__expand_viewport_to_ui != value: self.__expand_viewport_to_ui = value if not self.__root_size_changed(): self.__vp_api.resolution = self.__full_resolution def set_resolution(self, resolution: Tuple[float, float]) -> None: self.__full_resolution = resolution # When resolution is <= 0, that means ui.Frame drives Viewport resolution self.__push_ui_to_viewport = (resolution is None) or (resolution[0] <= 0) or (resolution[1] <= 0) if not self.__root_size_changed(): # If neither option is enabled, then just set the resolution directly self.__vp_api.resolution = resolution @property def resolution(self) -> Tuple[float, float]: return self.__vp_api.resolution @resolution.setter def resolution(self, resolution: Tuple[float, float]): self.set_resolution(resolution) @property def full_resolution(self): return self.__full_resolution def __root_size_changed(self, *args, **kwargs): # If neither options are enabled, then do nothing to the Viewport's resolution if not self.__push_ui_to_viewport and not self.__expand_viewport_to_ui: return False # Match the legacy Viewport resolution and fit # XXX: Note for a downsampled constant resolution, that is expanded to the Viewport dimensions # the order of operation is off if one expectes 512 x 512 @ 1 to 1024 x 1024 @ 0.5 to exapnd to the same result # Get the omni.ui.Widget computed size ui_frame = self.__ui_frame res_x, res_y = int(ui_frame.computed_width), int(ui_frame.computed_height) # Scale by DPI as legacy Viewport (to match legacy Viewport calculations) dpi_scale = ui.Workspace.get_dpi_scale() if self.__resolution_uses_dpi else 1.0 res_x, res_y = res_x * dpi_scale, res_y * dpi_scale # Full resolution width and hight fres_x, fres_y = self.__full_resolution if self.__full_resolution else (res_x, res_y) if self.__expand_viewport_to_ui and (fres_y > 0) and (res_y > 0): tex_ratio = fres_x / fres_y ui_ratio = res_x / res_y if tex_ratio < ui_ratio: fres_x = fres_x * (ui_ratio / tex_ratio) else: fres_y = fres_y * (tex_ratio / ui_ratio) # Limit the resolution to not grow too large res_x, res_y = min(res_x, fres_x), min(res_y, fres_y) self.__vp_api.resolution = res_x, res_y return True
28,492
Python
48.125862
159
0.615752
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_scene_view_integration.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestSceneViewIntegration"] from omni.kit.widget.viewport import ViewportWidget from omni.ui.tests.test_base import OmniUiTest import omni.usd from pathlib import Path import carb CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') TEST_WIDTH, TEST_HEIGHT = 360, 240 class TestSceneViewIntegration(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await omni.usd.get_context().new_stage_async() # After running each test async def tearDown(self): await super().tearDown() await self.linux_gpu_shutdown_workaround() async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''): await self.wait_n_updates(10) omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name)) await self.wait_n_updates(10) async def open_usd_file(self, filename: str, resolved: bool = False): usd_context = omni.usd.get_context() usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename) await usd_context.open_stage_async(usd_path) return usd_context def assertAlmostEqual(self, a, b, places: int = 4): if isinstance(a, float) or isinstance(a, int): super().assertAlmostEqual(a, b, places) else: for i in range(len(b)): super().assertAlmostEqual(a[i], b[i], places) async def test_scene_view_compositing(self): """Test adding a SceneView to the Viewport will draw correctly""" await self.open_usd_file("cube.usda") import omni.ui import omni.ui.scene await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # Need a Window otherwise the ui size calculations won't run window_flags = omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR style = {"border_width": 0} window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags, padding_x=0, padding_y=0) with window.frame: window.frame.set_style(style) with omni.ui.ZStack(): viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT), style=style) scene_view = omni.ui.scene.SceneView(style=style) with scene_view.scene: size = 50 vertex_indices = [0, 1, 3, 2, 4, 6, 7, 5, 6, 2, 3, 7, 4, 5, 1, 0, 4, 0, 2, 6, 5, 7, 3, 1] points = [(-size, -size, size), (size, -size, size), (-size, size, size), (size, size, size), (-size, -size, -size), (size, -size, -size), (-size, size, -size), (size, size, -size)] omni.ui.scene.PolygonMesh(points, [[1.0, 0.0, 1.0, 0.5]] * len(vertex_indices), vertex_counts=[4] * 6, vertex_indices=vertex_indices, wireframe=True, thicknesses=[2] * len(vertex_indices)) viewport_widget.viewport_api.add_scene_view(scene_view) await self.wait_n_updates(32) await self.finalize_test(golden_img_dir=TEST_FILES_DIR, golden_img_name="test_scene_view_compositing.png") viewport_widget.viewport_api.remove_scene_view(scene_view) viewport_widget.destroy() del viewport_widget
4,183
Python
42.583333
125
0.608654
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_widget.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestWidgetAPI"] import omni.kit.test from omni.kit.widget.viewport import ViewportWidget from omni.kit.widget.viewport.display_delegate import ViewportDisplayDelegate, OverlayViewportDisplayDelegate from omni.kit.test import get_test_output_path from omni.ui.tests.test_base import OmniUiTest import omni.kit.commands import omni.usd import carb from pxr import Gf, Sdf, Usd, UsdGeom from pathlib import Path import traceback CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') OUTPUTS_DIR = Path(get_test_output_path()) TEST_WIDTH, TEST_HEIGHT = 360, 240 class TestWidgetAPI(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await omni.usd.get_context().new_stage_async() # After running each test async def tearDown(self): await super().tearDown() await self.linux_gpu_shutdown_workaround() async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''): await self.wait_n_updates(10) omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name)) await self.wait_n_updates(10) async def open_usd_file(self, filename: str, resolved: bool = False): usd_context = omni.usd.get_context() usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename) await usd_context.open_stage_async(usd_path) return usd_context def assertAlmostEqual(self, a, b, places: int = 4): if isinstance(a, float) or isinstance(a, int): super().assertAlmostEqual(a, b, places) else: for i in range(len(b)): super().assertAlmostEqual(a[i], b[i], places) async def test_widget_pre_open(self): """Test ViewportWidget creation with existing UsdContext and Usd.Stage and startup resolutin settings""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('cube.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() settings = carb.settings.get_settings() viewport_widget = None try: settings.set("/app/renderer/resolution/width", 400) settings.set("/app/renderer/resolution/height", 400) await self.wait_n_updates(6) viewport_widget = ViewportWidget() viewport_api = viewport_widget.viewport_api # Test omni.usd.UsdContext and Usd.Stage properties self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) # Test startup resolution self.assertEqual(viewport_api.resolution, (400, 400)) self.assertEqual(viewport_api.resolution_scale, 1.0) # Test deprecated resolution API methods (not properties) self.assertEqual(viewport_api.resolution, viewport_api.get_texture_resolution()) viewport_api.set_texture_resolution((200, 200)) self.assertEqual(viewport_api.resolution, (200, 200)) # Test deprecated camera API methods (not properties) self.assertEqual(viewport_api.camera_path, viewport_api.get_active_camera()) viewport_api.set_active_camera(Sdf.Path('/OmniverseKit_Top')) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Top')) finally: settings.destroy_item("/app/renderer/resolution/width") settings.destroy_item("/app/renderer/resolution/height") if viewport_widget: viewport_widget.destroy() del viewport_widget await self.wait_n_updates(6) await self.finalize_test_no_image() async def test_widget_post_open(self): """Test ViewportWidget adopts a change to the Usd.Stage after it is visible and startup resolution scale setting""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) settings = carb.settings.get_settings() viewport_widget = None try: settings.set("/app/renderer/resolution/width", 400) settings.set("/app/renderer/resolution/height", 400) settings.set("/app/renderer/resolution/multiplier", 0.5) await self.wait_n_updates(6) viewport_widget = ViewportWidget() viewport_api = viewport_widget.viewport_api # Test omni.usd.UsdContext and Usd.Stage properties usd_context = await self.open_usd_file('sphere.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() # Test display-delegate API await self.__test_display_delegate(viewport_widget) self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) # Test startup resolution self.assertEqual(viewport_api.resolution, (200, 200)) self.assertEqual(viewport_api.resolution_scale, 0.5) finally: settings.destroy_item("/app/renderer/resolution/width") settings.destroy_item("/app/renderer/resolution/height") settings.destroy_item("/app/renderer/resolution/multiplier") if viewport_widget: viewport_widget.destroy() del viewport_widget await self.wait_n_updates(6) await self.finalize_test_no_image() async def test_widget_custom_camera_saved(self): """Test ViewportWidget will absorb the stored Kit bound camera""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('custom_camera.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) viewport_api = viewport_widget.viewport_api self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera')) cam_prim = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path) self.assertTrue(bool(cam_prim)) cam_geom = UsdGeom.Camera(cam_prim) self.assertTrue(bool(cam_geom)) coi_prop = cam_prim.GetProperty('omni:kit:centerOfInterest') self.assertTrue(bool(coi_prop)) coi_prop.Get() world_pos = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0)) self.assertAlmostEqual(world_pos, Gf.Vec3d(250, 825, 800)) self.assertAlmostEqual(coi_prop.Get(), Gf.Vec3d(0, 0, -1176.0633486339075)) viewport_widget.destroy() del viewport_widget await self.finalize_test_no_image() async def test_widget_custom_camera_contructor(self): """Test ViewportWidget can be contructed with a specified Camera""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('custom_camera.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT), camera_path='/World/Camera_01') viewport_api = viewport_widget.viewport_api self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera_01')) cam_prim = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path) self.assertTrue(bool(cam_prim)) cam_geom = UsdGeom.Camera(cam_prim) self.assertTrue(bool(cam_geom)) coi_prop = cam_prim.GetProperty('omni:kit:centerOfInterest') self.assertTrue(bool(coi_prop)) coi_prop.Get() world_pos = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0)) self.assertAlmostEqual(world_pos, Gf.Vec3d(350, 650, -900)) self.assertAlmostEqual(coi_prop.Get(), Gf.Vec3d(0, 0, -1164.0446726822815)) viewport_widget.destroy() del viewport_widget await self.finalize_test_no_image() async def test_implicit_cameras(self): """Test ViewportWidget creation with existing UsdContext and Usd.Stage""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('cube.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) viewport_api = viewport_widget.viewport_api self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) time = Usd.TimeCode.Default() def test_default_camera_position(cam_path: str, expected_pos: Gf.Vec3d, expected_rot: Gf.Vec3d = None): prim = usd_context.get_stage().GetPrimAtPath(cam_path) camera = UsdGeom.Camera(prim) if prim else None self.assertTrue(bool(camera)) world_xform = camera.ComputeLocalToWorldTransform(time) world_pos = world_xform.Transform(Gf.Vec3d(0, 0, 0)) self.assertAlmostEqual(world_pos, expected_pos) if expected_rot: rot_prop = prim.GetProperty('xformOp:rotateXYZ') self.assertIsNotNone(rot_prop) rot_value = rot_prop.Get() self.assertAlmostEqual(rot_value, expected_rot) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(-35.26439, 45, 0)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000), Gf.Vec3d(0, 0, 0)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0), Gf.Vec3d(90, 0, 180)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0), Gf.Vec3d(0, -90, 0)) output_file = str(OUTPUTS_DIR.joinpath('implicit_cameras_same.usda')) (result, err, saved_layers) = await usd_context.save_as_stage_async(output_file) self.assertTrue(result) await omni.usd.get_context().new_stage_async() await usd_context.open_stage_async(output_file) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0)) # Change OmniverseKit_Persp location omni.kit.commands.create( 'TransformPrimCommand', path='/OmniverseKit_Persp', new_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(-100, -200, -300)), old_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(500, 500, 500)), time_code=time, ).do() # Change OmniverseKit_Front location omni.kit.commands.create( 'TransformPrimCommand', path='/OmniverseKit_Front', new_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(0, 0, 56789)), old_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(0, 0, 50000)), time_code=time, ).do() # Change OmniverseKit_Top aperture UsdGeom.Camera(usd_context.get_stage().GetPrimAtPath('/OmniverseKit_Top')).GetHorizontalApertureAttr().Set(50000) output_file = str(OUTPUTS_DIR.joinpath('implicit_cameras_changed.usda')) (result, err, saved_layers) = await usd_context.save_as_stage_async(output_file) self.assertTrue(result) await omni.usd.get_context().new_stage_async() await usd_context.open_stage_async(output_file) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(-100, -200, -300)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 56789)) # These haven't changed and should be default test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0)) # Test ortho aperture change is picked up horiz_ap = UsdGeom.Camera(usd_context.get_stage().GetPrimAtPath('/OmniverseKit_Top')).GetHorizontalApertureAttr().Get() self.assertAlmostEqual(horiz_ap, 50000) # Test implicit camera creation for existing Z-Up scene # usd_context = await self.open_usd_file('implicit_cams_z_up.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Top')) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(54.73561, 0, 135)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(500, 0, 0), Gf.Vec3d(90, 0, 90)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 0, 25), Gf.Vec3d(0, 0, -90)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(0, -50000, 0), Gf.Vec3d(90, 0, 0)) # Test that creation of another ViewportWidget doesn't affect existing implict caameras viewport_widget_2 = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(54.73561, 0, 135)) viewport_widget_2.destroy() del viewport_widget_2 # Test saving metadata to usd, so copy the input files to writeable temp files from shutil import copyfile tmp_layers = str(OUTPUTS_DIR.joinpath('layers.usda')) copyfile(str(USD_FILES_DIR.joinpath('layers.usda')), tmp_layers) copyfile(str(USD_FILES_DIR.joinpath('sublayer.usda')), str(OUTPUTS_DIR.joinpath('sublayer.usda'))) # Open the copy and validate the default camera usd_context = await self.open_usd_file(tmp_layers, True) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) # Switch to a known camera and re-validate viewport_api.camera_path = '/World/Camera' self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera')) # Save the file and re-open it # XXX: Need to dirty something in the stage for save to take affect stage = usd_context.get_stage() stage.GetPrimAtPath(viewport_api.camera_path).GetAttribute('focalLength').Set(51) # Move the target layer to a sub-layer and then attmept the save with Usd.EditContext(stage, stage.GetLayerStack()[-1]): await usd_context.save_stage_async() await omni.kit.app.get_app().next_update_async() await omni.usd.get_context().new_stage_async() # Re-open usd_context = await self.open_usd_file(tmp_layers, True) # Camera should match what was just saved self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera')) # Test dynmically switching Stage up-axis async def set_stage_axis(stage, cam_prim, up_axis: str, wait: int = 2): stage.SetMetadata(UsdGeom.Tokens.upAxis, up_axis) for i in range(wait): await omni.kit.app.get_app().next_update_async() return UsdGeom.Xformable(cam_prim).GetLocalTransformation() await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() self.assertIsNotNone(usd_context) stage = usd_context.get_stage() self.assertIsNotNone(stage) cam_prim = stage.GetPrimAtPath(viewport_api.camera_path) self.assertIsNotNone(cam_prim) cam_xformable = UsdGeom.Xformable(cam_prim) self.assertIsNotNone(cam_xformable) self.assertEqual(cam_prim.GetPath().pathString, '/OmniverseKit_Persp') xform_y = await set_stage_axis(stage, cam_prim, 'Y') xform_y1 = cam_xformable.GetLocalTransformation() self.assertEqual(xform_y, xform_y1) self.assertAlmostEqual(xform_y.ExtractRotation().GetAxis(), Gf.Vec3d(-0.59028449177967, 0.7692737418738016, 0.24450384215364918)) xform_z = await set_stage_axis(stage, cam_prim, 'Z') self.assertNotEqual(xform_y, xform_z) self.assertAlmostEqual(xform_z.ExtractRotation().GetAxis(), Gf.Vec3d(0.1870534627395223, 0.4515870066346049, 0.8723990930279281)) xform_x = await set_stage_axis(stage, cam_prim, 'X') self.assertNotEqual(xform_x, xform_z) self.assertNotEqual(xform_x, xform_y) self.assertAlmostEqual(xform_x.ExtractRotation().GetAxis(), Gf.Vec3d(0.541766002079245, 0.07132485246922922, 0.8374976802423478)) texture_pixel, vp_api = viewport_api.map_ndc_to_texture((0, 0)) self.assertAlmostEqual(texture_pixel, (0.5, 0.5)) self.assertEqual(vp_api, viewport_api) # Test return of Viewport is None when NDC is out of bounds texture_pixel, vp_api = viewport_api.map_ndc_to_texture((-2, -2)) self.assertIsNone(vp_api) # Test return of Viewport is None when NDC is out of bounds texture_pixel, vp_api = viewport_api.map_ndc_to_texture((2, 2)) self.assertIsNone(vp_api) # Test camera is correctly positioned/labeled with new stage and Z or Y setting settings = carb.settings.get_settings() async def new_stage_with_up_setting(up_axis: str, wait: int = 2): settings.set('/persistent/app/stage/upAxis', up_axis) for i in range(wait): await omni.kit.app.get_app().next_update_async() await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() self.assertIsNotNone(usd_context) stage = usd_context.get_stage() self.assertIsNotNone(stage) cam_prim = stage.GetPrimAtPath(viewport_api.camera_path) return UsdGeom.Xformable(cam_prim).GetLocalTransformation() # Switch to new stage as Z-up and test against values from previous Z-up try: xform_z = await new_stage_with_up_setting('Z') self.assertNotEqual(xform_y, xform_z) self.assertAlmostEqual(xform_z.ExtractRotation().GetAxis(), Gf.Vec3d(0.1870534627395223, 0.4515870066346049, 0.8723990930279281)) finally: settings.destroy_item('/persistent/app/stage/upAxis') try: # Test again against default up as Y xform_y1 = await new_stage_with_up_setting('Y') self.assertEqual(xform_y, xform_y1) self.assertAlmostEqual(xform_y.ExtractRotation().GetAxis(), Gf.Vec3d(-0.59028449177967, 0.7692737418738016, 0.24450384215364918)) finally: settings.destroy_item('/persistent/app/stage/upAxis') # Test opeinig a file with implicit cameras saved into it works properly usd_context = await self.open_usd_file('implcit_precision.usda') self.assertIsNotNone(usd_context.get_stage()) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(-1500, 400, 500), Gf.Vec3d(-15, 751, 0)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000), Gf.Vec3d(0, 0, 0)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0), Gf.Vec3d(90, 0, 180)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0), Gf.Vec3d(0, -90, 0)) await self.__test_camera_startup_values(viewport_widget) await self.__test_camera_target_settings(viewport_widget) def get_tr(stage: Usd.Stage, cam: str): xf = UsdGeom.Camera(stage.GetPrimAtPath(f'/OmniverseKit_{cam}')).ComputeLocalToWorldTransform(0) return xf.ExtractTranslation() def get_rot(stage: Usd.Stage, cam: str): xf = UsdGeom.Camera(stage.GetPrimAtPath(f'/OmniverseKit_{cam}')).ComputeLocalToWorldTransform(0) decomp = (Gf.Vec3d(-1, 0, 0), Gf.Vec3d(0, -1, 0), Gf.Vec3d(0, 0, 1)) rotation = xf.ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) return rotation # Test re-opening ortho cameras keep orthogonal rotations usd_context = await self.open_usd_file('ortho_y.usda') stage = omni.usd.get_context().get_stage() self.assertTrue(Gf.IsClose(get_rot(stage, 'Top'), Gf.Vec3d(-90, 0, -180), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Front'), Gf.Vec3d(0, 0, 0), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Right'), Gf.Vec3d(0, -90, 0), 0.00001)) usd_context = await self.open_usd_file('ortho_z.usda') stage = omni.usd.get_context().get_stage() self.assertTrue(Gf.IsClose(get_rot(stage, 'Top'), Gf.Vec3d(0, 0, -90), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Front'), Gf.Vec3d(90, 90, 0), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Right'), Gf.Vec3d(90, 0, 0), 0.00001)) usd_context = await self.open_usd_file('cam_prop_declaration_only.usda') stage = omni.usd.get_context().get_stage() self.assertTrue(Gf.IsClose(get_tr(stage, 'Persp'), Gf.Vec3d(-417, 100, -110), 0.00001)) self.assertTrue(Gf.IsClose(get_tr(stage, 'Top'), Gf.Vec3d(0, 50000, 0), 0.00001)) self.assertTrue(Gf.IsClose(get_tr(stage, 'Front'), Gf.Vec3d(0, 0, 50000), 0.00001)) self.assertTrue(Gf.IsClose(get_tr(stage, 'Right'), Gf.Vec3d(-50000, 0, 0), 0.00001)) viewport_widget.destroy() del viewport_widget await self.finalize_test_no_image() async def test_dont_save_implicit_cameras(self): usd_context = omni.usd.get_context() await usd_context.new_stage_async() self.assertIsNotNone(usd_context.get_stage()) settings = carb.settings.get_settings() # Save current state so it restored shouldsave = settings.get("/app/omni.usd/storeCameraSettingsToUsdStage") try: settings.set("/app/omni.usd/storeCameraSettingsToUsdStage", False) output_file = str(OUTPUTS_DIR.joinpath('dont_save_implicit_cameras.usda')) (result, err, saved_layers) = await usd_context.save_as_stage_async(output_file) self.assertTrue(result) usd_context = await self.open_usd_file(output_file, True) stage = usd_context.get_stage() self.assertFalse(stage.HasMetadataDictKey("customLayerData", "cameraSettings")) except Exception as e: raise e finally: settings.set("/app/omni.usd/storeCameraSettingsToUsdStage", shouldsave) await self.finalize_test_no_image() async def __test_camera_startup_values(self, viewport_widget): # await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 18.147562, places=5) self.assertEqual(persp.GetFStopAttr().Get(), 0) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) self.assertEqual(top.GetHorizontalApertureAttr().Get(), 5000) self.assertEqual(top.GetVerticalApertureAttr().Get(), 5000) # Test typed-defaults and creation settings = carb.settings.get_settings() try: perps_key = '/persistent/app/primCreation/typedDefaults/camera' ortho_key = '/persistent/app/primCreation/typedDefaults/orthoCamera' settings.set(perps_key + '/focalLength', 150) settings.set(perps_key + '/fStop', 22) settings.set(perps_key + '/clippingRange', (200, 2000)) settings.set(perps_key + '/horizontalAperture', 1234) settings.set(ortho_key + '/horizontalAperture', 1000) settings.set(ortho_key + '/verticalAperture', 2000) settings.set(ortho_key + '/clippingRange', (20000.0, 10000000.0)) await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 150) self.assertAlmostEqual(persp.GetFStopAttr().Get(), 22) self.assertAlmostEqual(persp.GetHorizontalApertureAttr().Get(), 1234) self.assertAlmostEqual(persp.GetClippingRangeAttr().Get(), Gf.Vec2f(200, 2000)) self.assertFalse(persp.GetVerticalApertureAttr().IsAuthored()) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) self.assertAlmostEqual(top.GetHorizontalApertureAttr().Get(), 1000) self.assertAlmostEqual(top.GetVerticalApertureAttr().Get(), 2000) # Test that the extension.toml default is used self.assertAlmostEqual(top.GetClippingRangeAttr().Get(), Gf.Vec2f(20000.0, 10000000.0)) finally: # Reset now for all other tests settings.destroy_item(perps_key) settings.destroy_item(ortho_key) # viewport_widget.destroy() # del viewport_widget async def __test_camera_target_settings(self, viewport_widget): """Test /app/viewport/defaultCamera/target/distance settings values""" settings = carb.settings.get_settings() # These all have no defaults (as feature is disabled until set) enabled_key = "/app/viewport/defaultCamera/target/distance/enabled" value_key = "/app/viewport/defaultCamera/target/distance/value" unit_key = "/app/viewport/defaultCamera/target/distance/units" async def test_stage_open(filepath: str, expected_coi: Gf.Vec3d): usd_context = await self.open_usd_file(filepath) stage = usd_context.get_stage() await self.wait_n_updates(3) persp_cam = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertTrue(bool(persp_cam.GetPrim().IsValid())) coi_prop = persp_cam.GetPrim().GetProperty('omni:kit:centerOfInterest') self.assertTrue(bool(coi_prop.IsValid())) self.assertAlmostEqual(coi_prop.Get(), expected_coi) async def set_target_distance(value, unit): settings.set(enabled_key, True) settings.set(value_key, value) settings.set(unit_key, unit) await self.wait_n_updates(3) try: await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -1732.0508)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -1732.0508)) await set_target_distance(5, "stage") await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -0.04999)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -50)) await set_target_distance(5, "meters") await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -500)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -0.5)) await set_target_distance(5, 1) await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -5)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -5)) finally: # Make sure to clear the keys for remainig tests settings.destroy_item(enabled_key) settings.destroy_item(value_key) settings.destroy_item(unit_key) async def __test_display_delegate(self, viewport_widget): self.assertIsNotNone(viewport_widget.display_delegate) self.assertTrue(isinstance(viewport_widget.display_delegate, ViewportDisplayDelegate)) def test_set_display_delegate(display_delegate): success = False try: viewport_widget.display_delegate = display_delegate success = True except RuntimeError: pass return success result = test_set_display_delegate(None) self.assertFalse(result) result = test_set_display_delegate(32) self.assertFalse(result) result = test_set_display_delegate(OverlayViewportDisplayDelegate(viewport_widget.viewport_api)) self.assertTrue(result) async def test_ui_driven_resolution(self): """Test ViewportWidget driving the underlying Viewport texture resolution""" import omni.ui await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # Need a Window otherwise the ui size calculations won't run window_flags = omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR style = {"border_width": 0} window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags, padding_x=0, padding_y=0) startup_resolution = TEST_WIDTH * 0.5, TEST_HEIGHT * 0.25 with window.frame: window.frame.set_style(style) viewport_widget = ViewportWidget(resolution=startup_resolution, style=style) await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], startup_resolution[0]) self.assertEqual(current_res[1], startup_resolution[1]) viewport_widget.fill_frame = True await self.wait_n_updates(8) # Should match the ui.Frame which should be filling the ui.Window current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], window.frame.computed_width) self.assertEqual(current_res[1], window.frame.computed_height) viewport_widget.fill_frame = False viewport_widget.expand_viewport = True await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution # Some-what arbitrary numbers from implementation that are know to be correct for 360, 240 ui.Frame self.assertEqual(current_res[0], 180) self.assertEqual(current_res[1], 120) full_resolution = viewport_widget.full_resolution self.assertEqual(full_resolution[0], startup_resolution[0]) self.assertEqual(full_resolution[1], startup_resolution[1]) # Test reversion to no fill or exapnd returns back to the resolution explicitly specified. viewport_widget.fill_frame = False viewport_widget.expand_viewport = False await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], startup_resolution[0]) self.assertEqual(current_res[1], startup_resolution[1]) # Set render resolution to x3 viewport_widget.resolution = (TEST_WIDTH * 2.5, TEST_HEIGHT * 2.5) viewport_widget.expand_viewport = True # Set Window size to x2 two_x_res = TEST_WIDTH * 2, TEST_HEIGHT * 2 window.width, window.height = two_x_res await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], two_x_res[0]) self.assertEqual(current_res[1], two_x_res[1]) viewport_widget.destroy() del viewport_widget window.destroy() del window await self.finalize_test_no_image() async def __test_engine_creation_arguments(self, hydra_engine_options, verify_engine): viewport_widget, window = None, None try: import omni.ui await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # Need a Window otherwise the ui size calculations won't run window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT) startup_resolution = TEST_WIDTH * 0.5, TEST_HEIGHT * 0.25 with window.frame: viewport_widget = ViewportWidget(resolution=startup_resolution, width=TEST_WIDTH, height=TEST_HEIGHT, hydra_engine_options=hydra_engine_options) await self.wait_n_updates(5) await verify_engine(viewport_widget.viewport_api._hydra_texture) finally: if viewport_widget is not None: viewport_widget.destroy() del viewport_widget if window is not None: window.destroy() del window await self.finalize_test_no_image() async def test_engine_creation_default_arguments(self): """Test default engine creation arguments""" hydra_engine_options = {} async def verify_engine(hydra_texture): settings = carb.settings.get_settings() tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate") is_async = settings.get(f"{hydra_texture.get_settings_path()}async") is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency") self.assertEqual(is_async, bool(settings.get("/app/asyncRendering"))) self.assertEqual(is_async_ll, bool(settings.get("/app/asyncRenderingLowLatency"))) self.assertEqual(tick_rate, int(settings.get("/persistent/app/viewport/defaults/tickRate"))) await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine) async def test_engine_creation_forward_arguments(self): """Test forwarding of engine creation arguments""" settings = carb.settings.get_settings() # Make sure the defaults are in a state that overrides from hydra_engine_options can be tested self.assertFalse(bool(settings.get("/app/asyncRendering"))) self.assertFalse(bool(settings.get("/app/asyncRenderingLowLatency"))) self.assertNotEqual(30, int(settings.get("/persistent/app/viewport/defaults/tickRate"))) try: hydra_engine_options = { "is_async": True, "is_async_low_latency": True, "hydra_tick_rate": 30 } async def verify_engine(hydra_texture): tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate") is_async = settings.get(f"{hydra_texture.get_settings_path()}async") is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency") self.assertEqual(is_async, hydra_engine_options.get("is_async")) self.assertEqual(is_async_ll, hydra_engine_options.get("is_async_low_latency")) self.assertEqual(tick_rate, hydra_engine_options.get("hydra_tick_rate")) await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine) finally: settings.set("/app/asyncRendering", False) settings.destroy_item("/app/asyncRenderingLowLatency")
36,413
Python
46.414062
141
0.649411
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_capture.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestCaptureAPI"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.ui.tests.compare_utils import OUTPUTS_DIR, compare, CompareError import omni.usd import omni.ui as ui from omni.kit.widget.viewport import ViewportWidget from omni.kit.widget.viewport.capture import * from omni.kit.test_helpers_gfx.compare_utils import compare as gfx_compare from omni.kit.test.teamcity import teamcity_publish_image_artifact import carb import traceback from pathlib import Path import os from pxr import Usd, UsdRender CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') TEST_WIDTH, TEST_HEIGHT = 360, 240 NUM_DEFAULT_WINDOWS = 0 # XXX: Make this more accessible in compare_utils # def compare_images(image_name, threshold = 10): image1 = OUTPUTS_DIR.joinpath(image_name) image2 = TEST_FILES_DIR.joinpath(image_name) image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image_name).stem}.diffmap.png") gfx_compare(image1, image2, image_diffmap) class TestByteCapture(ByteCapture): def __init__(self, test, *args, **kwargs): super().__init__(*args, **kwargs) self.__test = test self.__complete = False def on_capture_completed(self, buffer, buffer_size, width, height, format): self.__test.assertEqual(width, TEST_WIDTH) self.__test.assertEqual(height, TEST_HEIGHT) self.__test.assertEqual(format, ui.TextureFormat.RGBA8_UNORM) class TestCaptureAPI(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def merged_test_capture_file(self): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_path = str(TEST_FILES_DIR.joinpath('usd/sphere.usda')) image_name = f'sphere.png' image_path = str(OUTPUTS_DIR.joinpath(image_name)) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) vp_window = ui.Window('test_capture_file', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) capture = vp_widget.viewport_api.schedule_capture(FileCapture(image_path)) captured_aovs = await capture.wait_for_result() self.assertEqual(captured_aovs, ['LdrColor']) # Test the frame's metadata is available self.assertIsNotNone(capture.view) self.assertIsNotNone(capture.projection) self.assertEqual(capture.resolution, (TEST_WIDTH, TEST_HEIGHT)) # Test the viewport_handle is also available for usets that self.assertIsNotNone(capture.viewport_handle) compare_images(image_name) vp_widget.destroy() vp_window.destroy() del vp_window async def merged_test_capture_file_with_format(self): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_path = str(TEST_FILES_DIR.joinpath('usd/sphere.usda')) image_name = f'sphere_rle.exr' image_path = str(OUTPUTS_DIR.joinpath(image_name)) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) vp_window = ui.Window('test_capture_file_with_format', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) format_desc = {} format_desc["format"] = "exr" format_desc["compression"] = "rle" capture = vp_widget.viewport_api.schedule_capture(FileCapture(image_path, format_desc=format_desc)) captured_aovs = await capture.wait_for_result() self.assertEqual(captured_aovs, ['LdrColor']) # Test the frame's metadata is available self.assertIsNotNone(capture.view) self.assertIsNotNone(capture.projection) self.assertEqual(capture.resolution, (TEST_WIDTH, TEST_HEIGHT)) # Test the viewport_handle is also available for usets that self.assertIsNotNone(capture.viewport_handle) self.assertIsNotNone(capture.format_desc) # Cannot compare EXR images for testing yet # compare_images(image_name) vp_widget.destroy() vp_window.destroy() del vp_window async def merged_test_capture_bytes_free_func_hdr(self): # 1030: Doesn't have the ability to set render_product_path and this test will fail import omni.hydratexture if not hasattr(omni.hydratexture.IHydraTexture, 'set_render_product_path'): return await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) aov_name = 'HdrColor' image_name = f'cube_{aov_name}.exr' image_path = str(OUTPUTS_DIR.joinpath(image_name)) usd_path = str(TEST_FILES_DIR.joinpath('usd/cube.usda')) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) num_calls = 0 def on_capture_completed(buffer, buffer_size, width, height, format): nonlocal num_calls num_calls = num_calls + 1 self.assertEqual(width, TEST_WIDTH) self.assertEqual(height, TEST_HEIGHT) # Note the RGBA16_SFLOAT format! self.assertEqual(format, ui.TextureFormat.RGBA16_SFLOAT) vp_window = ui.Window('test_capture_bytes_free_func', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) # Edit the RenderProduct to output HdrColor render_product_path = vp_widget.viewport_api.render_product_path if render_product_path[0] != '/': render_product_path = f'/Render/RenderProduct_{render_product_path}' stage = usd_context.get_stage() with Usd.EditContext(stage, stage.GetSessionLayer()): prim = usd_context.get_stage().GetPrimAtPath(render_product_path) self.assertTrue(prim.IsValid()) self.assertTrue(prim.IsA(UsdRender.Product)) product = UsdRender.Product(prim) targets = product.GetOrderedVarsRel().GetForwardedTargets() self.assertEqual(1, len(targets)) prim = usd_context.get_stage().GetPrimAtPath(targets[0]) self.assertTrue(prim.IsValid()) self.assertTrue(prim.IsA(UsdRender.Var)) render_var = UsdRender.Var(prim) value_set = render_var.GetSourceNameAttr().Set(aov_name) self.assertTrue(value_set) # Trigger the texture to update the render, and wait for the change to funnel back to us vp_widget.viewport_api.render_product_path = render_product_path settings_changed = await vp_widget.viewport_api.wait_for_render_settings_change() self.assertTrue(settings_changed) # Now that the settings have changed, so the capture of 'HdrColor' captured_aovs = await vp_widget.viewport_api.schedule_capture(ByteCapture(on_capture_completed, aov_name=aov_name)).wait_for_result() self.assertTrue(aov_name in captured_aovs) # Since we requested one AOV, test that on_capture_completed was only called once # Currently RTX will deliver 'HdrColor' and 'LdrColor' when 'HdrColor' is requested # If that changes these two don't neccessarily need to be tested. self.assertEqual(len(captured_aovs), 1) self.assertEqual(num_calls, 1) captured_aovs = await vp_widget.viewport_api.schedule_capture(FileCapture(image_path, aov_name=aov_name)).wait_for_result() self.assertTrue(aov_name in captured_aovs) # XXX cannot compare EXR # compare_images(image_name) # So test it exists and publish the image self.assertTrue(os.path.exists(image_path)) teamcity_publish_image_artifact(image_path, "results") vp_widget.destroy() vp_window.destroy() del vp_window async def merged_test_capture_bytes_subclass(self): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_path = str(TEST_FILES_DIR.joinpath('usd/cube.usda')) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) capture = TestByteCapture(self) vp_window = ui.Window('test_capture_bytes_subclass', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) vp_widget.viewport_api.schedule_capture(capture) captured_aovs = await capture.wait_for_result() self.assertEqual(captured_aovs, ['LdrColor']) vp_widget.destroy() vp_window.destroy() del vp_window async def test_3_capture_tests_merged_for_linux(self): try: await self.merged_test_capture_file() await self.wait_n_updates(10) await self.merged_test_capture_bytes_free_func_hdr() await self.wait_n_updates(10) await self.merged_test_capture_bytes_subclass() await self.wait_n_updates(10) await self.merged_test_capture_file_with_format() await self.wait_n_updates(10) finally: await self.finalize_test_no_image()
10,923
Python
41.177606
145
0.656596
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_ray_query.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__ = ["TestRayQuery"] from omni.kit.widget.viewport import ViewportWidget import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import omni.usd from pathlib import Path import carb CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') TEST_WIDTH, TEST_HEIGHT = 320, 180 class TestRayQuery(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() await self.linux_gpu_shutdown_workaround() async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''): await self.wait_n_updates(10) omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name)) await self.wait_n_updates(10) async def open_usd_file(self, filename: str, resolved: bool = False): usd_context = omni.usd.get_context() usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename) await usd_context.open_stage_async(usd_path) return usd_context async def __test_ray_query(self, camera_path: str): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) usd_context = await self.open_usd_file('ray_query.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() window_flags = omni.ui.WINDOW_FLAGS_NO_COLLAPSE window_flags |= omni.ui.WINDOW_FLAGS_NO_RESIZE window_flags |= omni.ui.WINDOW_FLAGS_NO_CLOSE window_flags |= omni.ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= omni.ui.WINDOW_FLAGS_NO_TITLE_BAR vp_window, viewport_widget = None, None try: vp_window = omni.ui.Window("Viewport", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags) with vp_window.frame: viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) results = [] def query_completed(*args): results.append(args) viewport_api = viewport_widget.viewport_api viewport_api.camera_path = camera_path # 1:1 conform of render and viewport await self.wait_n_updates(5) viewport_api.request_query((193, 123), query_completed) await self.wait_n_updates(15) # test with half height viewport_api.resolution = TEST_WIDTH, TEST_HEIGHT * 0.5 await self.wait_n_updates(5) viewport_api.request_query((193, 78), query_completed) await self.wait_n_updates(15) # test with half width viewport_api.resolution = TEST_WIDTH * 0.5, TEST_HEIGHT await self.wait_n_updates(5) viewport_api.request_query((96, 106), query_completed) await self.wait_n_updates(15) self.assertEqual(len(results), 3) for args in results: self.assertEqual(args[0], "/World/Xform/FG") # Compare integer in a sane range that must be toward the lower-right corner of the object iworld_pos = [int(v) for v in args[1]] self.assertTrue(iworld_pos[0] >= 46 and iworld_pos[0] <= 50) self.assertTrue(iworld_pos[1] >= -50 and iworld_pos[1] <= -46) self.assertTrue(iworld_pos[2] == 0) finally: if viewport_widget: viewport_widget.destroy() viewport_widget = None if vp_window: vp_window.destroy() vp_window = None await self.finalize_test_no_image() async def test_perspective_ray_query(self): '''Test request_query API with a perpective camera''' await self.__test_ray_query("/World/Xform/Camera") async def test_orthographic_ray_query(self): '''Test request_query API with an orthographic camera''' await self.__test_ray_query("/OmniverseKit_Front")
4,631
Python
39.99115
120
0.638523
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/drop_support.py
import os import asyncio import carb.events import carb.input import omni.appwindow import omni.ui as ui class ExternalDragDrop(): def __init__(self, window_name: str, drag_drop_fn: callable): self._window_name = window_name self._drag_drop_fn = drag_drop_fn # subscribe to external drag/drop events app_window = omni.appwindow.get_default_app_window() self._dropsub = app_window.get_window_drop_event_stream().create_subscription_to_pop( self._on_drag_drop_external, name="ExternalDragDrop event", order=0 ) def destroy(self): self._drag_drop_fn = None self._dropsub = None def get_current_mouse_coords(self): app_window = omni.appwindow.get_default_app_window() input = carb.input.acquire_input_interface() dpi_scale = ui.Workspace.get_dpi_scale() pos_x, pos_y = input.get_mouse_coords_pixel(app_window.get_mouse()) return pos_x / dpi_scale, pos_y / dpi_scale def is_window_hovered(self, pos_x, pos_y, window_name): window = ui.Workspace.get_window(window_name) # if window hasn't been drawn yet docked may not be valid, so check dock_id also if not window or not window.visible or ((window.docked or window.dock_id != 0) and not window.is_selected_in_dock()): return False if (pos_x > window.position_x and pos_y > window.position_y and pos_x < window.position_x + window.width and pos_y < window.position_y + window.height ): return True return False def _on_drag_drop_external(self, e: carb.events.IEvent): # need to wait until next frame as otherwise mouse coords can be wrong async def do_drag_drop(): await omni.kit.app.get_app().next_update_async() mouse_x, mouse_y = self.get_current_mouse_coords() if self.is_window_hovered(mouse_x, mouse_y, self._window_name): self._drag_drop_fn(self, list(e.payload['paths'])) asyncio.ensure_future(do_drag_drop()) def expand_payload(self, payload): new_payload = [] for file_path in payload: if os.path.isdir(file_path): for root, subdirs, files in os.walk(file_path): for file in files: new_payload.append(os.path.join(root, file)) else: new_payload.append(file_path) return new_payload
2,498
Python
37.446153
125
0.609287
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/__init__.py
from .drop_support import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/tests/test_drag_drop.py
import os import unittest import threading import carb import asyncio import omni.kit.test import omni.ui as ui import omni.appwindow import omni.client.utils as clientutils from pathlib import Path from omni.kit import ui_test class TestExternalDragDropUtils(omni.kit.test.AsyncTestCase): async def test_external_drag_drop(self): # new stage await omni.usd.get_context().new_stage_async() await ui_test.human_delay(50) # stage event future_test = asyncio.Future() def on_timeout(): nonlocal future_test future_test.set_result(False) carb.log_error(f"stage event omni.usd.StageEventType.OPENED hasn't been received") timeout_timer = threading.Timer(30.0, on_timeout) def on_stage_event(event): if event.type == int(omni.usd.StageEventType.OPENED): nonlocal timeout_timer timeout_timer.cancel() nonlocal future_test future_test.set_result(True) carb.log_info(f"stage event omni.usd.StageEventType.OPENED received") stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(on_stage_event, name="omni.kit.window.drop_support") timeout_timer.start() # get file path extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) file_path = str(Path(extension_path).joinpath("data/tests/4Lights.usda")).replace("\\", "/") # position mouse await ui_test.find("Viewport").click() await ui_test.human_delay() # simulate drag/drop omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [file_path]}) await ui_test.human_delay(50) # wait for stage event OPENED await future_test await ui_test.human_delay(50) # verify root_layer = omni.usd.get_context().get_stage().GetRootLayer() self.assertTrue(clientutils.equal_urls(root_layer.identifier, file_path))
2,103
Python
34.661016
153
0.646695
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/tests/__init__.py
from .test_drag_drop import *
31
Python
9.666663
29
0.709677
omniverse-code/kit/exts/omni.kit.window.drop_support/docs/README.md
# omni.kit.window.drop_support ## Introduction Library functions to allow drag & drop from outside kit
107
Markdown
12.499998
55
0.757009
omniverse-code/kit/exts/omni.kit.numpy.common/config/extension.toml
[package] title = "Common Types Numpy Bindings" description = "Numpy type bindings for common vector types" readme ="docs/README.md" preview_image = "" version = "0.1.0" [dependencies] "omni.kit.pip_archive" = {} [[python.module]] name = "omni.kit.numpy.common" [python.pipapi] requirements = ["numpy"] [[test]] waiver = "Simple binding extension (carb types to numpy)"
373
TOML
19.777777
59
0.707775
omniverse-code/kit/exts/omni.kit.numpy.common/omni/kit/numpy/common/_numpy_dtypes.pyi
from __future__ import annotations import omni.kit.numpy.common._numpy_dtypes import typing __all__ = [ ]
114
unknown
10.499999
42
0.675439
omniverse-code/kit/exts/omni.kit.numpy.common/omni/kit/numpy/common/__init__.py
__name__ = "Carb Primitive Numpy DTypes" from ._numpy_dtypes import *
71
Python
16.999996
40
0.690141
omniverse-code/kit/exts/omni.kit.numpy.common/docs/README.md
# Usage This extension is used when creating Python Bindings that returns a numpy array of common Carb types (e.g `carb::Float3`). To use this extension, add `"omni.kit.numpy.common" = {}` to the `[dependencies]` section on the `config/extension.toml` file.
261
Markdown
42.66666
126
0.735632
omniverse-code/kit/exts/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.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 from omni.kit.window.popup_dialog import MessageDialog, InputDialog, FormDialog, OptionsDialog, OptionsMenu class DemoApp: def __init__(self): self._window = None self._popups = [] self._cur_popup_index = 0 self._build_ui() def _build_ui(self): window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window("DemoPopup", width=600, height=80, flags=window_flags) with self._window.frame: builders = [ ("Message", self._build_message_popup), ("String Input", self._build_string_input), ("Form Dialog", self._build_form_dialog), ("Options Dialog", self._build_options_dialog), ("Options Menu", self._build_options_menu), ] with ui.VStack(spacing=10): with ui.HStack(height=30): collection = ui.RadioCollection() for i, builder in enumerate(builders): button = ui.RadioButton(text=builder[0], radio_collection=collection, width=120) self._popups.append(builder[1]()) button.set_clicked_fn(lambda i=i, parent=button: self._on_show_popup(i, parent)) ui.Spacer() ui.Spacer() def _build_message_popup(self) -> MessageDialog: #BEGIN-DOC-message-dialog message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." dialog = MessageDialog( title="Message", message=message, ok_handler=lambda dialog: print(f"Message acknowledged"), ) #END-DOC-message-dialog return dialog def _build_string_input(self) -> InputDialog: #BEGIN-DOC-input-dialog dialog = InputDialog( title="String Input", message="Please enter a string value:", pre_label="LDAP Name: ", post_label="@nvidia.com", ok_handler=lambda dialog: print(f"Input accepted: '{dialog.get_value()}'"), ) #END-DOC-input-dialog return dialog def _build_form_dialog(self) -> FormDialog: #BEGIN-DOC-form-dialog field_defs = [ FormDialog.FieldDef("string", "String: ", ui.StringField, "default"), FormDialog.FieldDef("int", "Integer: ", ui.IntField, 1), FormDialog.FieldDef("float", "Float: ", ui.FloatField, 2.0), FormDialog.FieldDef( "tuple", "Tuple: ", lambda **kwargs: ui.MultiFloatField(column_count=3, h_spacing=2, **kwargs), None ), FormDialog.FieldDef("slider", "Slider: ", lambda **kwargs: ui.FloatSlider(min=0, max=10, **kwargs), 3.5), FormDialog.FieldDef("bool", "Boolean: ", ui.CheckBox, True), ] dialog = FormDialog( title="Form Dialog", message="Please enter values for the following fields:", field_defs=field_defs, ok_handler=lambda dialog: print(f"Form accepted: '{dialog.get_values()}'"), ) #END-DOC-form-dialog return dialog def _build_options_dialog(self) -> OptionsDialog: #BEGIN-DOC-options-dialog field_defs = [ OptionsDialog.FieldDef("hard", "Hard place", False), OptionsDialog.FieldDef("harder", "Harder place", True), OptionsDialog.FieldDef("hardest", "Hardest place", False), ] dialog = OptionsDialog( title="Options Dialog", message="Please make your choice:", field_defs=field_defs, width=300, radio_group=True, ok_handler=lambda choice: print(f"Choice: '{dialog.get_choice()}'"), ) #END-DOC-options-dialog return dialog def _build_options_menu(self) -> OptionsMenu: #BEGIN-DOC-options-menu field_defs = [ OptionsMenu.FieldDef("audio", "Audio", None, False), OptionsMenu.FieldDef("materials", "Materials", None, True), OptionsMenu.FieldDef("scripts", "Scripts", None, False), OptionsMenu.FieldDef("textures", "Textures", None, False), OptionsMenu.FieldDef("usd", "USD", None, True), ] menu = OptionsMenu( title="Options Menu", field_defs=field_defs, width=150, value_changed_fn=lambda dialog, name: print(f"Value for '{name}' changed to {dialog.get_value(name)}"), ) #END-DOC-options-menu return menu def _on_show_popup(self, popup_index: int, parent: ui.Widget): self._popups[self._cur_popup_index].hide() self._popups[popup_index].show(offset_x=-1, offset_y=26, parent=parent) self._cur_popup_index = popup_index if __name__ == "__main__": app = DemoApp()
5,387
Python
40.767442
143
0.585112
omniverse-code/kit/exts/omni.kit.window.popup_dialog/config/extension.toml
[package] title = "Simple Popup Dialogs with Input Fields" version = "2.0.16" description = "A variety of simple Popup Dialogs for taking in user inputs" authors = ["NVIDIA"] slackids = ["UQY4RMR3N"] repository = "" keywords = ["kit", "ui"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.window.popup_dialog" [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ] [[python.scriptFolder]] path = "scripts" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", "--/renderer/multiGpu/maxGpuCount=1", "--no-window", ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ] pythonTests.unreliable = [ "*test_ui_layout", # OM-77232 "*test_one_button_layout", # OM-77232 ]
1,019
TOML
20.25
75
0.652601
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/input_dialog.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.kit.app import asyncio from typing import Callable, Any, Optional from .dialog import AbstractDialog, PopupDialog, get_field_value from .style import get_style class InputDialog(PopupDialog): """ A simple popup dialog with an input field and two buttons, OK and Cancel Keyword Args: title (str): Title of popup window. Default None. message (str): Message to display. input_cls (omni.ui.AbstractField): Type of input field specified by class name, e.g. omni.ui.StringField, omni.ui.IntField, omni.ui.CheckBox. Default is omni.ui.StringField. pre_label (str): Text displayed before input field. Default None. post_label (str): Text displayed after input field. Default None. default_value (str): Default value of the input field. warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None. """ def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", input_cls: ui.AbstractField=None, pre_label: str=None, post_label: str=None, default_value: str=None, warning_message: Optional[str]=None ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, modal=True, warning_message=warning_message ) with self._window.frame: with ui.VStack(): self._build_warning_message() self._widget = InputWidget( message=message, input_cls=input_cls or ui.StringField, pre_label=pre_label, post_label=post_label, default_value=default_value) self._build_ok_cancel_buttons() self.hide() def get_value(self) -> Any: """ Returns field value. Returns: Any, e.g. one of [str, int, float, bool] """ if self._widget: return self._widget.get_value() return None def destroy(self): if self._widget: self._widget.destroy() self._widget = None super().destroy() class InputWidget: """ A simple widget with an input field. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): Message to display. input_cls (omni.ui.AbstractField): Class of the input field, e.g. omni.ui.StringField, omni.ui.IntField, omni.ui.CheckBox. Default is omni.ui.StringField. pre_label (str): Text displayed before input field. Default None. post_label (str): Text displayed after input field. Default None. default_value (str): Default value of the input field. """ def __init__(self, message: str = None, input_cls: ui.AbstractField = None, pre_label: str = None, post_label: str = None, default_value: Any = None ): self._input = None self._build_ui(message, input_cls or ui.StringField, pre_label, post_label, default_value) def _build_ui(self, message: str, input_cls: ui.AbstractField, pre_label: str, post_label: str, default_value: Any, ): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=6): if message: ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message") with ui.HStack(height=0): input_width = 100 if pre_label: ui.Label(pre_label, style_type_name_override="Field.Label", name="prefix") input_width -= 30 if post_label: input_width -= 30 self._input = input_cls( width=ui.Percent(input_width), height=20, style_type_name_override="Input" ) if default_value: self._input.model.set_value(default_value) # OM-95817: Wait a frame to make sure it focus correctly async def focus_field(): await omni.kit.app.get_app().next_update_async() if self._input: self._input.focus_keyboard() asyncio.ensure_future(focus_field()) if post_label: ui.Label(post_label, style_type_name_override="Field.Label", name="postfix") def get_value(self) -> Any: """ Returns value of input field. Returns: Any """ if self._input: return get_field_value(self._input) return None def destroy(self): self._input = None self._window = None
5,888
Python
35.80625
121
0.573709
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/message_dialog.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 from typing import Callable, Optional from .dialog import AbstractDialog, PopupDialog from .style import get_style class MessageDialog(PopupDialog): """ This simplest of all popup dialogs displays a confirmation message before executing an action. Keyword Args: title (str): Title of popup window. Default None. message (str): The displayed message. Default ''. disable_cancel_button (bool): If True, then don't display 'Cancel' button. Default False. warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None. """ def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str="", title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", disable_okay_button: bool=False, disable_cancel_button: bool=False, warning_message: Optional[str]=None, ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, modal=True, warning_message=warning_message, ) with self._window.frame: with ui.VStack(): self._widget = MessageWidget(message) self._build_warning_message() self._build_ok_cancel_buttons(disable_okay_button=disable_okay_button, disable_cancel_button=disable_cancel_button) self.hide() def set_message(self, message: str): """ Updates the message string. Args: message (str): The message string. """ if self._widget: self._widget.set_message(message) def destroy(self): if self._widget: self._widget.destroy() self._widget = None super().destroy() class MessageWidget: """ This widget displays a custom message. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): The message string """ def __init__(self, message: str = ""): self._message_label = None self._build_ui(message) def _build_ui(self, message: str): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=6): with ui.HStack(height=0): self._message_label = ui.Label(message, word_wrap=True, style_type_name_override="Message") def set_message(self, message: str): """ Updates the message string. Args: message (str): The message string. """ self._message_label.text = message def destroy(self): self._message_label = None
3,552
Python
31.898148
131
0.619088
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/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 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}") def get_style(): if THEME == "NvidiaLight": style = { "Button": {"background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF}, "Button.Label": {"color": 0xFF535354}, "Dialog": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin_width": 6}, "Label": {"background_color": 0xFFC9C9C9, "color": 0xFF535354}, "Input": { "background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF, "color": 0xFF535354, "alignment": ui.Alignment.LEFT_CENTER, }, "Rectangle": {"background_color": 0xFFC9C9C9, "border_radius": 3}, "Background": {"background_color": 0xFFE0E0E0, "border_radius": 2, "border_width": 0.5, "border_color": 0x55ADAC9F}, "Background::header": {"background_color": 0xFF535354, "corner_flag": ui.CornerFlag.TOP, "margin": 0}, "Dialog": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 10}, "Message": { "background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 0, "alignment": ui.Alignment.LEFT_CENTER, "margin": 0, }, "Button": {"background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF, "margin": 0}, "Button.Label": {"color": 0xFF535354}, "Field": {"background_color": 0xFF535354, "color": 0xFFD6D6D6}, "Field:pressed": {"background_color": 0xFF535354, "color": 0xFFD6D6D6}, "Field:selected": {"background_color": 0xFFBEBBAE, "color": 0xFFD6D6D6}, "Field.Label": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 0}, "Field.Label::title": {"color": 0xFFD6D6D6}, "Field.Label::prefix": {"alignment": ui.Alignment.RIGHT_CENTER}, "Field.Label::postfix": {"alignment": ui.Alignment.LEFT_CENTER}, "Field.Label::reset_all": {"color": 0xFFB0703B, "alignment": ui.Alignment.RIGHT_CENTER}, "Input": { "background_color": 0xFF535354, "color": 0xFFD6D6D6, "alignment": ui.Alignment.LEFT_CENTER, "margin_height": 0, }, "Menu.Item": {"margin_width": 6, "margin_height": 2}, "Menu.Header": {"margin": 6}, "Menu.CheckBox": {"background_color": 0xFF535354, "color": 0xFFD6D6D6}, "Menu.Separator": {"color": 0x889E9E9E}, "Options.Item": {"margin_width": 6, "margin_height": 0}, "Options.CheckBox": {"background_color": 0x0, "color": 0xFF23211F}, "Options.RadioButton": {"background_color": 0x0, "color": 0xFF9E9E9E}, "Rectangle.Warning": {"background_color": 0x440000FF, "border_radius": 3, "margin": 10}, } else: style = { "BorderedBackground": {"background_color": 0x0, "border_width": .5, "border_color": 0x55ADAC9F}, "Background": {"background_color": 0x0}, "Background::header": {"background_color": 0xFF23211F, "corner_flag": ui.CornerFlag.TOP, "margin": 0}, "Dialog": {"background_color": 0x0, "color": 0xFF9E9E9E, "margin": 10}, "Message": { "background_color": 0x0, "color": 0xFF9E9E9E, "margin": 0, "alignment": ui.Alignment.LEFT_CENTER, "margin": 0, }, "Button": {"background_color": 0xFF23211F, "selected_color": 0xFF8A8777, "margin": 0}, "Button.Label": {"color": 0xFF9E9E9E}, "Field.Label": {"background_color": 0x0, "color": 0xFF9E9E9E, "margin": 0}, "Field.Label::prefix": {"alignment": ui.Alignment.RIGHT_CENTER}, "Field.Label::postfix": {"alignment": ui.Alignment.LEFT_CENTER}, "Field.Label::reset_all": {"color": 0xFFB0703B, "alignment": ui.Alignment.RIGHT_CENTER}, "Input": { "background_color": 0xCC23211F, "color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER, "margin_height": 0, }, "Menu.Item": {"margin_width": 6, "margin_height": 2}, "Menu.Header": {"margin": 6}, "Menu.CheckBox": {"background_color": 0xDD9E9E9E, "color": 0xFF23211F}, "Menu.Separator": {"color": 0x889E9E9E}, "Options.Item": {"margin_width": 6, "margin_height": 0}, "Options.CheckBox": {"background_color": 0xDD9E9E9E, "color": 0xFF23211F}, "Options.RadioButton": {"background_color": 0x0, "color": 0xFF9E9E9E}, "Rectangle.Warning": {"background_color": 0x440000FF, "border_radius": 3, "margin": 10}, } return style
5,578
Python
51.140186
128
0.573682
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """ A set of simple popup dialogs with optional input fields and two buttons, OK and Cancel. Example: .. code-block:: python dialog = InputDialog( width=450, pre_label="prefix", post_label="postfix", ok_handler=on_okay, cancel_handler=on_cancel, ) """ __all__ = [ 'MessageDialog', 'MessageWidget', 'InputDialog', 'InputWidget', 'FormDialog', 'FormWidget', 'OptionsDialog', 'OptionsWidget', 'OptionsMenu', 'OptionsMenuWidget', 'PopupDialog' ] from .message_dialog import MessageDialog, MessageWidget from .input_dialog import InputDialog, InputWidget from .form_dialog import FormDialog, FormWidget from .options_dialog import OptionsDialog, OptionsWidget from .options_menu import OptionsMenu, OptionsMenuWidget from .dialog import PopupDialog
1,255
Python
30.399999
88
0.738645
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/dialog.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 carb.input import omni.ui as ui from typing import Callable, Union, Optional from .style import get_style class AbstractDialog: pass class PopupDialog(AbstractDialog): """ Base class for a simple popup dialog with two primary buttons, OK and Cancel.""" WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", hide_title_bar: bool=False, modal: bool=False, warning_message: Optional[str]=None, ): """ Inherited args from the base class. Keyword Args: width (int): Window width. Default 400. title (str): Title to display. Default None. ok_handler (Callable): Function to invoke when Ok button clicked. Function signature: void okay_handler(dialog: PopupDialog) cancel_handler (Callable): Function to invoke when Cancel button clicked. Function signature: void cancel_handler(dialog: PopupDialog) ok_label (str): Alternative text to display on 'Accept' button. Default 'Ok'. cancel_label (str): Alternative text to display on 'Cancel' button. Default 'Cancel'. warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None. parent (omni.ui.Widget): OBSOLETE. """ super().__init__() self._title = title self._click_okay_handler = ok_handler self._click_cancel_handler = cancel_handler self._okay_label = ok_label self._okay_button = None self._cancel_label = cancel_label self._cancel_button = None self._warning_message = warning_message self._modal = modal self._width = width self._hide_title_bar = hide_title_bar self._key_functions = { int(carb.input.KeyboardInput.ENTER): self._on_okay, int(carb.input.KeyboardInput.ESCAPE): self._on_cancel } self._build_window() def __del__(self): self.destroy() def show(self, offset_x: int = 0, offset_y: int = 0, parent: ui.Widget = None, recreate_window: bool = False): """ Shows this dialog, optionally offset from the parent widget, if any. Keyword Args: offset_x (int): X offset. Default 0. offset_y (int): Y offset. Default 0. parent (ui.Widget): Offset from this parent widget. Default None. recreate_window (bool): Recreate popup window. Default False. """ if recreate_window: # OM-42020: Always recreate window. # Recreate to follow the parent window type (external window or main window) to make position right # TODO: Only recreate when parent window external status changed. But there is no such notification now. self._window = None self._build_window() if parent: self._window.position_x = parent.screen_position_x + offset_x self._window.position_y = parent.screen_position_y + offset_y elif offset_x != 0 or offset_y != 0: self._window.position_x = offset_x self._window.position_y = offset_y self._window.set_key_pressed_fn(self._on_key_pressed) self._window.visible = True def hide(self): """Hides this dialog.""" self._window.visible = False @property def position_x(self): return self._window.position_x @property def position_y(self): return self._window.position_y @property def window(self): return self._window def _build_window(self): window_flags = self.WINDOW_FLAGS if not self._title or self._hide_title_bar: window_flags |= ui.WINDOW_FLAGS_NO_TITLE_BAR if self._modal: window_flags |= ui.WINDOW_FLAGS_MODAL self._window = ui.Window(self._title or "", width=self._width, height=0, flags=window_flags) self._build_widgets() def _build_widgets(self): pass def _cancel_handler(self, dialog): self.hide() def _ok_handler(self, dialog): pass def _build_ok_cancel_buttons(self, disable_okay_button: bool = False, disable_cancel_button: bool = False): if disable_okay_button and disable_cancel_button: return with ui.HStack(height=20, spacing=4): ui.Spacer() if not disable_okay_button: self._okay_button = ui.Button(self._okay_label, width=100, clicked_fn=self._on_okay) if not disable_cancel_button: self._cancel_button = ui.Button(self._cancel_label, width=100, clicked_fn=self._on_cancel) ui.Spacer() def _build_warning_message(self, glyph_width=50, glyph_height=100): if not self._warning_message: return with ui.ZStack(style=get_style(), height=0): with ui.HStack(style={"margin": 15}): ui.Image( "resources/glyphs/Warning_Log.svg", width=glyph_width, height=glyph_height, alignment=ui.Alignment.CENTER ) ui.Label(self._warning_message, word_wrap=True, style_type_name_override="Message") ui.Rectangle(style_type_name_override="Rectangle.Warning") def _on_okay(self): if self._click_okay_handler: self._click_okay_handler(self) def _on_cancel(self): if self._click_cancel_handler: self._click_cancel_handler(self) else: self.hide() def _on_key_pressed(self, key, mod, pressed): if not pressed: return func = self._key_functions.get(key) if func and mod in (0, ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD): func() def set_okay_clicked_fn(self, ok_handler: Callable[[AbstractDialog], None]): """ Sets function to invoke when Okay button is clicked. Args: ok_handler (Callable): Callback with signature: void okay_handler(dialog: PopupDialog) """ self._click_okay_handler = ok_handler def set_cancel_clicked_fn(self, cancel_handler: Callable[[AbstractDialog], None]): """ Sets function to invoke when Cancel button is clicked. Args: cancel_handler (Callable): Callback with signature: void cancel_handler(dialog: PopupDialog) """ self._click_cancel_handler = cancel_handler def destroy(self): self._window = None self._click_okay_handler = None self._click_cancel_handler = None self._key_functions = None self._okay_button = None self._cancel_button = None def get_field_value(field: ui.AbstractField) -> Union[str, int, float, bool]: if not field: return None if isinstance(field, ui.StringField): return field.model.get_value_as_string() elif type(field) in [ui.IntField, ui.IntDrag, ui.IntSlider]: return field.model.get_value_as_int() elif type(field) in [ui.FloatField, ui.FloatDrag, ui.FloatSlider]: return field.model.get_value_as_float() elif isinstance(field, ui.CheckBox): return field.model.get_value_as_bool() else: # TODO: Retrieve values for MultiField return None
8,192
Python
34.777292
125
0.613403
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/options_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from typing import List, Dict, Callable from collections import namedtuple from .dialog import AbstractDialog, PopupDialog from .options_dialog import OptionsWidget from .style import get_style class OptionsMenu(PopupDialog): """ A simple checkbox menu with a set of options Keyword Args: title (str): Title of this menu. Default None. field_defs ([OptionsMenu.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. Note: OptionsMenu.FieldDef: A namedtuple of (name, label, glyph, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", None, True). """ FieldDef = namedtuple("OptionsMenuFieldDef", "name label glyph default") def __init__( self, width: int=400, parent: ui.Widget=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", field_defs: List[FieldDef]=None, value_changed_fn: Callable=None, ): self._widget = OptionsMenuWidget(title, field_defs, value_changed_fn, build_ui=False) super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, hide_title_bar=True, ) def get_values(self) -> dict: """ Returns all values in a dictionary. Returns: dict """ if self._widget: return self._widget.get_values() return {} def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if self._widget: return self._widget.get_value(name) return False def set_value(self, name: str, value: bool): """ Sets the value of the named field. Args: name (str): Name of the field. value (bool): New value """ if self._widget: self._widget.set_value(name, value) return None def reset_values(self): """Resets all values to their defaults.""" if self._widget: self._widget.reset_values() return None def destroy(self): """Destructor""" if self._widget: self._widget.destroy() self._widget = None super().destroy() def _build_widgets(self): with self._window.frame: with ui.VStack(): self._widget.build_ui() self.hide() class OptionsMenuWidget: """ A simple checkbox widget with a set of options. As opposed to the menu class, the widget can be combined with other widget types in the same window. Keyword Args: title (str): Title of this menu. Default None. field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. build_ui (bool): Build ui when created. Note: OptionsMenu.FieldDef: A namedtuple of (name, label, glyph, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", None, True). """ def __init__(self, title: str = None, field_defs: List[OptionsMenu.FieldDef] = [], value_changed_fn: Callable = None, build_ui: bool = True, ): self._field_defs = field_defs self._field_models: Dict[str, ui.AbstractValueModel] = {} for field in field_defs: self._field_models[field.name] = ui.SimpleBoolModel(field.default) self._fields: Dict[str, ui.Widget] = {} self._title = title self._value_changed_fn = value_changed_fn if build_ui: self.build_ui() def build_ui(self): with ui.ZStack(height=0, style=get_style()): ui.Rectangle(style_type_name_override="BorderedBackground") with ui.VStack(): with ui.ZStack(height=0): ui.Rectangle(name="header", style_type_name_override="Background") with ui.HStack(style_type_name_override="Menu.Header"): if self._title: ui.Label(self._title, width=0, name="title", style_type_name_override="Field.Label") ui.Spacer() label = ui.Label( "Reset All", width=0, name="reset_all", style_type_name_override="Field.Label" ) ui.Spacer(width=6) label.set_mouse_pressed_fn(lambda x, y, b, _: self.reset_values()) ui.Spacer(height=4) for field_def in self._field_defs: with ui.HStack(height=20, style_type_name_override="Menu.Item"): check_box = ui.CheckBox(model=self._field_models[field_def.name], width=20, style_type_name_override="Menu.CheckBox") # check_box.model.set_value(field_def.default) check_box.model.add_value_changed_fn( lambda _, name=field_def.name: self._value_changed_fn(self, name) ) ui.Spacer(width=2) ui.Label(field_def.label, width=0, style_type_name_override="Field.Label") self._fields[field_def.name] = check_box ui.Spacer(height=4) def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if name and name in self._field_models: model = self._field_models[name] return model.get_value_as_bool() return False def get_values(self) -> dict: """ Returns all values in a dictionary. Returns: dict """ options = {} for name, model in self._field_models.items(): options[name] = model.get_value_as_bool() return options def set_value(self, name: str, value: bool): """ Sets the value of the named field. Args: name (str): Name of the field. value (bool): New value """ if name and name in self._field_models: model = self._field_models[name] model.set_value(value) def reset_values(self): """Resets all values to their defaults.""" for field_def in self._field_defs: model = self._field_models[field_def.name] model.set_value(field_def.default) def destroy(self): self._field_defs = None self._fields.clear() self._field_models.clear()
7,633
Python
32.191304
141
0.562688
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/options_dialog.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 from typing import List, Dict, Callable, Optional from collections import namedtuple from .dialog import AbstractDialog, PopupDialog from .style import get_style, ICON_PATH class OptionsDialog(PopupDialog): """ A simple checkbox dialog with a set options and two buttons, OK and Cancel Keyword Args: title (str): Title of popup window. Default None. message (str): Message string. field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. radio_group (bool): If True, then only one option can be selected at a time. Note: OptionsDialog.FieldDef: A namedtuple of (name, label, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", True). """ FieldDef = namedtuple("OptionsDialogFieldDef", "name label default") def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", field_defs: List[FieldDef]=None, value_changed_fn: Callable=None, radio_group: bool=False, ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, hide_title_bar=True, modal=True ) with self._window.frame: with ui.VStack(): self._widget = OptionsWidget(message, field_defs, value_changed_fn, radio_group) self._build_ok_cancel_buttons() self.hide() def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if self._widget: return self._widget.get_value(name) return None def get_values(self) -> Dict: """ Returns all values in a dictionary. Returns: Dict """ if self._widget: return self._widget.get_values() return {} def get_choice(self) -> str: """ Returns name of chosen option. Returns: str """ if self._widget: return self._widget.get_choice() return None def destroy(self): if self._widget: self._widget.destroy() self._widget = None super().destroy() class OptionsWidget: """ A simple checkbox widget with a set options. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): Message string. field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. radio_group (bool): If True, then only one option can be selected at a time. Note: OptionsDialog.FieldDef: A namedtuple of (name, label, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", True). """ def __init__(self, message: str = None, field_defs: List[OptionsDialog.FieldDef] = [], value_changed_fn: Callable = None, radio_group: bool = False ): self._field_defs = field_defs self._radio_group = ui.RadioCollection() if radio_group else None self._fields: Dict[str, ui.Widget] = {} self._build_ui(message, field_defs, value_changed_fn, self._radio_group) def _build_ui(self, message: str, field_defs: List[OptionsDialog.FieldDef], value_changed_fn: Callable, radio_group: Optional[ui.RadioCollection]): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=0): if message: ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message") for field_def in field_defs: with ui.HStack(): ui.Spacer(width=30) with ui.HStack(height=20, style_type_name_override="Options.Item"): if radio_group: icon_style = { "image_url": f"{ICON_PATH}/radio_off.svg", ":checked": {"image_url": f"{ICON_PATH}/radio_on.svg"}, } field = ui.RadioButton( radio_collection=radio_group, width=26, height=26, style=icon_style, style_type_name_override="Options.RadioButton", ) else: field = ui.CheckBox(width=20, style_type_name_override="Options.CheckBox") field.model.set_value(field_def.default) ui.Spacer(width=2) ui.Label(field_def.label, width=0, style_type_name_override="Field.Label") self._fields[field_def.name] = field ui.Spacer() #ui.Spacer(height=4) def get_values(self) -> dict: """ Returns all values in a dictionary. Returns: dict """ options = {} for name, field in self._fields.items(): options[name] = field.checked if isinstance(field, ui.RadioButton) else field.model.get_value_as_bool() return options def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if name and name in self._fields: field = self._fields[name] return field.checked if isinstance(field, ui.RadioButton) else field.model.get_value_as_bool() return None def get_choice(self) -> str: """ Returns name of chosen option. Returns: str """ if self._radio_group: choice = self._radio_group.model.get_value_as_int() return self._field_defs[choice].name return None def destroy(self): self._field_defs = None self._fields.clear() self._radio_group = None
7,428
Python
33.235023
151
0.551158
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/form_dialog.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. # __all__ = ['FormDialog', 'FormWidget'] from omni.kit.async_engine import run_coroutine import omni.ui as ui import asyncio from typing import List, Union, Callable from collections import namedtuple from .dialog import AbstractDialog, PopupDialog, get_field_value from .style import get_style class FormDialog(PopupDialog): """ A simple popup dialog with a set of input fields and two buttons, OK and Cancel Keyword Args: title (str): Title of popup window. Default None. message (str): Message string. field_defs ([FormDialog.FieldDef]): List of FieldDefs. Default []. input_width (int): OBSOLETE. Note: FormDialog.FieldDef: A namedtuple of (name, label, type, default value) for describing the input field, e.g. FormDialog.FieldDef("name", "Name: ", omni.ui.StringField, "Bob"). """ FieldDef = namedtuple("FormDialogFieldDef", "name label type default focused", defaults=[False]) def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", field_defs: List[FieldDef]=None, input_width: int=250 # OBSOLETE ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, modal=True ) with self._window.frame: with ui.VStack(style=get_style(), style_type_name_override="Dialog"): self._widget = FormWidget(message, field_defs) self._build_ok_cancel_buttons() self.hide() def show(self, offset_x: int = 0, offset_y: int = 0, parent: ui.Widget = None): """ Shows this dialog, optionally offset from the parent widget, if any. Keyword Args: offset_x (int): X offset. Default 0. offset_y (int): Y offset. Default 0. parent (ui.Widget): Offset from this parent widget. Default None. """ # focus on show self._widget.focus() super().show(offset_x=offset_x, offset_y=offset_y, parent=parent) def get_field(self, name: str) -> ui.AbstractField: """ Returns widget corresponding to named field. Args: name (str): Name of the field. Returns: omni.ui.AbstractField """ if self._widget: return self._widget.get_field(name) return None def get_value(self, name: str) -> Union[str, int, float, bool]: """ Returns value of the named field. Args: name (str): Name of the field. Returns: Union[str, int, float, bool] Note: Doesn't currently return MultiFields correctly. """ if self._widget: return self._widget.get_value(name) return None def get_values(self) -> dict: """ Returns all values in a dict. Args: name (str): Name of the field. Returns: dict Note: Doesn't currently return MultiFields correctly. """ if self._widget: return self._widget.get_values() return {} def reset_values(self): """Resets all values to their defaults.""" if self._widget: return self._widget.reset_values() def destroy(self): """Destructor""" if self._widget: self._widget.destroy() self._widget = None super().destroy() class FormWidget: """ A simple form widget with a set of input fields. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): Message string. field_defs ([FormDialog.FieldDef]): List of FieldDefs. Default []. Note: FormDialog.FieldDef: A namedtuple of (name, label, type, default value) for describing the input field, e.g. FormDialog.FieldDef("name", "Name: ", omni.ui.StringField, "Bob"). """ def __init__(self, message: str = None, field_defs: List[FormDialog.FieldDef] = []): self._field_defs = field_defs self._fields = {} self._build_ui(message, field_defs) def _build_ui(self, message: str, field_defs: List[FormDialog.FieldDef]): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=6): if message: ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message") for field_def in field_defs: with ui.HStack(height=0): ui.Label(field_def.label, style_type_name_override="Field.Label", name="prefix") field = field_def.type(width=ui.Percent(70), height=20, style_type_name_override="Field") if "set_value" in dir(field.model): field.model.set_value(field_def.default) self._fields[field_def.name] = field def focus(self) -> None: """Focus fields for the current widget.""" # had to delay focus keyboard for one frame async def delay_focus(field): import omni.kit.app await omni.kit.app.get_app().next_update_async() field.focus_keyboard() # OM-80009: Add ability to focus an input field for form dialog; # When multiple fields are set to focused, then the last field will be the # actual focused field. for field_def in self._field_defs: if field_def.focused: field = self._fields[field_def.name] run_coroutine(delay_focus(field)) def get_field(self, name: str) -> ui.AbstractField: """ Returns widget corresponding to named field. Args: name (str): Name of the field. Returns: omni.ui.AbstractField """ if name and name in self._fields: return self._fields[name] return None def get_value(self, name: str) -> Union[str, int, float, bool]: """ Returns value of the named field. Args: name (str): Name of the field. Returns: Union[str, int, float, bool] Note: Doesn't currently return MultiFields correctly. """ if name and name in self._fields: field = self._fields[name] return get_field_value(field) return None def get_values(self) -> dict: """ Returns all values in a dict. Args: name (str): Name of the field. Returns: dict Note: Doesn't currently return MultiFields correctly. """ return {name: get_field_value(field) for name, field in self._fields.items()} def reset_values(self): """Resets all values to their defaults.""" for field_def in self._field_defs: if field_def.name in self._fields: field = self._fields[field_def.name] if "set_value" in dir(field.model): field.model.set_value(field_def.default) def destroy(self): self._field_defs = None self._fields.clear()
8,184
Python
30.972656
113
0.577713
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_input_dialog.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. ## import omni.kit.test import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..input_dialog import InputDialog, InputWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestInputDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: InputWidget( message="Please enter a username:", pre_label="LDAP Name: ", post_label="@nvidia.com", default_value="user", ) await omni.kit.app.get_app().next_update_async() # Add a threshold for the focused field is not stable. await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="input_dialog.png", threshold=25) async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = InputDialog( message="Please enter a string value:", pre_label="LDAP Name: ", post_label="@nvidia.com", ok_handler=mock_okay_handler, ) under_test.show() under_test._on_okay() await omni.kit.app.get_app().next_update_async() mock_okay_handler.assert_called_once() async def test_get_field_value(self): """Test that get_value returns the value of the input field""" under_test = InputDialog( message="Please enter a string value:", pre_label="LDAP Name: ", post_label="@nvidia.com", default_value="user", ) self.assertEqual("user", under_test.get_value())
2,503
Python
36.373134
119
0.644826
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_menu.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. ## import omni.kit.test import unittest import asyncio import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..options_menu import OptionsMenu, OptionsMenuWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestOptionsMenu(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ OptionsMenu.FieldDef("audio", "Audio", None, False), OptionsMenu.FieldDef("materials", "Materials", None, True), OptionsMenu.FieldDef("scripts", "Scripts", None, False), OptionsMenu.FieldDef("textures", "Textures", None, False), OptionsMenu.FieldDef("usd", "USD", None, True), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: OptionsMenuWidget( title="Options", field_defs=self._field_defs, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_menu.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_value_changed_fn = Mock() under_test = OptionsMenu( title="Options", field_defs=self._field_defs, value_changed_fn=mock_value_changed_fn, ) under_test.show() self.assertEqual(under_test.get_value('usd'), True) under_test.destroy()
2,415
Python
37.349206
105
0.662112
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_message_dialog.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. ## import omni.kit.test import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..message_dialog import MessageWidget, MessageDialog CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestMessageDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_message_widget(self): """Testing the look of message widget""" window = await self.create_test_window() with window.frame: under_test = MessageWidget() under_test.set_message(self._message) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="message_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_messgae_dialog(self): """Testing the look of message dialog""" mock_cancel_handler = Mock() under_test = MessageDialog(title="Message", cancel_handler=mock_cancel_handler,) under_test.set_message("Hello World") under_test.show() await omni.kit.app.get_app().next_update_async() under_test._on_cancel() mock_cancel_handler.assert_called_once() under_test.destroy()
2,155
Python
41.274509
149
0.703016
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_form_dialog.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. ## import omni.kit.test import omni.ui as ui import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..form_dialog import FormDialog, FormWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestFormDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ FormDialog.FieldDef("string", "String: ", ui.StringField, "default"), FormDialog.FieldDef("int", "Integer: ", ui.IntField, 1), FormDialog.FieldDef("float", "Float: ", ui.FloatField, 2.0), FormDialog.FieldDef( "tuple", "Tuple: ", lambda **kwargs: ui.MultiFloatField(column_count=3, h_spacing=2, **kwargs), None ), FormDialog.FieldDef("slider", "Slider: ", lambda **kwargs: ui.FloatSlider(min=0, max=10, **kwargs), 3.5), FormDialog.FieldDef("bool", "Boolean: ", ui.CheckBox, True), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: FormWidget( message="Test fields:", field_defs=self._field_defs, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="form_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ok_handler=mock_okay_handler, ) under_test.show() under_test._on_okay() await omni.kit.app.get_app().next_update_async() mock_okay_handler.assert_called_once() under_test.destroy() async def test_get_field_value(self): """Test that get_value returns the value of the named field""" under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ) for field in self._field_defs: name, label, _, default_value, focused = field self.assertEqual(default_value, under_test.get_value(name)) under_test.destroy() async def test_reset_dialog_value(self): """Test reset dialog value""" under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ) string_field = under_test.get_field("string") string_field.model.set_value("test") self.assertEqual(under_test.get_value("string"), "test") under_test.reset_values() self.assertEqual(under_test.get_value("string"), "default") under_test.destroy()
3,641
Python
39.021978
118
0.629223
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_dialog.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. ## import omni.kit.test import unittest import asyncio import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..options_dialog import OptionsDialog, OptionsWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestOptionsDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ OptionsDialog.FieldDef("hard", "Hard place", False), OptionsDialog.FieldDef("harder", "Harder place", True), OptionsDialog.FieldDef("hardest", "Hardest place", False), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: OptionsWidget( message="Please make your choice:", field_defs=self._field_defs, radio_group=False, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = OptionsDialog( message="Please make your choice:", field_defs=self._field_defs, width=300, radio_group=False, ok_handler=mock_okay_handler, ) under_test.show() await asyncio.sleep(1) under_test._on_okay() mock_okay_handler.assert_called_once() # TODO: # self.assertEqual(under_test.get_choice(), 'harder') under_test.destroy()
2,523
Python
36.117647
107
0.653983
omniverse-code/kit/exts/omni.kit.window.popup_dialog/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [2.0.16] - 2023-01-31 ### Fixed - OM-79359: Ensure imput dialog auto focus when it has default value ## [2.0.15] - 2022-12-12 ### Fixed - Reverts popup flag, otherwise cannot click away the dialog ## [2.0.14] - 2022-12-08 ### Fixed - Removes popup flag from core dialog, which causes drawing issues when dialogs collide ## [2.0.13] - 2022-11-30 ### Fixed - Centre the okay or cancel button when either or both are enabled. ## [2.0.12] - 2022-11-17 ### Changes - Updated doc. ## [2.0.11] - 2022-11-04 ### Changes - Added warning_message kwarg to base dialog class, and ui build for the warning message. ## [2.0.10] - 2022-08-23 ### Changes - Added set_cancel_clicked_fn to base dialog class. ## [2.0.9] - 2022-07-06 ### Changes - Added title bar. ## [2.0.8] - 2022-05-26 ### Changes - Updated styling ## [2.0.7] - 2022-04-06 ### Changes - Fixes Filepicker delete items dialog. ## [2.0.6] - 2022-03-31 ### Changes - Added unittests and created separate widgets and dialogs. ## [2.0.5] - 2021-11-01 ### Changes - Added set_value method to programmatically set an options menu value. ## [2.0.4] - 2021-11-01 ### Changes - Add method to MessageDialog for updating the message text. ## [2.0.3] - 2021-09-07 ### Changes - Makes all dialog windows modal. - Option to hide Okay button. - Better control of window placement when showing it. ## [2.0.2] - 2021-06-29 ### Changes - Binds ENTER key to Okay button, and ESC key to Cancel button. ## [2.0.1] - 2021-06-07 ### Changes - More thorough destruction of class instances upon shutdown. ## [2.0.0] - 2021-05-05 ### Changes - Update `__init__` of the popup dialog to be explicit in supported arguments - Renamed click_okay_handler and click_cancel_handler to ok_handler and cancel_handler - Added support for `Enter` and `Esc` keys. - Renamed okay_label to ok_label ## [1.0.1] - 2021-02-10 ### Changes - Updated StyleUI handling ## [1.0.0] - 2020-10-29 ### Added - Ported OptionsMenu from content browser - New OptionsDialog derived from OptionsMenu ## [0.1.0] - 2020-09-24 ### Added - Initial commit to master.
2,172
Markdown
23.41573
89
0.680018
omniverse-code/kit/exts/omni.kit.window.popup_dialog/docs/Overview.md
# Overview A set of simple Popup Dialogs for passing user inputs. All of these dialogs subclass from the base PopupDialog, which provides OK and Cancel buttons. The user is able to re-label these buttons as well as associate callbacks that execute upon being clicked. Why you should use the dialogs in this extension: * Avoid duplicating UI code that you then have to maintain. * Re-use dialogs that have standard look and feel to keep a consistent experience across the app. * Inherit future improvements. ## Form Dialog A form dialog can display a mixed set of input types. ![](form_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-form-dialog end-before: END-DOC-form-dialog dedent: 8 --- ``` ## Input Dialog An input dialog allows one input field. ![](input_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-input-dialog end-before: END-DOC-input-dialog dedent: 8 --- ``` ## Message Dialog A message dialog is the simplest of all popup dialogs; it displays a confirmation message before executing some action. ![](message_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-message-dialog end-before: END-DOC-message-dialog dedent: 8 --- ``` ## Options Dialog An options dialog displays a set of checkboxes; the choices optionally belong to a radio group - meaning only one choice is active at a given time. ![](options_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-options-dialog end-before: END-DOC-options-dialog dedent: 8 --- ``` ## Options Menu Similar to the options dialog, but displayed in menu form. ![](options_menu.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-options-menu end-before: END-DOC-options-menu dedent: 8 --- ``` ## Demo app A complete demo, that includes the code snippets above, is included with this extension at "scripts/demo_popup_dialog.py".
2,456
Markdown
23.326732
122
0.739821
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/config/extension.toml
[package] title = "Channel Manager" description = "The channel manager provides universal way to create/manage Omniverse Channel without caring about the state management but only message exchange between clients." version = "1.0.9" changelog = "docs/CHANGELOG.md" readme = "docs/README.md" category = "Utility" feature = true # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] [dependencies] "omni.client" = {} [[python.module]] name = "omni.kit.collaboration.channel_manager" [[test]] args = [ "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] pyCoverageOmit = [ "omni/kit/collaboration/channel_manager/tests/channel_manager_tests.py", "omni/kit/collaboration/channel_manager/tests/test_base.py", "omni/kit/collaboration/channel_manager/manager.py", "omni/kit/collaboration/channel_manager/extension.py", ] dependencies = [] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = [] [settings] exts."omni.kit.collaboration.channel_manager".enable_server_tests = false exts."omni.kit.collaboration.channel_manager".from_app = "Kit"
1,577
TOML
29.346153
178
0.740013
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ChannelManagerExtension", "join_channel_async"] import carb import omni.ext from .manager import Channel, ChannelManager _global_instance = None class ChannelManagerExtension(omni.ext.IExt): # pragma: no cover def on_startup(self): global _global_instance _global_instance = self self._channel_manager = ChannelManager() self._channel_manager.on_startup() def on_shutdown(self): global _global_instance _global_instance = None self._channel_manager.on_shutdown() self._channel_manager = None async def join_channel_async(self, url, get_users_only) -> Channel: channel = await self._channel_manager.join_channel_async(url, get_users_only) return channel def _has_channel(self, url) -> bool: """Internal for testing.""" return self._channel_manager.has_channel(url) @staticmethod def _get_instance(): global _global_instance return _global_instance async def join_channel_async(url: str, get_users_only=False) -> Channel: """ Joins a channel and starts listening. The typical life cycle is as follows of a channel session if get_users_only is False: 1. User joins and sends a JOIN message to the channel. 2. Other clients receive JOIN message will respond with HELLO to broadcast its existence. 3. Clients communicate with each other by sending MESSAGE to each other. 4. Clients send LEFT before quit this channel. Args: url (str): The channel url to join. The url could be stage url or url with `.__omni_channel__` or `.channel` suffix. If the suffix is not provided, it will be appended internally with `.__omni_channel__` to be compatible with old version. get_users_only (bool): It will join channel without sending JOIN/HELLO/LEFT message but only receives message from other clients. For example, it can be used to fetch user list without broadcasting its existence. After joining, all users inside the channel will respond HELLO message. Returns: omni.kit.collaboration.channel_manager.Channel. The instance of channel that could be used to publish/subscribe channel messages. Examples: >>> import omni.kit.collaboration.channel_manager as nm >>> >>> async join_channel_async(url): >>> channel = await nm.join_channel_async(url) >>> if channel: >>> channel.add_subscriber(...) >>> await channel.send_message_async(...) >>> else: >>> # Failed to join >>> pass """ if not url.startswith("omniverse:"): carb.log_warn(f"Only Omniverse URL supports to create channel: {url}.") return None if not ChannelManagerExtension._get_instance(): carb.log_warn(f"Channel Manager Extension is not enabled.") return None channel = await ChannelManagerExtension._get_instance().join_channel_async(url, get_users_only=get_users_only) return channel
3,571
Python
38.252747
131
0.66508
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/manager.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. # __all__ = ["Channel", "ChannelSubscriber"] import asyncio import concurrent.futures import weakref import json import carb import carb.settings import omni.client import omni.kit.app import time import omni.kit.collaboration.telemetry import zlib from typing import Callable, Dict, List from .types import Message, MessageType, PeerUser CHANNEL_PING_TIME_IN_SECONDS = 60 # Period to ping. KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER = b'__OVUM__' KIT_CHANNEL_MESSAGE_VERSION = "3.0" OMNIVERSE_CHANNEL_URL_SUFFIX = ".__omni_channel__" OMNIVERSE_CHANNEL_NEW_URL_SUFFIX = ".channel" MESSAGE_VERSION_KEY = "version" MESSAGE_FROM_USER_NAME_KEY = "from_user_name" MESSAGE_CONTENT_KEY = "content" MESSAGE_TYPE_KEY = "message_type" MESSAGE_APP_KEY = "app" def _get_app(): # pragma: no cover settings = carb.settings.get_settings() app_name = settings.get("/app/name") or "Kit" if app_name.lower().endswith(".next"): # FIXME: OM-55917: temp hack for Create. return app_name[:-5] return app_name def _build_message_in_bytes(from_user, message_type, content): # pragma: no cover content = { MESSAGE_VERSION_KEY: KIT_CHANNEL_MESSAGE_VERSION, MESSAGE_TYPE_KEY: message_type, MESSAGE_FROM_USER_NAME_KEY: from_user, MESSAGE_CONTENT_KEY: content, MESSAGE_APP_KEY: _get_app(), } content_bytes = json.dumps(content).encode() return KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER + content_bytes class ChannelSubscriber: # pragma: no cover """Handler of subscription to a channel.""" def __init__(self, message_handler: Callable[[Message], None], channel: weakref) -> None: """ Constructor. Internal only. Args: message_handler (Callable[[Message], None]): Message handler to handle message. channel (weakref): Weak holder of channel. """ self._channel = channel self._message_handler = message_handler def __del__(self): self.unsubscribe() def unsubscribe(self): """Stop subscribe.""" self._message_handler = None if self._channel and self._channel(): self._channel()._remove_subscriber(self) def _on_message(self, message: Message): if self._message_handler: self._message_handler(message) class NativeChannelWrapper: # pragma: no cover """ Channel is the manager that manages message receive and distribution to MessageSubscriber. It works in subscribe/publish pattern. """ def __init__(self, url: str, get_users_only): """ Constructor. Internal only. """ self._url = url self._logged_user_name = "" self._logged_user_id = "" self._peer_users: Dict[str, PeerUser] = {} self._channel_handler = None self._subscribers = [] self._message_queue = [] self._stopped = False self._get_users_only = get_users_only self._stopping = False self._last_ping_time = time.time() self._last_user_response_time = {} self._all_pending_tasks = [] self._joining = False self._telemetry = omni.kit.collaboration.telemetry.Schema_omni_kit_collaboration_1_0() def _track_asyncio_task(self, task): self._all_pending_tasks.append(task) def _remove_asyncio_task(self, task): if task in self._all_pending_tasks: self._all_pending_tasks.remove(task) def _run_asyncio_task(self, func, *args): task = asyncio.ensure_future(func(*args)) self._track_asyncio_task(task) task.add_done_callback(lambda task: self._remove_asyncio_task(task)) return task def _remove_all_tasks(self): for task in self._all_pending_tasks: task.cancel() self._all_pending_tasks = [] def destroy(self): self._remove_all_tasks() self._telemetry = None @property def url(self) -> str: """Property. The channel url in Omniverse.""" return self._url @property def stopped(self) -> bool: """Property. If this channel is stopped already.""" return self._stopped or not self._channel_handler or self._channel_handler.is_finished() @property def stopping(self) -> bool: return self._stopping @property def logged_user_name(self) -> str: """Property. The logged user name for this channel.""" return self._logged_user_name @property def logged_user_id(self) -> str: """Property. The unique logged user id.""" return self._logged_user_id @property def peer_users(self) -> Dict[str, PeerUser]: """Property. All the peer clients that joined to this channel.""" return self._peer_users def _emit_channel_event(self, event_name:str): """ Generates a structured log event noting that a join or leave event has occurred. This event is sent through the 'omni.kit.collaboration.telemetry' extension. Args: event_name: the name of the event to send. This must be either 'join' or 'leave'. """ # build up the event data to emit. Note that the live-edit session's URL will be hashed # instead of exposed directly. This is because the URL contains both the USD stage name # and potential PII in the session's name tag itself (ie: "Bob_session". Both of these # are potentially considered either personal information or intellectual property and # should not be exposed in telemetry events. The hashed value will at least be stable # for any given URL. event = omni.kit.collaboration.telemetry.Struct_liveEdit_liveEdit() event.id = str(zlib.crc32(bytes(self.url, "utf-8"))) event.action = event_name settings = carb.settings.get_settings() cloud_link_id = settings.get("/cloud/cloudLinkId") or "" self._telemetry.liveEdit_sendEvent(cloud_link_id, event) async def join_channel_async(self): """ Async function. Join Omniverse Channel. Args: url: The url to create/join a channel. get_users_only: Johns channel as a monitor only or not. """ if self._get_users_only: carb.log_info(f"Getting users from channel: {self.url}") else: carb.log_info(f"Starting to join channel: {self.url}") if self._channel_handler: self._channel_handler.stop() self._channel_handler = None # Gets the logged user information. try: result, server_info = await omni.client.get_server_info_async(self.url) if result != omni.client.Result.OK: return False self._logged_user_name = server_info.username self._logged_user_id = server_info.connection_id except Exception as e: carb.log_error(f"Failed to join channel {self.url} since user token cannot be got: {str(e)}.") return False channel_connect_future = concurrent.futures.Future() # TODO: Should this function be guarded with mutex? # since it's called in another native thread. def on_channel_message( result: omni.client.Result, event_type: omni.client.ChannelEvent, from_user: str, content ): if not channel_connect_future.done(): if not self._get_users_only: carb.log_info(f"Join channel {self.url} successfully.") self._emit_channel_event("join") channel_connect_future.set_result(result == omni.client.Result.OK) if result != omni.client.Result.OK: carb.log_warn(f"Stop channel since it has errors: {result}.") self._stopped = True return self._on_message(event_type, from_user, content) self._joining = True self._channel_handler = omni.client.join_channel_with_callback(self.url, on_channel_message) result = channel_connect_future.result() if result: if self._get_users_only: await self._send_message_internal_async(MessageType.GET_USERS, {}) else: await self._send_message_internal_async(MessageType.JOIN, {}) self._joining = False return result def stop(self): """Stop this channel.""" if self._stopping or self.stopped: return if not self._get_users_only: carb.log_info(f"Stopping channel {self.url}") self._emit_channel_event("leave") self._stopping = True return self._run_asyncio_task(self._stop_async) async def _stop_async(self): if self._channel_handler and not self._channel_handler.is_finished(): if not self._get_users_only and not self._joining: await self._send_message_internal_async(MessageType.LEFT, {}) self._channel_handler.stop() self._channel_handler = None self._stopped = True self._stopping = False self._subscribers.clear() self._peer_users.clear() self._last_user_response_time.clear() def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber: subscriber = ChannelSubscriber(on_message, weakref.ref(self)) self._subscribers.append(weakref.ref(subscriber)) return subscriber def _remove_subscriber(self, subscriber: ChannelSubscriber): to_be_removed = [] for item in self._subscribers: if not item() or item() == subscriber: to_be_removed.append(item) for item in to_be_removed: self._subscribers.remove(item) async def send_message_async(self, content: dict) -> omni.client.Request: if self.stopped or self.stopping: return return await self._send_message_internal_async(MessageType.MESSAGE, content) async def _send_message_internal_async(self, message_type: MessageType, content: dict): carb.log_verbose(f"Send {message_type} message to channel {self.url}, content: {content}") message = _build_message_in_bytes(self._logged_user_name, message_type, content) return await omni.client.send_message_async(self._channel_handler.id, message) def _update(self): if self.stopped or self._stopping: return # FIXME: Is this a must? pending_messages, self._message_queue = self._message_queue, [] for message in pending_messages: self._handle_message(message[0], message[1], message[2]) current_time = time.time() duration_in_seconds = current_time - self._last_ping_time if duration_in_seconds > CHANNEL_PING_TIME_IN_SECONDS: self._last_ping_time = current_time carb.log_verbose("Ping all users...") self._run_asyncio_task(self._send_message_internal_async, MessageType.GET_USERS, {}) dropped_users = [] for user_id, last_response_time in self._last_user_response_time.items(): duration = current_time - last_response_time if duration > CHANNEL_PING_TIME_IN_SECONDS: dropped_users.append(user_id) for user_id in dropped_users: peer_user = self._peer_users.pop(user_id, None) if not peer_user: continue message = Message(peer_user, MessageType.LEFT, {}) self._broadcast_message(message) def _broadcast_message(self, message: Message): for subscriber in self._subscribers: if subscriber(): subscriber()._on_message(message) def _on_message(self, event_type: omni.client.ChannelEvent, from_user: str, content): # Queue message handling to main looper. self._message_queue.append((event_type, from_user, content)) def _handle_message(self, event_type: omni.client.ChannelEvent, from_user: str, content): # Sent from me, skip them if not from_user: return self._last_user_response_time[from_user] = time.time() peer_user = None payload = {} message_type = None new_user = False if event_type == omni.client.ChannelEvent.JOIN: # We don't use JOIN from server pass elif event_type == omni.client.ChannelEvent.LEFT: peer_user = self._peer_users.pop(from_user, None) if peer_user: message_type = MessageType.LEFT elif event_type == omni.client.ChannelEvent.DELETED: self._channel_handler.stop() self._channel_handler = None elif event_type == omni.client.ChannelEvent.MESSAGE: carb.log_verbose(f"Message received from user with id {from_user}.") try: header_len = len(KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER) bytes = memoryview(content).tobytes() if len(bytes) < header_len: carb.log_error(f"Unsupported message received from user {from_user}.") else: bytes = bytes[header_len:] message = json.loads(bytes) except Exception: carb.log_error(f"Failed to decode message sent from user {from_user}.") return version = message.get(MESSAGE_VERSION_KEY, None) if not version or version != KIT_CHANNEL_MESSAGE_VERSION: carb.log_warn(f"Message version sent from user {from_user} does not match expected one: {message}.") return from_user_name = message.get(MESSAGE_FROM_USER_NAME_KEY, None) if not from_user_name: carb.log_warn(f"Message sent from unknown user: {message}") return message_type = message.get(MESSAGE_TYPE_KEY, None) if not message_type: carb.log_warn(f"Message sent from user {from_user} does not include message type.") return if message_type == MessageType.GET_USERS: carb.log_verbose(f"Fetch message from user with id {from_user}, name {from_user_name}.") if not self._get_users_only: self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {}) return peer_user = self._peer_users.get(from_user, None) if not peer_user: # Don't handle non-recorded user's left. if message_type == MessageType.LEFT: carb.log_verbose(f"User {from_user}, name {from_user_name} left channel.") return else: from_app = message.get(MESSAGE_APP_KEY, "Unknown") peer_user = PeerUser(from_user, from_user_name, from_app) self._peer_users[from_user] = peer_user new_user = True else: new_user = False if message_type == MessageType.HELLO: carb.log_verbose(f"Hello message from user with id {from_user}, name {from_user_name}.") if not new_user: return elif message_type == MessageType.JOIN: carb.log_verbose(f"Join message from user with id {from_user}, name {from_user_name}.") if not new_user: return if not self._get_users_only: self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {}) elif message_type == MessageType.LEFT: carb.log_verbose(f"Left message from user with id {from_user}, name {from_user_name}.") self._peer_users.pop(from_user, None) else: message_content = message.get(MESSAGE_CONTENT_KEY, None) if not message_content or not isinstance(message_content, dict): carb.log_warn(f"Message content sent from user {from_user} is empty or invalid format: {message}.") return carb.log_verbose(f"Message received from user with id {from_user}: {message}.") payload = message_content message_type = MessageType.MESSAGE if message_type and peer_user: # It's possible that user blocks its main thread and hang over the duration time to reponse ping command. # This is to notify user is back again. if new_user and message_type != MessageType.HELLO and message_type != MessageType.JOIN: message = Message(peer_user, MessageType.HELLO, {}) self._broadcast_message(message) message = Message(peer_user, message_type, payload) self._broadcast_message(message) class Channel: # pragma: no cover def __init__(self, handler: weakref, channel_manager: weakref) -> None: self._handler = handler self._channel_manager = channel_manager if self._handler and self._handler(): self._url = self._handler().url self._logged_user_name = self._handler().logged_user_name self._logged_user_id = self._handler().logged_user_id else: self._url = "" @property def stopped(self): return not self._handler or not self._handler() or self._handler().stopped @property def logged_user_name(self): return self._logged_user_name @property def logged_user_id(self): return self._logged_user_id @property def peer_users(self) -> Dict[str, PeerUser]: """Property. All the peer clients that joined to this channel.""" if self._handler and self._handler(): return self._handler().peer_users return None @property def url(self): return self._url def stop(self) -> asyncio.Future: if not self.stopped and self._channel_manager and self._channel_manager(): task = self._channel_manager()._stop_channel(self._handler()) else: task = None self._handler = None return task def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber: """ Add subscriber. Args: on_message (Callable[[Message], None]): The message handler. Returns: Instance of ChannelSubscriber. The channel will be stopped if instance is release. So it needs to hold the instance before it's stopped. You can manually call `stop` to stop this channel, or set the returned instance to None. """ if not self.stopped: return self._handler().add_subscriber(on_message) return None async def send_message_async(self, content: dict) -> omni.client.Request: """ Async function. Send message to all peer clients. Args: content (dict): The message composed in dictionary. Return: omni.client.Request. """ if not self.stopped: return await self._handler().send_message_async(content) return None class ChannelManager: # pragma: no cover def __init__(self) -> None: self._all_channels: List[NativeChannelWrapper] = [] self._update_subscription = None def on_startup(self): carb.log_info("Starting Omniverse Channel Manager...") self._all_channels.clear() app = omni.kit.app.get_app() self._update_subscription = app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.kit.collaboration.channel_manager update" ) def on_shutdown(self): carb.log_info("Shutting down Omniverse Channel Manager...") self._update_subscription = None for channel in self._all_channels: self._stop_channel(channel) channel.destroy() self._all_channels.clear() def _stop_channel(self, channel: NativeChannelWrapper): if channel and not channel.stopping: task = channel.stop() return task return None def _on_update(self, dt): to_be_removed = [] for channel in self._all_channels: if channel.stopped: to_be_removed.append(channel) else: channel._update() for channel in to_be_removed: channel.destroy() self._all_channels.remove(channel) # Internal interface def has_channel(self, url: str): for channel in self._all_channels: if url == channel: return True return False async def join_channel_async(self, url: str, get_users_only: bool): """ Async function. Join Omniverse Channel. Args: url: The url to create/join a channel. get_users_only: Joins channel as a monitor only or not. """ channel_wrapper = NativeChannelWrapper(url, get_users_only) success = await channel_wrapper.join_channel_async() if success: self._all_channels.append(channel_wrapper) channel = Channel(weakref.ref(channel_wrapper), weakref.ref(self)) else: channel = None return channel
21,927
Python
35.304636
119
0.602727
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/types.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. # class PeerUser: """Information of peer user that's joined to the same channel.""" def __init__(self, user_id: str, user_name: str, from_app: str) -> None: """ Constructor. Internal only. Args: user_id (str): Unique user id. user_name (str): Readable user name. from_app (str): Which app this users join from. """ self._user_id = user_id self._user_name = user_name self._from_app = from_app @property def user_id(self): """Property. Unique user id.""" return self._user_id @property def user_name(self): """Property. Readable user name.""" return self._user_name @property def from_app(self): """Property. Readable app name, like 'Kit', 'Maya', etc.""" return self._from_app class MessageType: JOIN = "JOIN" # User is joined. Client should respond HELLO if it receives JOIN from new user. HELLO = "HELLO" # Someone said hello to me. Normally, client sends HELLO when it receives GET_USERS = "GET_USERS" # User does not join this channel, but wants to find who are inside this channel. # Clients receive this message should respond with HELLO to broadcast its existence. # Clients implement this command does not need to send JOIN firstly, and no LEFT sent # also before quitting channel. LEFT = "LEFT" # User left this channel. MESSAGE = "MESSAGE" # Normal message after JOIN. class Message: def __init__(self, from_user: PeerUser, message_type: MessageType, content: dict) -> None: """ Constructor. Internal only. Args: from_user (PeerUser): User that message sent from. message_type (MessageType): Message type. content (dict): Message content in dict. """ self._from_user = from_user self._message_type = message_type self._content = content @property def from_user(self) -> PeerUser: """Property. User that message sent from.""" return self._from_user @property def message_type(self) -> MessageType: """Property. Message type.""" return self._message_type @property def content(self) -> dict: """Property. Message content in dictionary.""" return self._content def __str__(self) -> str: return f"from: {self.from_user.user_name}, message_type: {self.message_type}, content: {self.content}"
3,048
Python
32.505494
113
0.613517
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/__init__.py
from .channel_manager_tests import TestChannelManager
54
Python
26.499987
53
0.87037
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/channel_manager_tests.py
import unittest import omni.client import omni.kit.test import omni.kit.app import omni.kit.collaboration.channel_manager as cm from omni.kit.collaboration.channel_manager.manager import _build_message_in_bytes from .test_base import enable_server_tests class TestChannelManager(omni.kit.test.AsyncTestCase): # pragma: no cover BASE_URL = "omniverse://localhost/Projects/tests/omni.kit.collaboration.channel_manger/" # Before running each test async def setUp(self): self.app = omni.kit.app.get_app() self.current_message = None async def tearDown(self): pass async def _wait(self, frames=10): for i in range(frames): await self.app.next_update_async() async def test_join_invalid_omniverse_url(self): channel = await cm.join_channel_async("file://c/invalid_url.channel") self.assertFalse(channel) channel = await cm.join_channel_async("omniverse://invalid-server/invalid_url.channel") self.assertFalse(channel) async def test_peer_user_and_message_api(self): peer_user = cm.PeerUser("test_id", "test", "Create") self.assertEqual(peer_user.user_id, "test_id") self.assertEqual(peer_user.user_name, "test") self.assertEqual(peer_user.from_app, "Create") content = {"key" : "value"} message = cm.Message(peer_user, cm.MessageType.HELLO, content=content) self.assertEqual(message.from_user, peer_user) self.assertEqual(message.message_type, cm.MessageType.HELLO) self.assertEqual(message.content, content) @unittest.skipIf(not enable_server_tests(), "") async def test_api(self): test_url = self.BASE_URL + "test.channel" def subscriber(message: cm.Message): self.current_message = message channel = await cm.join_channel_async(test_url) handle = channel.add_subscriber(subscriber) self.assertTrue(channel is not None, f"Failed to connect channel.") self.assertTrue(channel.url is not None) self.assertTrue(channel.logged_user_name is not None) self.assertTrue(channel.logged_user_id is not None) self.assertTrue(channel.stopped is False) # Send empty message result = await channel.send_message_async({}) self.assertTrue(result == omni.client.Result.OK) # Send more result = await channel.send_message_async({"test": "message_content"}) self.assertTrue(result == omni.client.Result.OK) # Simulates multi-users user_id = 0 for message_type in [cm.MessageType.JOIN, cm.MessageType.HELLO, cm.MessageType.LEFT]: self.current_message = None content = _build_message_in_bytes("test", message_type, {}) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), content) self.assertTrue(self.current_message is not None) self.assertEqual(self.current_message.message_type, message_type) self.assertEqual(self.current_message.from_user.user_id, str(user_id)) self.assertEqual(self.current_message.from_user.user_name, "test") # Don't increment user id for LEFT message as LEFT message will not be handled if user is not logged. if message_type == cm.MessageType.JOIN: user_id += 1 # Simulates customized message self.current_message = None content = {"test_key": "content"} message = _build_message_in_bytes("test", cm.MessageType.MESSAGE, content) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), message) self.assertTrue(self.current_message) self.assertEqual(self.current_message.message_type, cm.MessageType.MESSAGE) self.assertEqual(self.current_message.content, content) # Channel's LEFT message will be treated as left too. self.current_message = None channel._handler()._handle_message(omni.client.ChannelEvent.LEFT, str(user_id), None) self.assertEqual(self.current_message.message_type, cm.MessageType.LEFT) handle.unsubscribe() @unittest.skipIf(not enable_server_tests(), "") async def test_synchronization(self): test_url = self.BASE_URL + "test.channel" for i in range(20): channel = await cm.join_channel_async(test_url) self.assertTrue(not not channel)
4,456
Python
40.654205
113
0.665619
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/test_base.py
import carb.settings def enable_server_tests(): settings = carb.settings.get_settings() enabled = settings.get_as_bool("/exts/omni.kit.collaboration.channel_manager/enable_server_tests") return enabled
218
Python
20.899998
102
0.738532
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/CHANGELOG.md
# Changelog ## [1.0.9] - 2021-11-02 ### Changed - Support to fetch connection id for logged user. ## [1.0.8] - 2021-09-22 ### Changed - More tests coverage. ## [1.0.7] - 2021-08-21 ### Changed - More tests coverage. ## [1.0.6] - 2021-08-08 ### Changed - Exclude code to improve test coverage. ## [1.0.5] - 2021-07-25 ### Changed - Don't send LEFT message for getting users only. ## [1.0.4] - 2021-07-08 ### Changed - Use real app name for live session. ## [1.0.3] - 2021-06-07 ### Changed - Don't send hello if user is joined already. ## [1.0.2] - 2021-03-15 ### Changed - Improve extension and add tests. ## [1.0.0] - 2021-03-09 ### Changed - Initial extension.
681
Markdown
16.947368
49
0.615272
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/README.md
# Channel Manager [omni.kit.collaboration.channel_manager] This extension provides interfaces create/manage Omniverse Channel without caring about state management but only message exchange between clients.
207
Markdown
68.333311
147
0.850242
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/index.rst
omni.kit.collaboration.channel_manager ###################################### Channel Manager Introduction ============ This extension provides interfaces create/manage Omniverse Channel without caring about state management but only message exchange between clients.
270
reStructuredText
26.099997
121
0.696296
omniverse-code/kit/exts/omni.debugdraw/config/extension.toml
[package] title = "debug draw" category = "Rendering" version = "0.1.1" [dependencies] "omni.usd" = {} "omni.hydra.rtx" = {optional=true} [[python.module]] name = "omni.debugdraw" [[native.plugin]] path = "bin/*.plugin" [[test]] timeout = 600 args = [ "--/app/asyncRendering=false", # OM-49867 random test crashes without this flag "--/renderer/enabled=rtx", "--/renderer/active=rtx", "--/rtx/post/aa/op=0", "--/rtx/post/tonemap/op=1", "--/app/file/ignoreUnsavedOnExit=true", "--/persistent/app/viewport/displayOptions=0", "--/app/viewport/forceHideFps=true", "--/app/viewport/grid/enabled=false", "--/app/viewport/show/lights=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/width=800", "--/app/window/height=600", "--no-window" ] dependencies = [ "omni.ui", "omni.kit.ui_test", "omni.hydra.rtx", "omni.kit.test_helpers_gfx", "omni.kit.viewport.utility", "omni.kit.window.viewport" ]
1,025
TOML
21.8
83
0.623415
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/_debugDraw.pyi
"""pybind11 omni.debugdraw bindings""" from __future__ import annotations import omni.debugdraw._debugDraw import typing import carb._carb __all__ = [ "IDebugDraw", "SimplexPoint", "acquire_debug_draw_interface", "release_debug_draw_interface" ] class IDebugDraw(): def draw_box(self, box_pos: carb._carb.Float3, box_rotation: carb._carb.Float4, box_size: carb._carb.Float3, color: int, line_width: float = 1.0) -> None: ... @typing.overload def draw_line(self, start_pos: carb._carb.Float3, start_color: int, start_width: float, end_pos: carb._carb.Float3, end_color: int, end_width: float) -> None: ... @typing.overload def draw_line(self, start_pos: carb._carb.Float3, start_color: int, end_pos: carb._carb.Float3, end_color: int) -> None: ... def draw_lines(self, lines_list: list) -> None: ... def draw_point(self, pos: carb._carb.Float3, color: int, width: float = 1.0) -> None: ... def draw_points(self, points_list: list) -> None: ... def draw_sphere(self, sphere_pos: carb._carb.Float3, sphere_radius: float, color: int, line_width: float = 1.0, tesselation: int = 32) -> None: ... pass class SimplexPoint(): """ SimplexPoint structure. """ def __init__(self) -> None: ... @property def color(self) -> int: """ :type: int """ @color.setter def color(self, arg0: int) -> None: pass @property def position(self) -> carb._carb.Float3: """ :type: carb._carb.Float3 """ @position.setter def position(self, arg0: carb._carb.Float3) -> None: pass @property def width(self) -> float: """ :type: float """ @width.setter def width(self, arg0: float) -> None: pass pass def acquire_debug_draw_interface(plugin_name: str = None, library_path: str = None) -> IDebugDraw: pass def release_debug_draw_interface(arg0: IDebugDraw) -> None: pass
1,968
unknown
31.816666
166
0.609756
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/__init__.py
from ._debugDraw import IDebugDraw from ._debugDraw import acquire_debug_draw_interface, release_debug_draw_interface def _get_interface(func, acq): if not hasattr(func, "iface"): func.iface = acq() return func.iface def get_debug_draw_interface() -> IDebugDraw: return _get_interface(get_debug_draw_interface, acquire_debug_draw_interface) from .scripts.extension import *
397
Python
29.615382
82
0.735516
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/scripts/extension.py
import omni.ext from .. import get_debug_draw_interface class DebugDrawExtension(omni.ext.IExt): def on_startup(self): get_debug_draw_interface() def on_shutdown(self): pass
201
Python
17.363635
40
0.676617
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/tests/visualtests.py
import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.debugdraw import get_debug_draw_interface from omni.debugdraw._debugDraw import SimplexPoint import carb from pathlib import Path import inspect from omni.kit.viewport.utility import get_active_viewport_window, next_viewport_frame_async from omni.kit.viewport.utility.camera_state import ViewportCameraState from omni.kit.viewport.utility.tests import setup_viewport_test_window, capture_viewport_and_compare EXTENSION_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${omni.debugdraw}")).resolve().absolute() GOLDEN_IMAGES = EXTENSION_ROOT.joinpath("data", "tests") OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) COLOR_RED = 0xffff0000 class DebugDrawVisualTest(OmniUiTest): def set_camera(self): camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world((10, 0, 0), False) camera_state.set_target_world((0, 0, 0), True) async def setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600): await self.create_test_area(resolution_x, resolution_y) return await setup_viewport_test_window(resolution_x, resolution_y) async def base(self, fn): viewport_window = await self.setup_viewport() viewport = viewport_window.viewport_api await omni.usd.get_context().new_stage_async() self.set_camera() # Wait until the Viewport has delivered some frames await next_viewport_frame_async(viewport, 2) # Draw for 20 frames (TC: Windows requires ~5 Linux requires ~20) for _ in range(20): fn() await omni.kit.app.get_app().next_update_async() # Capture and compare the image test_caller = inspect.stack()[1][3] image_name = f"{test_caller}.png" passed, fail_msg = await capture_viewport_and_compare(image_name=image_name, output_img_dir=OUTPUTS_DIR, golden_img_dir=GOLDEN_IMAGES, viewport=viewport) self.assertTrue(passed, msg=fail_msg) def get_point(self, pos, width=2): p = SimplexPoint() p.position = pos p.color = COLOR_RED p.width = width return p async def setUp(self): await super().setUp() self._iface = get_debug_draw_interface() async def test_debugdraw_visual_sphere(self): await self.base(lambda: self._iface.draw_sphere(carb.Float3(0.0, 0.0, 0.0), 2, COLOR_RED)) async def test_debugdraw_visual_line(self): await self.base(lambda: self._iface.draw_line( carb.Float3(0.0, 0.0, 0.0), COLOR_RED, 2, carb.Float3(0.0, 2.0, 0.0), COLOR_RED, 2 )) async def test_debugdraw_visual_line_list(self): line_list = [ self.get_point(carb.Float3(0.0, 0.0, 0.0)), self.get_point(carb.Float3(0.0, -2.0, 0.0)), self.get_point(carb.Float3(0.0, 0.0, 0.0)), self.get_point(carb.Float3(0.0, 2.0, 0.0)), ] await self.base(lambda: self._iface.draw_lines(line_list)) async def test_debugdraw_visual_point(self): await self.base(lambda: self._iface.draw_point(carb.Float3(0.0, 0.0, 0.0), COLOR_RED, 10)) async def test_debugdraw_visual_box(self): await self.base(lambda: self._iface.draw_box( carb.Float3(0.0, 0.0, 0.0), carb.Float4(0.3535534, 0.3535534, 0.1464466, 0.8535534), carb.Float3(2, 2, 2), COLOR_RED )) async def test_debugdraw_visual_points(self): point_list = [ self.get_point(carb.Float3(0.0, 0.0, 0.0), 10), self.get_point(carb.Float3(0.0, -2.0, 0.0), 10), self.get_point(carb.Float3(0.0, 2.0, 0.0), 10), ] await self.base(lambda: self._iface.draw_points(point_list))
3,833
Python
38.122449
161
0.639969
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/tests/__init__.py
from .visualtests import *
27
Python
12.999994
26
0.777778
omniverse-code/kit/exts/omni.kit.test_app_compat/docs/index.rst
omni.kit.test_app_compat ########################### Test app.dev in compatibility mode.
91
reStructuredText
14.333331
35
0.538462
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/__init__.py
from ._app_snippets import *
29
Python
13.999993
28
0.724138
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/_app_snippets.pyi
from __future__ import annotations import omni.kit.app_snippets._app_snippets import typing __all__ = [ "IAppSnippets", "acquire_app_snippets_interface", "release_app_snippets_interface" ] class IAppSnippets(): def execute(self) -> int: ... def shutdown(self) -> None: ... def startup(self) -> None: ... pass def acquire_app_snippets_interface(plugin_name: str = None, library_path: str = None) -> IAppSnippets: pass def release_app_snippets_interface(arg0: IAppSnippets) -> None: pass
525
unknown
24.047618
102
0.672381
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/tests/__init__.py
from .test_app_snippets import *
33
Python
15.999992
32
0.757576
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/tests/test_app_snippets.py
import inspect import carb import carb.settings import omni.kit.app import omni.kit.test import omni.kit.app_snippets class RendererTest(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.acquire_settings_interface() self._app_snippets = omni.kit.app_snippets.acquire_app_snippets_interface() self._app_snippets.startup() def __test_name(self) -> str: return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def tearDown(self): self._app_snippets.shutdown() self._app_snippets = None self._settings = None async def test_0_cpp_snippets(self): carb.log_warn("\n\n\ntest 0!!\n\n") failed_test_count = self._app_snippets.execute() carb.log_warn("failed test count: %d" % (failed_test_count)) self.assertEqual(0, failed_test_count)
902
Python
27.218749
85
0.648559
omniverse-code/kit/exts/omni.graph.scriptnode/ogn/docs/OgnScriptNode.rst
.. _omni_graph_scriptnode_ScriptNode_2: .. _omni_graph_scriptnode_ScriptNode: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Script Node :keywords: lang-en omnigraph node script WriteOnly scriptnode script-node Script Node =========== .. <description> This script node allows you to execute arbitrary Python code. `import` statements, function/class definitions, and global variables may be placed outside of the callbacks, and variables may be added to the ``db.internal_state`` state object The following callback functions may be defined in the script - ``setup(db)`` is called before compute the first time, or after reset is pressed - ``compute(db)`` is called every time the node computes (should always be defined) - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed Predefined Variables - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems - ``og``: is the `omni.graph.core` module .. </description> Installation ------------ To use this node enable :ref:`omni.graph.scriptnode<ext_omni_graph_scriptnode>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:execIn", "``execution``", "The input execution", "None" "Inline Script (*inputs:script*)", "``string``", "A string containing a Python script that may define code to be executed when the script node computes. See the default and example scripts for more info.", "None" "Script File Path (*inputs:scriptPath*)", "``token``", "The path of a file containing a Python script that may define code to be executed when the script node computes. See the default and example scripts for more info.", "None" "", "*uiType*", "filePath", "" "", "*fileExts*", "Python Scripts (\\*.py)", "" "Use Script File (*inputs:usePath*)", "``bool``", "When true, the python script is read from the file specified in 'Script File Path', instead of the string in 'Inline Script'", "False" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:execOut", "``execution``", "The output execution", "None" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:omni_initialized", "``bool``", "State attribute used to control when the script should be reloaded. This should be set to False to trigger a reload of the script.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.graph.scriptnode.ScriptNode" "Version", "2" "Extension", "omni.graph.scriptnode" "Icon", "ogn/icons/omni.graph.scriptnode.ScriptNode.svg" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "uiName", "Script Node" "Categories", "script" "Generated Class Name", "OgnScriptNodeDatabase" "Python Module", "omni.graph.scriptnode"
3,366
reStructuredText
34.072916
232
0.635472
omniverse-code/kit/exts/omni.graph.scriptnode/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.10.0" authors = ["NVIDIA"] title = "Script Node" description="Python Node for OmniGraph" readme = "docs/README.md" repository = "" category = "graph" keywords = ["script"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] [dependencies] "omni.graph" = {} "omni.graph.tools" = {} "omni.kit.widget.text_editor" = { optional = true } # Note: omni.kit.widget.text_editor is brought in by omni.graph.ui "omni.graph.ui" = { optional = true } "omni.kit.widget.searchfield" = { optional = true } "omni.kit.property.usd" = { optional = true } "omni.kit.window.popup_dialog" = { optional = true } "omni.kit.window.property" = { optional = true } # Main python module this extension provides, it will be publicly available as "import omni.graph.scriptnode". [[python.module]] name = "omni.graph.scriptnode" [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,142
TOML
26.878048
118
0.691769
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/OgnScriptNodeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.scriptnode.ScriptNode This script node allows you to execute arbitrary Python code. `import` statements, function/class definitions, and global variables may be placed outside of the callbacks, and variables may be added to the ``db.internal_state`` state object The following callback functions may be defined in the script - ``setup(db)`` is called before compute the first time, or after reset is pressed - ``compute(db)`` is called every time the node computes (should always be defined) - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed Predefined Variables - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems - ``og``: is the `omni.graph.core` module """ import carb import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnScriptNodeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.scriptnode.ScriptNode Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.script inputs.scriptPath inputs.usePath Outputs: outputs.execOut State: state.omni_initialized """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:execIn', 'execution', 0, None, 'The input execution', {}, True, None, False, ''), ('inputs:script', 'string', 0, 'Inline Script', 'A string containing a Python script that may define code to be executed when the script node computes.\nSee the default and example scripts for more info.', {}, False, None, False, ''), ('inputs:scriptPath', 'token', 0, 'Script File Path', 'The path of a file containing a Python script that may define code to be executed when the script node computes.\nSee the default and example scripts for more info.', {ogn.MetadataKeys.UI_TYPE: 'filePath', 'fileExts': 'Python Scripts (*.py)'}, False, None, False, ''), ('inputs:usePath', 'bool', 0, 'Use Script File', "When true, the python script is read from the file specified in 'Script File Path', instead of the string in 'Inline Script'", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('outputs:execOut', 'execution', 0, None, 'The output execution', {}, True, None, False, ''), ('state:omni_initialized', 'bool', 0, None, 'State attribute used to control when the script should be reloaded.\nThis should be set to False to trigger a reload of the script.', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.AttributeRole.EXECUTION role_data.inputs.script = og.AttributeRole.TEXT role_data.outputs.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "script", "scriptPath", "usePath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.script, self._attributes.scriptPath, self._attributes.usePath] self._batchedReadValues = [None, None, None, False] @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def script(self): return self._batchedReadValues[1] @script.setter def script(self, value): self._batchedReadValues[1] = value @property def scriptPath(self): return self._batchedReadValues[2] @scriptPath.setter def scriptPath(self, value): self._batchedReadValues[2] = value @property def usePath(self): return self._batchedReadValues[3] @usePath.setter def usePath(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) @property def omni_initialized(self): data_view = og.AttributeValueHelper(self._attributes.omni_initialized) return data_view.get() @omni_initialized.setter def omni_initialized(self, value): data_view = og.AttributeValueHelper(self._attributes.omni_initialized) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnScriptNodeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnScriptNodeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnScriptNodeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.scriptnode.ScriptNode' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnScriptNodeDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnScriptNodeDatabase(node) try: compute_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnScriptNodeDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnScriptNodeDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnScriptNodeDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnScriptNodeDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.scriptnode") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Script Node") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "script") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This script node allows you to execute arbitrary Python code.\n `import` statements, function/class definitions, and global variables may be placed\n outside of the callbacks, and variables may be added to the ``db.internal_state`` state object\n \n The following callback functions may be defined in the script\n - ``setup(db)`` is called before compute the first time, or after reset is pressed\n - ``compute(db)`` is called every time the node computes (should always be defined)\n - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed\n \n Predefined Variables\n - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems\n - ``og``: is the `omni.graph.core` module\n \n") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.scriptnode}") icon_path = icon_path + '/' + "ogn/icons/omni.graph.scriptnode.ScriptNode.svg" node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path) __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.set_data_access(og.eAccessLocation.E_USD, og.eAccessType.E_WRITE) OgnScriptNodeDatabase.INTERFACE.add_to_node_type(node_type) node_type.set_has_state(True) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnScriptNodeDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnScriptNodeDatabase.abi, 2) @staticmethod def deregister(): og.deregister_node_type("omni.graph.scriptnode.ScriptNode")
15,498
Python
47.586207
890
0.639115
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/python/nodes/OgnScriptNode.py
import inspect import os import tempfile import traceback import omni.client import omni.graph.core as og import omni.graph.tools.ogn as ogn import omni.usd from omni.graph.scriptnode.ogn.OgnScriptNodeDatabase import OgnScriptNodeDatabase # A hacky context manager that captures local variable name declarations and saves them in a dict class ScriptContextSaver: def __init__(self, script_context: dict): self.script_context = script_context self.local_names = None def __enter__(self): caller_frame = inspect.currentframe().f_back self.local_names = set(caller_frame.f_locals) return self def __exit__(self, exc_type, exc_val, exc_tb): caller_frame = inspect.currentframe().f_back caller_locals = caller_frame.f_locals for name in caller_locals: if name not in self.local_names: self.script_context[name] = caller_locals[name] class UserCode: """The cached data associated with a user script""" def __init__(self): self.code_object = None # The compiled code object self.setup_fn = None # setup() self.cleanup_fn = None # cleanup() self.compute_fn = None # compute() self.script_context = {} # namespace for the executed code class OgnScriptNodeState: def __init__(self): self.code = UserCode() # The cached code data self.tempfile_path: str = None # Name of the temporary file for storing the script self.script_path: str = None # The last value of inputs:scriptPath self.script: str = None # The last value of inputs:script self.use_path: bool = None # The last value of inputs:usePath self.node_initialized: bool = False # Flag used to check if the per-instance node state is initialized. class OgnScriptNode: @staticmethod def internal_state(): return OgnScriptNodeState() @staticmethod def _is_initialized(node: og.Node) -> bool: return og.Controller.get(og.Controller.attribute("state:omni_initialized", node)) @staticmethod def _set_initialized(node: og.Node, init: bool): return og.Controller.set(og.Controller.attribute("state:omni_initialized", node), init) @staticmethod def initialize(context, node: og.Node): state = OgnScriptNodeDatabase.per_node_internal_state(node) state.node_initialized = True # Create a temporary file for storing the script with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as tf: state.tempfile_path = tf.name OgnScriptNode._set_initialized(node, False) @staticmethod def release(node: og.Node): state = OgnScriptNodeDatabase.per_node_internal_state(node) # Same logic as when the reset button is pressed OgnScriptNode.try_cleanup(node) # Delete the temporary file for storing the script if os.path.exists(state.tempfile_path): os.remove(state.tempfile_path) @staticmethod def try_cleanup(node: og.Node): # Skip if not setup in the fist place if not OgnScriptNode._is_initialized(node): return state = OgnScriptNodeDatabase.per_node_internal_state(node) # Call the user-defined cleanup function if state.code.cleanup_fn is not None: # Get the database object per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get("_db") try: db.inputs._setting_locked = True # noqa: PLW0212 state.code.cleanup_fn(db) db.inputs._setting_locked = False # noqa: PLW0212 except Exception: # pylint: disable=broad-except OgnScriptNode._print_stacktrace(db) OgnScriptNode._set_initialized(node, False) @staticmethod def _print_stacktrace(db: OgnScriptNodeDatabase): stacktrace = traceback.format_exc().splitlines(keepends=True) stacktrace_iter = iter(stacktrace) stacktrace_output = "" for stacktrace_line in stacktrace_iter: if "OgnScriptNode.py" in stacktrace_line: # The stack trace shows that the exception originates from this file # Removing this useless information from the stack trace next(stacktrace_iter, None) else: stacktrace_output += stacktrace_line db.log_error(stacktrace_output) @staticmethod def _read_script_file(file_path: str) -> str: """Reads the given file and returns the contents""" # Get the absolute path from the possibly relative path in inputs:scriptPath with the edit layer edit_layer = omni.usd.get_context().get_stage().GetEditTarget().GetLayer() if not edit_layer.anonymous: file_path = omni.client.combine_urls(edit_layer.realPath, file_path).replace("\\", "/") del edit_layer # Try to read the script at the specified path result, _, content = omni.client.read_file(file_path) if result != omni.client.Result.OK: raise RuntimeError(f"Could not open/read the script at '{file_path}': error code: {result}") script_bytes = memoryview(content).tobytes() if len(script_bytes) < 2: return "" cur_script = script_bytes.decode("utf-8") return cur_script @staticmethod def _legacy_compute(db: OgnScriptNodeDatabase): # Legacy compute we just exec the whole script every compute with ScriptContextSaver(db.internal_state.code.script_context): exec(db.internal_state.code.code_object) # noqa: PLW0122 @staticmethod def compute(db) -> bool: # Note that we initialize this node's OgnScriptNodeState in the OgnScriptNode initialize # method. While this works for non-instanced workflows, if we try to instance an OmniGraph # that contains a ScriptNode we run into issues, mainly because the instanced ScriptNode # will NOT have an initialized OgnScriptNodeState (since the instanced node's initialize() # method was never actually executed). To account for this, in the compute method we'll # simply call the OgnScriptNode initialize() if said method was never called. if not db.internal_state.node_initialized: OgnScriptNode.initialize(db.abi_context, db.abi_node) use_path = db.inputs.usePath cur_script: str = "" # The script contents tempfile_path = db.internal_state.tempfile_path # The path to the script file to be compiled/executed initialized = db.state.omni_initialized if use_path: script_path = db.inputs.scriptPath if not script_path: return True else: # Use inputs:script for the script and the temporary file for the script path cur_script = db.inputs.script if not cur_script: return True if use_path != db.internal_state.use_path: initialized = False db.internal_state.use_path = use_path try: # Compile / Execute the script if necessary if not initialized: db.state.omni_initialized = True db.internal_state.code = UserCode() db.internal_state.script = None try: if use_path: cur_script = OgnScriptNode._read_script_file(script_path) db.internal_state.script_path = script_path # If the script content has changed we need to re-compile if db.internal_state.script != cur_script: with open(tempfile_path, "w", encoding="utf-8") as tf: tf.write(cur_script) db.internal_state.code.code_object = compile(cur_script, tempfile_path, "exec") db.internal_state.script = cur_script except Exception as ex: # pylint: disable=broad-except # No need for a callstack for an i/o or compilation error db.log_error(str(ex)) return False # Execute the script inside a context manager that captures the names defined in it with ScriptContextSaver(db.internal_state.code.script_context): exec(db.internal_state.code.code_object) # noqa: PLW0122 # Extract the user-defined setup, compute, and cleanup functions db.internal_state.code.compute_fn = db.internal_state.code.script_context.get("compute") if not callable(db.internal_state.code.compute_fn): db.internal_state.code.compute_fn = None if db.internal_state.code.compute_fn is None: # Assume the script is legacy, so execute on every compute db.log_warning("compute(db) not defined in user script, running in legacy mode") db.internal_state.code.compute_fn = OgnScriptNode._legacy_compute return True db.internal_state.code.setup_fn = db.internal_state.code.script_context.get("setup") if not callable(db.internal_state.code.setup_fn): db.internal_state.code.setup_fn = None db.internal_state.code.cleanup_fn = db.internal_state.code.script_context.get("cleanup") if not callable(db.internal_state.code.cleanup_fn): db.internal_state.code.cleanup_fn = None # Inject script-global names into the function globals if db.internal_state.code.compute_fn is not None: db.internal_state.code.compute_fn.__globals__.update(db.internal_state.code.script_context) if db.internal_state.code.setup_fn is not None: db.internal_state.code.setup_fn.__globals__.update(db.internal_state.code.script_context) if db.internal_state.code.cleanup_fn is not None: db.internal_state.code.cleanup_fn.__globals__.update(db.internal_state.code.script_context) # Call the user-defined setup function if db.internal_state.code.setup_fn is not None: db.internal_state.code.setup_fn(db) # ------------------------------------------------------------------------------------ # Call the user-defined compute function if db.internal_state.code.compute_fn is not None: db.internal_state.code.compute_fn(db) # Set outputs:execOut if not hidden if db.node.get_attribute("outputs:execOut").get_metadata(ogn.MetadataKeys.HIDDEN) != "1": db.outputs.execOut = og.ExecutionAttributeState.ENABLED except Exception: # pylint: disable=broad-except OgnScriptNode._print_stacktrace(db) return False return True
11,103
Python
43.594377
112
0.618752
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/extension.py
"""Support required by the Carbonite extension loader""" import asyncio from contextlib import suppress from typing import List import carb import carb.dictionary import omni.ext import omni.graph.core as og from omni.kit.app import get_app SCRIPTNODE_OPT_IN_SETTING = "/app/omni.graph.scriptnode/opt_in" SCRIPTNODE_ENABLE_OPT_IN_SETTING = "/app/omni.graph.scriptnode/enable_opt_in" OMNIGRAPH_STAGEUPDATE_ORDER = 100 # We want our attach() to run after OG so that nodes have been instantiated # ============================================================================================================== def set_all_graphs_enabled(enable: bool): """Set the enabled state of all OmniGraphs""" graphs = og.get_all_graphs() if graphs and not isinstance(graphs, list): graphs = [graphs] for graph in graphs: graph.set_disabled(not enable) def is_check_enabled(): """Returns True if scriptnode opt-in is enabled""" settings = carb.settings.get_settings() if not settings.is_accessible_as(carb.dictionary.ItemType.BOOL, SCRIPTNODE_ENABLE_OPT_IN_SETTING): # The enable-setting is not present, we enable the check return True if not settings.get(SCRIPTNODE_ENABLE_OPT_IN_SETTING): # The enable-setting is present and False, disable the check return False # the enable-setting is present and True, enable the check return True def on_opt_in_change(item: carb.dictionary.Item, change_type: carb.settings.ChangeEventType): """Update the local cache of the setting value""" if change_type != carb.settings.ChangeEventType.CHANGED: return settings = carb.settings.get_settings() should_run = bool(settings.get(SCRIPTNODE_OPT_IN_SETTING)) if should_run: set_all_graphs_enabled(True) def verify_scriptnode_load(script_nodes: List[og.Node]): """ Get verification from the user that they want to run scriptnodes. This opt-in applies to the current session only. Args: script_nodes: The list of script nodes on the stage that have been disabled. """ from omni.kit.window.popup_dialog import MessageDialog def on_cancel(dialog: MessageDialog): settings = carb.settings.get_settings() settings.set(SCRIPTNODE_OPT_IN_SETTING, False) dialog.hide() def on_ok(dialog: MessageDialog): settings = carb.settings.get_settings() settings.set(SCRIPTNODE_OPT_IN_SETTING, True) dialog.hide() message = """ This stage contains scriptnodes. There is currently no limitation on what code can be executed by this node. This means that graphs that contain these nodes should only be used when the author of the graph is trusted. Do you want to enable the scriptnode functionality for this session? """ dialog = MessageDialog( title="Warning", width=400, message=message, cancel_handler=on_cancel, ok_handler=on_ok, ok_label="Yes", cancel_label="No", ) async def show_async(): # wait a few frames to allow the app ui to finish loading await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() dialog.show() asyncio.ensure_future(show_async()) def check_for_scriptnodes(): """ Check for presence of omni.graph.scriptnode instances and confirm user wants to enable them. """ # If the check is not enabled then we are good if not is_check_enabled(): return # Check is enabled - see if they already opted-in settings = carb.settings.get_settings() scriptnode_opt_in = settings.get(SCRIPTNODE_OPT_IN_SETTING) if scriptnode_opt_in: # The check is enabled, and they opted-in return # The check is enabled but they opted out, or haven't been prompted yet try: import omni.kit.window.popup_dialog # noqa except ImportError: # Don't prompt in headless mode return script_nodes = [] graphs = og.get_all_graphs() if graphs and not isinstance(graphs, list): graphs = [graphs] for graph in graphs: for node in graph.get_nodes(): node_type = node.get_node_type() if node_type.get_node_type() == "omni.graph.scriptnode.ScriptNode": # Found one script_nodes.append(node) if not script_nodes: # No script nodes means we can leave them enabled return # Disable them until we get the opt-in via the async dialog set_all_graphs_enabled(False) verify_scriptnode_load(script_nodes) def on_attach(ext_id: int, _): """Called when USD stage is attached""" check_for_scriptnodes() # ============================================================================================================== class _PublicExtension(omni.ext.IExt): """Object that tracks the lifetime of the Python part of the extension loading""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__stage_subscription = None self.__opt_in_setting_sub = None with suppress(ImportError): manager = get_app().get_extension_manager() # This is a bit of a hack to make the template directory visible to the OmniGraph UI extension # if it happens to already be enabled. The "hack" part is that this logic really should be in # omni.graph.ui, but it would be much more complicated there, requiring management of extensions # that both do and do not have dependencies on omni.graph.ui. if manager.is_extension_enabled("omni.graph.ui"): import omni.graph.ui as ogui # noqa: PLW0621 ogui.ComputeNodeWidget.get_instance().add_template_path(__file__) def on_startup(self): stage_update = omni.stageupdate.get_stage_update_interface() self.__stage_subscription = stage_update.create_stage_update_node("OmniGraphAttach", on_attach_fn=on_attach) assert self.__stage_subscription nodes = stage_update.get_stage_update_nodes() stage_update.set_stage_update_node_order(len(nodes) - 1, OMNIGRAPH_STAGEUPDATE_ORDER + 1) self.__opt_in_setting_sub = omni.kit.app.SettingChangeSubscription(SCRIPTNODE_OPT_IN_SETTING, on_opt_in_change) assert self.__opt_in_setting_sub def on_shutdown(self): self.__stage_subscription = None self.__opt_in_setting_sub = None
6,536
Python
35.316666
184
0.643666
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/scriptnode_example_scripts.py
# This file contains the set of example scripts for the script node. # User can click on the Code Snippets button in the UI to display these scripts. # To add new example scripts to the script node, # simply add the delimiter to the bottom of this file, followed by the new script. # Declare og to suppress linter warnings about undefined variables og = None # # # DELIMITER # # # Title = "Default Script" # This script is executed the first time the script node computes, or the next time it computes after this script # is modified or the 'Reset' button is pressed. # The following callback functions may be defined in this script: # setup(db): Called immediately after this script is executed # compute(db): Called every time the node computes (should always be defined) # cleanup(db): Called when the node is deleted or the reset button is pressed (if setup(db) was called before) # Defining setup(db) and cleanup(db) is optional, but if compute(db) is not defined then this script node will run # in legacy mode, where the entire script is executed on every compute and the callback functions above are ignored. # Available variables: # db: og.Database The node interface, attributes are db.inputs.data, db.outputs.data. # Use db.log_error, db.log_warning to report problems. # Note that this is available outside of the callbacks only to support legacy mode. # og: The OmniGraph module # Import statements, function/class definitions, and global variables may be placed outside of the callbacks. # Variables may also be added to the db.internal_state state object. # Example code snippet: import math UNITS = "cm" def calculate_circumfrence(radius): return 2 * math.pi * radius def setup(db): state = db.internal_state state.radius = 1 def compute(db): state = db.internal_state circumfrence = calculate_circumfrence(state.radius) print(f"{circumfrence} {UNITS}") state.radius += 1 # To see more examples, click on the Code Snippets button below. # # # DELIMITER # # # Title = "Compute Count" # In this example, we retrieve the number of times this script node has been computed # and assign it to Output Data so that downstream nodes can use this information. def compute(db): compute_count = db.node.get_compute_count() db.outputs.my_output_attribute = compute_count # # # DELIMITER # # # Title = "Fibonacci" # In this example, we produce the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21... # Each time this node is evaluated, the next Fibonacci number will be set as the output value. # This illustrates how variables declared in the setup script can be used to keep persistent information. # Remember to add an output attribute of type 'int' named my_output_attribute first. def setup(db): state = db.internal_state state.num1 = 0 state.num2 = 1 def compute(db): state = db.internal_state total = state.num1 + state.num2 state.num1 = state.num2 state.num2 = total db.outputs.my_output_attribute = state.num1 # # # DELIMITER # # # Title = "Controller" # In this example, we use omni.graph.core.Controller to create cube prims. # Each time this node is evaluated, it will create a new cube prim on the scene. # When the 'Reset' button is pressed or the node is deleted, the created cube prims will be deleted. import omni.kit.commands def setup(db): state = db.internal_state state.cube_count = 0 def compute(db): state = db.internal_state state.cube_count += 1 og.Controller.edit( db.node.get_graph(), {og.Controller.Keys.CREATE_PRIMS: [(f"/World/Cube{state.cube_count}", "Cube")]} ) def cleanup(db): state = db.internal_state omni.kit.commands.execute("DeletePrims", paths=[f"/World/Cube{i}" for i in range(1, state.cube_count + 1)]) # # # DELIMITER # # # Title = "Random Vectors with Warp" # In this example, we compute the lengths of random 3D vectors using Warp import numpy as np import warp as wp wp.init() NUM_POINTS = 1024 DEVICE = "cuda" @wp.kernel def length(points: wp.array(dtype=wp.vec3), lengths: wp.array(dtype=float)): # thread index tid = wp.tid() # compute distance of each point from origin lengths[tid] = wp.length(points[tid]) def compute(db): # allocate an array of 3d points points = wp.array(np.random.rand(NUM_POINTS, 3), dtype=wp.vec3, device=DEVICE) lengths = wp.zeros(NUM_POINTS, dtype=float, device=DEVICE) # launch kernel wp.launch(kernel=length, dim=len(points), inputs=[points, lengths], device=DEVICE) print(lengths) # # # DELIMITER # # # Title = "Value Changed Callbacks" # In this example, we register a value changed callback function for inputs:my_input_attribute. # The callback is called when the value of inputs:my_input_attribute is changed from the property panel. # Remember to add an input attribute named my_input_attribute first. def on_my_input_attribute_changed(attr): print(f"inputs:my_input_attribute = {attr.get_attribute_data().get()}") def setup(db): attr = db.node.get_attribute("inputs:my_input_attribute") attr.register_value_changed_callback(on_my_input_attribute_changed) def compute(db): pass
5,239
Python
30.190476
116
0.712541
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/templates/template_omni.graph.scriptnode.ScriptNode.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import shutil import subprocess from functools import partial from pathlib import Path import carb.settings import omni.client import omni.graph.core as og import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn import omni.ui as ui from omni.graph.scriptnode.ogn.OgnScriptNodeDatabase import OgnScriptNodeDatabase from omni.graph.ui import OmniGraphAttributeModel from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder from omni.kit.widget.text_editor import TextEditor EXT_PATH = Path(__file__).absolute().parent.parent.parent.parent.parent.parent ICONS_PATH = EXT_PATH.joinpath("icons") FONTS_PATH = EXT_PATH.joinpath("fonts") class ComboBoxOption(ui.AbstractItem): """Provide a conversion from simple text to a StringModel to be used in ComboBox options""" def __init__(self, text: str): super().__init__() self.model = ui.SimpleStringModel(text) def destroy(self): self.model = None class ComboBoxModel(ui.AbstractItemModel): """The underlying model of a combo box""" def __init__(self, option_names, option_values, current_value, on_value_changed_callback): super().__init__() self.option_names = option_names self.option_values = option_values self.on_value_changed_callback = on_value_changed_callback self._current_index = ui.SimpleIntModel(self.option_values.index(current_value)) self._current_index.add_value_changed_fn(self._on_index_changed) self._items = [ComboBoxOption(option) for option in self.option_names] def destroy(self): ogt.destroy_property(self, "_current_index") ogt.destroy_property(self, "_items") def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id: int): if item is None: return self._current_index # combo box expects index model on item == None return item.model def _on_index_changed(self, new_index: ui.SimpleIntModel): new_value = self.option_values[new_index.as_int] self.on_value_changed_callback(new_value) self._item_changed(None) class CreateAttributePopupDialog: """The popup dialog for creating new dynamic attribute on the script node""" def __init__(self, create_new_attribute_callback, **kwargs): self.create_new_attribute_callback = create_new_attribute_callback self.all_supported_types = [] self.all_displayed_types = [] self.window = None self.attribute_name_field = None self.port_type_radio_collection = None self.input_port_button = None self.output_port_button = None self.state_port_button = None self.scrolling_frame = None self.selected_type_button = None self.selected_memory_type = None self.selected_cuda_pointers = None self.error_message_label = None self.get_all_supported_types() self.build_popup_dialog() def get_all_supported_types(self): """Get a list of types that can be added to the script node""" # "any" types need to be manually resolved by script writers, # "transform" types are marked for deprecation in USD, so we don't want to support them self.all_supported_types = [ attr_type for attr_type in ogn.supported_attribute_type_names() if attr_type != "any" and attr_type[:9] != "transform" ] self.all_displayed_types = self.all_supported_types def build_scrolling_frame(self): """Build the scrolling frame underneath the search bar""" def _on_type_selected(button): if self.selected_type_button is not None: self.selected_type_button.checked = False self.selected_type_button = button self.selected_type_button.checked = True self.scrolling_frame.clear() with self.scrolling_frame: with ui.VStack(): for displayed_type in self.all_displayed_types: button = ui.Button(displayed_type, height=20) button.set_clicked_fn(partial(_on_type_selected, button)) def build_popup_dialog(self): def filter_types_by_prefix(text): """Callback executed when the user presses enter in the search bar""" if text is None: self.all_displayed_types = self.all_supported_types else: text = text[0] self.all_displayed_types = [ displayed_type for displayed_type in self.all_supported_types if displayed_type[: len(text)] == text ] self.build_scrolling_frame() self.selected_type_button = None def on_create_new_attribute(): """Callback executed when the user creates a new dynamic attribute""" if not self.attribute_name_field.model.get_value_as_string(): self.error_message_label.text = "Error: Attribute name cannot be empty!" return if not self.attribute_name_field.model.get_value_as_string()[0].isalpha(): self.error_message_label.text = "Error: The first character of attribute name must be a letter!" return if ( not self.input_port_button.checked and not self.output_port_button.checked and not self.state_port_button.checked ): self.error_message_label.text = "Error: You must select a port type!" return if self.selected_type_button is None: self.error_message_label.text = "Error: You must select a type for the new attribute!" return attrib_name = self.attribute_name_field.model.get_value_as_string() attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT if self.output_port_button.checked: attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT elif self.state_port_button.checked: attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE attrib_type_name = self.selected_type_button.text attrib_type = og.AttributeType.type_from_ogn_type_name(attrib_type_name) self.create_new_attribute_callback( attrib_name, attrib_port_type, attrib_type, self.selected_memory_type, self.selected_cuda_pointers ) self.window.visible = False def on_cancel_clicked(): self.window.visible = False window_flags = ui.WINDOW_FLAGS_NO_RESIZE self.window = ui.Window( "Create Attribute", width=400, height=0, padding_x=15, padding_y=15, flags=window_flags, ) input_field_width = ui.Percent(60) with self.window.frame: with ui.VStack(spacing=10): # Attribute name string field with ui.HStack(height=0): ui.Label("Attribute Name: ") self.attribute_name_field = ui.StringField(width=input_field_width, height=20) # Attribute port type radio button with ui.HStack(height=0): ui.Label("Attribute Port Type: ") self.port_type_radio_collection = ui.RadioCollection() with ui.HStack(width=input_field_width, height=20): self.input_port_button = ui.RadioButton( text="input", radio_collection=self.port_type_radio_collection ) self.output_port_button = ui.RadioButton( text="output", radio_collection=self.port_type_radio_collection ) self.state_port_button = ui.RadioButton( text="state", radio_collection=self.port_type_radio_collection ) # Attribute type search bar with ui.HStack(height=0): ui.Label("Attribute Type: ", alignment=ui.Alignment.LEFT_TOP) with ui.VStack(width=input_field_width): # Search bar try: from omni.kit.widget.searchfield import SearchField SearchField(show_tokens=False, on_search_fn=filter_types_by_prefix) except ImportError: # skip the search bar if the module cannot be imported pass # List of attribute types self.scrolling_frame = ui.ScrollingFrame( height=150, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="TreeView", ) self.build_scrolling_frame() # TODO: Uncomment this block when dynamic attributes support memory types # # Attribute memory type combo box # with ui.HStack(height=0): # ui.Label("Attribute Memory Type: ") # memory_type_option_names = ["CPU", "CUDA", "Any"] # memory_type_option_values = [ogn.MemoryTypeValues.CPU, # ogn.MemoryTypeValues.CUDA, ogn.MemoryTypeValues.ANY] # self.selected_memory_type = ogn.MemoryTypeValues.CPU # def _on_memory_type_selected(new_memory_type): # self.selected_memory_type = new_memory_type # ui.ComboBox( # ComboBoxModel( # memory_type_option_names, # memory_type_option_values, # self.selected_memory_type, # _on_memory_type_selected, # ), # width=input_field_width, # ) # # CUDA pointers combo box # with ui.HStack(height=0): # ui.Label("CUDA Pointers: ") # cuda_pointers_option_names = ["CUDA", "CPU"] # cuda_pointers_option_values = [ogn.CudaPointerValues.CUDA, ogn.CudaPointerValues.CPU] # self.selected_cuda_pointers = ogn.CudaPointerValues.CUDA # def _on_cuda_pointers_selected(new_cuda_pointers): # self.selected_cuda_pointers = new_cuda_pointers # ui.ComboBox( # ComboBoxModel( # cuda_pointers_option_names, # cuda_pointers_option_values, # self.selected_cuda_pointers, # _on_cuda_pointers_selected, # ), # width=input_field_width, # ) # OK button to confirm selection with ui.HStack(height=0): ui.Spacer() with ui.HStack(width=input_field_width, height=20): ui.Button( "OK", clicked_fn=on_create_new_attribute, ) ui.Button( "Cancel", clicked_fn=on_cancel_clicked, ) # Some empty space to display error messages if needed self.error_message_label = ui.Label( " ", height=20, alignment=ui.Alignment.H_CENTER, style={"color": 0xFF0000FF} ) class ScriptTextbox(TextEditor): def __init__(self, script_model: OmniGraphAttributeModel): super().__init__( syntax=TextEditor.Syntax.PYTHON, style={"font": str(FONTS_PATH.joinpath("DejaVuSansMono.ttf"))}, text=script_model.get_value_as_string(), ) self.script_model = script_model self.script_model_callback_id = self.script_model.add_value_changed_fn(self._on_script_model_changed) self.set_edited_fn(self._on_script_edited) def _on_script_edited(self, text_changed: bool): if text_changed: # Don't trigger the model changed callback when script is edited self.script_model.remove_value_changed_fn(self.script_model_callback_id) # Remove the newline that TextEditor adds or else it will accumulate self.script_model.set_value(self.text[:-1]) self.script_model_callback_id = self.script_model.add_value_changed_fn(self._on_script_model_changed) def _on_script_model_changed(self, script_model): self.text = script_model.get_value_as_string() # noqa: PLW0201 class CustomLayout: def __init__(self, compute_node_widget): self._remove_attribute_menu = None self._code_snippets_menu = None self.enable = True self.compute_node_widget = compute_node_widget self.node_prim_path = self.compute_node_widget._payload[-1] self.node = og.Controller.node(self.node_prim_path) self.script_textbox_widget = None self.script_textbox_model = None self.script_textbox_resizer = None self.script_path_widget = None self.script_selector_window = None self.external_script_editor = None self.external_script_editor_ui_name = None self.DEFAULT_SCRIPT = "" self.EXAMPLE_SCRIPTS = [] self.EXAMPLE_SCRIPTS_TITLE = [] self.add_attribute_button = None self.remove_attribute_button = None self.code_snippets_button = None self.reset_button = None self.initialized_model = None self.EXISTING_ATTRIBUTES = [ "inputs:script", "inputs:scriptPath", "inputs:usePath", "inputs:execIn", "outputs:execOut", "state:omni_initialized", "node:type", "node:typeVersion", ] # Retrieve the example scripts cur_file_path = os.path.abspath(os.path.dirname(__file__)) example_scripts_path = os.path.join(cur_file_path, "..", "scriptnode_example_scripts.py") with open(example_scripts_path, "r", encoding="utf-8") as file: file_contents = file.read().split("# # # DELIMITER # # #") for script in file_contents[1:]: script = script.strip() script_lines = script.splitlines(keepends=True) script_title_line = script_lines[0] script_title = script_title_line.strip()[9:-1] script_content = "".join(script_lines[1:]) if script_title == "Default Script": self.DEFAULT_SCRIPT = script_content else: self.EXAMPLE_SCRIPTS.append(script_content) self.EXAMPLE_SCRIPTS_TITLE.append(script_title) # Determine the external script editor # Check the settings editor = carb.settings.get_settings().get("/app/editor") if not editor: # Check the environment variable EDITOR editor = os.environ.get("EDITOR", None) if not editor: # Default to VSCode editor = "code" # Remove quotes from the editor name if present if editor[0] == '"' and editor[-1] == '"': editor = editor[1:-1] # Get the user-friendly editor name editor_ui_name = editor if editor == "code": editor_ui_name = "VSCode" elif editor == "notepad": editor_ui_name = "Notepad" # Check that the editor exists and is executable if not (os.path.isfile(editor) and os.access(editor, os.X_OK)): try: editor = shutil.which(editor) except shutil.Error: editor = None if not editor: # Resort to notepad on windows and gedit on linux if os.name == "nt": editor = "notepad" editor_ui_name = "Notepad" else: editor = "gedit" editor_ui_name = "gedit" self.external_script_editor = editor self.external_script_editor_ui_name = editor_ui_name def retrieve_existing_attributes(self): """Retrieve the dynamic attributes that already exist on the node""" all_attributes = self.node.get_attributes() inputs = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ] outputs = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ] states = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE ] return (all_attributes, inputs, outputs, states) def _on_script_textbox_resizer_dragged(self, offset_y: ui.Length): self.script_textbox_resizer.offset_y = max(offset_y.value, 50) def _script_textbox_build_fn(self, *args): """Build the textbox used to input custom scripts""" self.script_textbox_model = OmniGraphAttributeModel( self.compute_node_widget.stage, [self.node_prim_path.AppendProperty("inputs:script")], False, {} ) if self.script_textbox_model.get_value_as_string() == "": self.script_textbox_model.set_value(self.DEFAULT_SCRIPT) with ui.VStack(): with ui.HStack(): UsdPropertiesWidgetBuilder._create_label( # noqa: PLW0212 "Script", {}, {"style": {"alignment": ui.Alignment.RIGHT_TOP}} ) ui.Spacer(width=7) with ui.ZStack(): with ui.VStack(): self.script_textbox_widget = ScriptTextbox(self.script_textbox_model) # Disable editing if the script value comes from an upstream connection if og.Controller.attribute("inputs:script", self.node).get_upstream_connection_count() > 0: self.script_textbox_widget.read_only = True # noqa: PLW0201 ui.Spacer(height=12) # Add a draggable bar below the script textbox to resize it self.script_textbox_resizer = ui.Placer(offset_y=200, draggable=True, drag_axis=ui.Axis.Y) self.script_textbox_resizer.set_offset_y_changed_fn(self._on_script_textbox_resizer_dragged) with self.script_textbox_resizer: script_textbox_resizer_style = { ":hovered": {"background_color": 0xFFB0703B}, ":pressed": {"background_color": 0xFFB0703B}, } with ui.ZStack(height=12): ui.Rectangle(style=script_textbox_resizer_style) with ui.HStack(): ui.Spacer() ui.Label("V", width=0) ui.Spacer() ui.Spacer(height=5) with ui.HStack(): ui.Spacer() self._code_snippets_button_build_fn() def _code_snippets_button_build_fn(self, *args): """Build the code snippets button used to show example scripts""" def _code_snippets_menu_build_fn(): """Build the code snippets popup menu""" self._code_snippets_menu = ui.Menu("Code Snippets") with self._code_snippets_menu: for example_script_title, example_script in zip(self.EXAMPLE_SCRIPTS_TITLE, self.EXAMPLE_SCRIPTS): ui.MenuItem( example_script_title, triggered_fn=partial(self.script_textbox_model.set_value, example_script) ) self._code_snippets_menu.show() self.code_snippets_button = ui.Button("Code Snippets", width=135, clicked_fn=_code_snippets_menu_build_fn) def _on_initialized_changed(self, initialized_model): self.reset_button.enabled = initialized_model.as_bool def _reset_button_build_fn(self, *args): """Build button that calls the cleanup script and forces the setup script to be called on next compute""" def do_reset(): """Call the user-defined cleanup function and set state:omni_initialized to false""" OgnScriptNodeDatabase.NODE_TYPE_CLASS._try_cleanup(self.node) # noqa: PLW0212 self.reset_button.enabled = False def get_initialized(): """Get the value of state:omni_initialized""" initialized_attr = og.Controller.attribute("state:omni_initialized", self.node) return og.Controller.get(initialized_attr) self.reset_button = ui.Button( "Reset", width=135, clicked_fn=do_reset, enabled=get_initialized(), tooltip="Execute the setup script again on the next compute", ) self.initialized_model = OmniGraphAttributeModel( self.compute_node_widget.stage, [self.node_prim_path.AppendProperty("state:omni_initialized")], False, {} ) self.initialized_model.add_value_changed_fn(self._on_initialized_changed) def _add_attribute_button_build_fn(self, *args): def create_dynamic_attribute(attrib_name, attrib_port_type, attrib_type, attrib_memory_type, cuda_pointers): if ( attrib_name == "execOut" and attrib_port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and attrib_type.get_ogn_type_name() == "execution" ): # Unhide outputs:execOut instead of creating it self.node.get_attribute("outputs:execOut").set_metadata(ogn.MetadataKeys.HIDDEN, None) return new_attribute = og.Controller.create_attribute(self.node, attrib_name, attrib_type, attrib_port_type) if new_attribute is None: return if attrib_type.get_type_name() == "prim" and attrib_port_type in ( og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE, ): # For bundle output/state attribs, the default UI name contains the port type, so we set it here instead def make_ui_name(attrib_name: str): parts_out = [] words = attrib_name.replace("_", " ").split(" ") for word in words: # noqa: PLR1702 if word.islower() or word.isupper(): parts_out += [word] else: # Mixed case. # Lower-case followed by upper-case breaks between them. E.g. 'usdPrim' -> 'usd Prim' # Upper-case followed by lower-case breaks before them. E.g: 'USDPrim' -> 'USD Prim' # Combined example: abcDEFgHi -> abc DE Fg Hi sub_word = "" uppers = "" for c in word: if c.isupper(): if not uppers: # noqa: SIM102 if sub_word: parts_out += [sub_word] sub_word = "" uppers += c else: if len(uppers) > 1: parts_out += [uppers[:-1]] sub_word += uppers[-1:] + c uppers = "" if sub_word: parts_out += [sub_word] elif uppers: parts_out += [uppers] # Title-case any words which are all lower case. parts_out = [part.title() if part.islower() else part for part in parts_out] return " ".join(parts_out) new_attribute.set_metadata(ogn.MetadataKeys.UI_NAME, make_ui_name(attrib_name)) # TODO: Uncomment this when dynamic attributes support memory types # new_attribute.set_metadata(ogn.MetadataKeys.MEMORY_TYPE, attrib_memory_type) # new_attribute.set_metadata(ogn.MetadataKeys.CUDA_POINTERS, cuda_pointers) self.compute_node_widget.rebuild_window() def on_click_add(): CreateAttributePopupDialog(create_dynamic_attribute) self.add_attribute_button = ui.Button("Add +", width=100, clicked_fn=on_click_add) def _remove_attribute_button_build_fn(self, *args): def remove_dynamic_attribute(attrib): if attrib.get_name() == "outputs:execOut": # Hide outputs:execOut instead of removing it og.Controller.disconnect_all(("outputs:execOut", self.node)) attrib.set_metadata(ogn.MetadataKeys.HIDDEN, "1") return success = og.Controller.remove_attribute(attrib) if not success: return self.compute_node_widget.rebuild_window() def _remove_attribute_menu_build_fn(): self._remove_attribute_menu = ui.Menu("Remove Attribute") (all_attributes, _, _, _) = self.retrieve_existing_attributes() with self._remove_attribute_menu: for attrib in all_attributes: name = attrib.get_name() # These attributes were not created by user so they are not deletable, # except for outputs:execOut, which can be hidden if not already hidden if not attrib.is_dynamic() and not ( name == "outputs:execOut" and attrib.get_metadata(ogn.MetadataKeys.HIDDEN) != "1" ): continue # Any attribute without the inputs:/outputs:/state: prefix were not created by user so they are # not deletable, except for bundle output and state attributes, which are delimited with '_' if ( name[:7] != "inputs:" and name[:8] != "outputs:" and name[:6] != "state:" and not ( attrib.get_type_name() == "bundle" and (name[:8] == "outputs_" or name[:6] == "state_") ) ): continue # Otherwise we should allow user to delete this attribute ui.MenuItem(name, triggered_fn=partial(remove_dynamic_attribute, attrib)) self._remove_attribute_menu.show() self.remove_attribute_button = ui.Button("Remove -", width=100, clicked_fn=_remove_attribute_menu_build_fn) def _special_control_build_fn(self, *args): with ui.HStack(): self._add_attribute_button_build_fn() ui.Spacer(width=8) self._remove_attribute_button_build_fn() def _get_absolute_script_path(self): """Get the possibly relative path in inputs:scriptPath as an aboslute path""" script_path = og.Controller.get(og.Controller.attribute("inputs:scriptPath", self.node)) edit_layer = self.compute_node_widget.stage.GetEditTarget().GetLayer() if not edit_layer.anonymous: script_path = omni.client.combine_urls(edit_layer.realPath, script_path).replace("\\", "/") return script_path def _show_script_selector_window(self): """Create and show the file browser window which is used to select the script for inputs:scriptPath""" try: from omni.kit.window.filepicker import FilePickerDialog except ImportError: # Do nothing if the module cannot be imported return def _on_click_okay(filename: str, dirname: str): # Get the relative path relative to the edit layer chosen_file = omni.client.combine_urls(dirname, filename) edit_layer = self.compute_node_widget.stage.GetEditTarget().GetLayer() if not edit_layer.anonymous: chosen_file = omni.client.make_relative_url(edit_layer.realPath, chosen_file) chosen_file = chosen_file.replace("\\", "/") # Set the value of inputs:scriptPath self.script_path_widget.set_value(chosen_file) self.script_selector_window.hide() def _on_click_cancel(filename: str, dirname: str): self.script_selector_window.hide() self.script_selector_window = FilePickerDialog( "Select a Python script", click_apply_handler=_on_click_okay, click_cancel_handler=_on_click_cancel, allow_multi_selection=False, file_extension_options=[("*.py", "Python scripts (*.py)")], ) self.script_selector_window.show(self._get_absolute_script_path()) def _launch_external_script_editor(self): """Launch an external editor targeting the path specified in inputs:scriptPath""" # Use cmd in case the editor is a bat or cmd file call_command = ["cmd", "/c"] if os.name == "nt" else [] call_command.append(self.external_script_editor) call_command.append(self._get_absolute_script_path()) subprocess.Popen(call_command) # noqa: PLR1732 def _script_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): """Build the attribute label, textbox, browse button, and edit button for inputs:scriptPath""" self.script_path_widget = UsdPropertiesWidgetBuilder._string_builder( # noqa: PLW0212 self.compute_node_widget.stage, ui_prop.prop_name, ui_prop.property_type, ui_prop.metadata, [self.node_prim_path], {"style": {"alignment": ui.Alignment.RIGHT_TOP}}, ) ui.Spacer(width=5) ui.Button( image_url=str(ICONS_PATH.joinpath("folder_open.svg")), width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=self._show_script_selector_window, tooltip="Browse...", ) ui.Spacer(width=5) ui.Button( image_url=str(ICONS_PATH.joinpath("external_link.svg")), width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=self._launch_external_script_editor, tooltip=f"Open in {self.external_script_editor_ui_name}\n(set the preferred editor from the '/app/editor' setting)", ) def apply(self, props): """Called by compute_node_widget to apply UI when selection changes""" def find_prop(name): try: return next((p for p in props if p.prop_name == name)) except StopIteration: return None frame = CustomLayoutFrame(hide_extra=True) (_, inputs, outputs, states) = self.retrieve_existing_attributes() with frame: with ui.HStack(): ui.Spacer() self._reset_button_build_fn() with CustomLayoutGroup("Add and Remove Attributes"): CustomLayoutProperty(None, None, self._special_control_build_fn) with CustomLayoutGroup("Inputs"): prop = find_prop("inputs:script") CustomLayoutProperty(prop.prop_name, "Script", partial(self._script_textbox_build_fn, prop)) prop = find_prop("inputs:usePath") CustomLayoutProperty(prop.prop_name, "Use Path") prop = find_prop("inputs:scriptPath") CustomLayoutProperty(prop.prop_name, "Script Path", partial(self._script_path_build_fn, prop)) for input_attrib in inputs: attrib_name = input_attrib.get_name() if input_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name[7:]) with CustomLayoutGroup("Outputs"): for output_attrib in outputs: attrib_name = output_attrib.get_name() if output_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name[8:]) with CustomLayoutGroup("State"): for state_attrib in states: attrib_name = state_attrib.get_name() if state_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name) return frame.apply(props)
34,537
Python
44.325459
128
0.559603
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/test_scriptnode_ui.py
"""Tests for scriptnode which exercise the UI""" import os import tempfile import omni.graph.core as og import omni.graph.ui._impl.omnigraph_attribute_base as ogab import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_for_window from omni.ui.tests.test_base import OmniUiTest class TestScriptNodeUI(OmniUiTest): """ Tests for scriptnode which exercise the UI """ TEST_GRAPH_PATH = "/World/TestGraph" # Before running each test async def setUp(self): await super().setUp() # Ensure we have a clean stage for the test await omni.usd.get_context().new_stage_async() # Give OG a chance to set up on the first stage update await omni.kit.app.get_app().next_update_async() self._temp_file_path = None # A temporary file we need to clean up import omni.kit.window.property as p self._w = p.get_window() # The OG attribute-base UI should refresh every frame ogab.AUTO_REFRESH_PERIOD = 0 async def tearDown(self): if (self._temp_file_path is not None) and os.path.isfile(self._temp_file_path): os.remove(self._temp_file_path) # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async() await super().tearDown() async def test_interaction(self): """ Exercise the controls on the custom template """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() (_, (script_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ScriptNode", "omni.graph.scriptnode.ScriptNode"), ], keys.SET_VALUES: [("ScriptNode.inputs:usePath", False), ("ScriptNode.inputs:scriptPath", "")], }, ) ok = script_node.create_attribute( "outputs:out", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) self.assertTrue(ok) attr_out = script_node.get_attribute("outputs:out") attr_script = script_node.get_attribute("inputs:script") # Select the node. usd_context.get_selection().set_selected_prim_paths([script_node.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Set the inline script back to empty attr_script.set("") reset_button = ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_reset'") script_path_model = ui_test.find("Property//Frame/**/.identifier=='sdf_asset_inputs:scriptPath'") use_path_toggle = ui_test.find("Property//Frame/**/.identifier=='bool_inputs:usePath'") snippets_button = ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_snippets'") # write out a script and change the file path await use_path_toggle.click() await ui_test.human_delay(5) # NamedTemporaryFile is not very nice on Windows, need to ensure we close before node tries to read with tempfile.NamedTemporaryFile(mode="w+t", encoding="utf-8", delete=False) as tf: self._temp_file_path = tf.name tf.write( """ def compute(db: og.Database): db.outputs.out = 42 return True""" ) await script_path_model.input(self._temp_file_path) await omni.kit.app.get_app().next_update_async() # verify it has now computed, because `input` above will trigger the widget `end_edit` self.assertEqual(attr_out.get(), 42) # change the script, verify it doesn't take effect until reset is pressed with open(self._temp_file_path, mode="w+t", encoding="utf-8") as tf: tf.write( """ def compute(db: og.Database): db.outputs.out = 1000 return True""" ) await omni.kit.app.get_app().next_update_async() # verify it has now computed self.assertEqual(attr_out.get(), 42) await reset_button.click() await ui_test.human_delay(1) # Verify the script now computed with the new script self.assertEqual(attr_out.get(), 1000) # Switch it back to inline script attr_script.set( """ def compute(db): db.outputs.out = 1 """ ) await ui_test.human_delay(1) await use_path_toggle.click() await reset_button.click() await ui_test.human_delay(1) self.assertEqual(attr_out.get(), 1) # Switch it back to external script await use_path_toggle.click() await ui_test.human_delay(1) self.assertEqual(attr_out.get(), 1000) # Now add an attribute using the dialog await ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_add_attribute'").click() await wait_for_window("Add Attribute") await ui_test.find("Add Attribute//Frame/**/StringField[*].identifier=='_scriptnode_name'").input("test_attrib") # Find the only string field without an identifier, that is the search field await ui_test.find("Add Attribute//Frame/**/StringField[*].identifier!='_scriptnode_name'").input("int64") await ui_test.find("Add Attribute//Frame/**/Button[*].text=='int64'").click() await ui_test.human_delay(1) await ui_test.find("Add Attribute//Frame/**/Button[*].identifier=='_scriptnode_add_ok'").click() await ui_test.human_delay(3) # Check the attribute was actually added attr_test = script_node.get_attribute("inputs:test_attrib") self.assertEqual(attr_test.get_resolved_type(), og.Type(og.BaseDataType.INT64, 1, 0)) # Show the remove menu, remove the item we added await ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_remove_attribute'").click() await ui_test.human_delay(1) menu = ui.Menu.get_current() test_item = next((item for item in ui.Inspector.get_children(menu) if item.text == "inputs:test_attrib")) test_item.call_triggered_fn() await ui_test.human_delay(1) self.assertFalse(script_node.get_attribute_exists("inputs:test_attrib")) menu.hide() # Clear the current script attr_script.set("") await ui_test.human_delay(1) # Show the snippets menu await snippets_button.click() await ui_test.human_delay(1) menu = ui.Menu.get_current() # select the first one, verify the script was changed ui.Inspector.get_children(menu)[0].call_triggered_fn() await ui_test.human_delay(1) self.assertTrue("def compute(db)" in attr_script.get())
6,930
Python
37.082417
120
0.623665
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.scriptnode as ogs from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphScriptNodeApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ogs, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogs.tests, is_test_module=True) # noqa: PLW0212 async def test_api_features(self): """Test that the known public API features continue to exist""" _check_public_api_contents(ogs.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
825
Python
44.888886
107
0.653333
omniverse-code/kit/exts/omni.graph.scriptnode/docs/CHANGELOG.md
# CHANGELOG ## [0.10.0] - 2023-01-23 ### Changed - opt-in is enabled by /app/omni.graph.scriptnode/enable_opt_in - modify the dialog to appear after loading - disable all graphs until opt-in is verified ## [0.9.3] - 2022-10-16 ### Changed - opt-in mechanism reads from remote file instead of app setting ## [0.9.2] - 2022-10-08 ### Changed - Fix for font size in 104 ## [0.9.1] - 2022-10-07 ### Fixed - Font size of code editor ## [0.9.0] - 2022-09-29 ### Added - User-defined callbacks 'compute', 'setup', and 'cleanup', along with a reset button - Ability to "remove" outputs:execOut by hiding it - Support for warp, inspect, ast, and other modules by saving inputs:script to a temp file - Script path input for reading scripts from files - Improved textbox UI for inputs:script using omni.kit.widget.text_editor ## [0.8.0] - 2022-09-14 ### Added - opt-in mechanism on attach. Controlled by /app/omni.graph.scriptnode/enable_opt_in and /app/omni.graph.scriptnode/opt_in ## [0.7.2] - 2022-08-23 ### Changed - Removed security warnings. We don't want to advertise the problem. ## [0.7.1] - 2022-08-09 ### Fixed - Applied formatting to all of the Python files ## [0.7.0] - 2022-08-09 ### Changed - Removed omni.graph.action dependency ## [0.6.0] - 2022-07-07 ### Changed - Refactored imports from omni.graph.tools to get the new locations ## [0.5.0] - 2022-03-30 ### Changed - Give each example code snippet a title, which will be displayed when you click on the Code Snippets button - Change title of Add Attribute window from "Create a new attribute..." to "Create Attribute" - Disable resizing of the Add Attribute dialog - Add Cancel button to the Add Attribute dialog - Make the Add Attribute/Remove Attribute/Code Snippets buttons left aligned - Allow users to add Script Node to push graphs by removing the graph:action category ### Fixed - Fixed a bug where Remove Attribute button allows you to remove the node-as-bundle output attribute ## [0.4.1] - 2022-03-10 ### Fixed - Made property panel only display non-None props - Renamed some variables to better match what they are doing ## [0.4.0] - 2022-02-28 ### Added - Gave user the ability to add and remove dynamic attribute from the script node via UI - Also allowed user to select a fixed, static type for their new attributes - Created a popup dialog window for the Add Attribute button, which has a search bar for the attribute types ### Removed - Removed the existing inputs:data and outputs:data attributes which are of type "any" ## [0.3.0] - 2022-02-18 ### Added - A default script with a simple example, and some comments explaining how to use the script node - Three example scripts to illustrate the various functionalities of the script node ### Changed - Move the script node widget into a template - Move the multiline editor to the top of property window, so that we don't have two multiline editors - Compile the script before executing it - Catch errors and log the errors ## [0.2.0] - 2022-02-15 ### Added - icon and category ## [0.1.2] - 2021-10-19 ### Modified - Restructured plugin files as part of repo relocation ## [0.1.1] - 2021-06-30 ### Modified - Change bundle input to Any type ## [0.1.0] - 2021-06-30 ### Added - Initial publish
3,239
Markdown
31.4
122
0.724298
omniverse-code/kit/exts/omni.graph.scriptnode/docs/README.md
# OgnScriptNode [omni.graph.scriptnode] Provides the Script Node for use in OmniGraph graphs. This node allows custom python code to be executed when the node is computed. The python code is compiled and computed when the graph runs using the embedded interpreter in Kit. The python script itself is stored as an attribute value in the USD where the graph is stored. Dynamic inputs and output attributes can be added to the node to provide inputs and outputs from the script.
478
Markdown
94.799981
435
0.807531
omniverse-code/kit/exts/omni.graph.scriptnode/docs/Overview.md
# OmniGraph Script Node Provides the Script Node for use in OmniGraph graphs. This node allows custom python code to be executed when the node is computed. The python code is compiled and computed when the graph runs using the embedded interpreter in Kit. The python script itself is stored as an attribute value in the USD where the graph is stored. Dynamic inputs and output attributes can be added to the node to provide inputs and outputs from the script. ```{csv-table} **Extension**: omni.graph.scriptnode,**Documentation Generated**: {sub-ref}`today` ```
564
Markdown
69.624991
435
0.783688
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_widget.py
from pathlib import Path from typing import Callable, Dict, List import os import traceback import sys import omni.ui as ui import carb import omni.kit.commands import omni.kit.app from omni.kit.widget.settings import get_style, get_ui_style_name from .rtx_settings_stack import RTXSettingsStack from omni.kit.window.file_importer import get_file_importer from omni.kit.window.file_exporter import get_file_exporter from .usd_serializer import USDSettingsSerialiser CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") RENDERER_CHANGED_EVT = carb.events.type_from_string( "render_settings.renderer.CHANGED" ) RENDERER_EVT_PAYLOAD_KEY = "renderer" # global renderers/stacks so any widget can use them registered_renderers: Dict[str, List[str]] = {} registered_stacks: Dict[str, Callable] = {} class RTXSettingsWidget(): engine_to_mode = { 'iray': '/rtx/iray/rendermode', 'rtx': '/rtx/rendermode', 'pxr': '/pxr/rendermode' } rendermode_to_settings = { 'RaytracedLighting': 'Real-Time', 'PathTracing': 'Interactive (Path Tracing)', 'iray': 'Accurate (Iray)' } def __init__(self, frame): style = None use_default_style = carb.settings.get_settings().get_as_bool("/persistent/app/window/useDefaultStyle") or False if not use_default_style: style = get_style() ui_style_name = get_ui_style_name() if ui_style_name == "NvidiaLight": option_icon_style = {"image_url": f"{ICON_PATH}/NvidiaLight/options.svg","color": 0xFF535354} else: option_icon_style = {"image_url": f"{ICON_PATH}/NvidiaDark/options.svg","color": 0xFF8A8777} self._option_icon_style = option_icon_style self._style = style self._frame = frame self._stack_frame = None self._renderer_model = None self._visible_stacks: Dict[str, RTXSettingsStack] = {} self.picker_open = False self._folder_exist_popup = None self._event_stream = omni.kit.app.get_app().get_message_bus_event_stream() def renderChangedSubscription(path): return omni.kit.app.SettingChangeSubscription(path, self.__active_renderer_changed) # If the viewport renderer is changed, update render settings to reflect it self._renderer_subscriptions = [renderChangedSubscription("/renderer/active")] # Also need to watch all engine-mode changes for _, path in self.engine_to_mode.items(): self._renderer_subscriptions.append(renderChangedSubscription(path)) # menu self._options_menu = ui.Menu("Options") with self._options_menu: ui.MenuItem("Load Settings", triggered_fn=self.load_from_usd) ui.MenuItem("Save Settings", triggered_fn=self.save_to_usd) ui.MenuItem("Reset Settings", triggered_fn=self.restore_all_settings) def destroy(self) -> None: """ """ for k, s in self._visible_stacks.items(): s.destroy() self._renderer_subscriptions = None def get_current_viewport_renderer(self, hydra_engine: str = None, render_mode: str = None): settings = carb.settings.get_settings() if hydra_engine is None: hydra_engine = settings.get('/renderer/active') if hydra_engine in self.engine_to_mode: if render_mode is None: render_mode = settings.get(self.engine_to_mode[hydra_engine]) # XXX: Delegate this to the render-settings-extension instance # (i.e.) let omni.hydra.pxr map HdStormRenderPlugin => Storm return self.rendermode_to_settings.get(render_mode, render_mode) return None def set_render_settings_to_viewport_renderer(self, hydra_engine: str = None, render_mode: str = None): renderer = self.get_current_viewport_renderer(hydra_engine, render_mode) if not renderer or not self._renderer_model: return renderer_list = list(registered_renderers.keys()) if renderer in renderer_list: index = renderer_list.index(renderer) self._renderer_model.get_item_value_model().set_value(index) def __active_renderer_changed(self, *args, **kwargs): self.set_render_settings_to_viewport_renderer() def build_ui(self) -> None: if not self._frame: return if self._style is not None: self._frame.set_style(self._style) self._frame.clear() with self._frame: with ui.VStack(spacing=5): ui.Spacer(height=5) with ui.HStack(height=20): ui.Spacer(width=20) ui.Label("Renderer", name="RenderLabel", width=80) renderer_list = list(registered_renderers.keys()) index = 0 current_renderer = self.get_current_viewport_renderer() #Set to the default renderer if it's there if current_renderer in renderer_list: index = renderer_list.index(current_renderer) self._renderer_model = ui.ComboBox(index, *renderer_list, name="renderer_choice").model self._renderer_model.add_item_changed_fn(lambda i, m: self.renderer_item_changed()) # build_stacks()) ui.Spacer(width=10) ui.Button( style=self._option_icon_style, width=20, clicked_fn=lambda: self._options_menu.show() ) ui.Spacer(width=10) ui.Spacer(height=0) self._stack_frame = ui.VStack() def build_stacks(self): """ "stacks" are the tabs in the Render Settings UI that contain groups of settings They can be reused amongst different renderers. This method is called every time the renderer is changed """ if not self._stack_frame: return for k, s in self._visible_stacks.items(): s.destroy() self._stack_frame.clear() if not registered_renderers: return current_renderer = self.get_current_renderer() current_renderer_stacks = registered_renderers.get(current_renderer, None) if not current_renderer_stacks: print("RTXSettingsWidget: renderer Not supported") return with self._stack_frame: # Build the stacks ("Common", "Ray Tracing" etc) self._collection = ui.RadioCollection() with ui.HStack(height=30): ui.Spacer(width=15) for name in current_renderer_stacks: ui.RadioButton( text=name, radio_collection=self._collection, clicked_fn=lambda p=name: self.show_stack_from_name(p), ) ui.Spacer(width=10) ui.Spacer(height=7) with ui.ScrollingFrame(): # stack pages with ui.ZStack(): for name in current_renderer_stacks: stack_class = registered_stacks.get(name, None) if not stack_class: continue self._visible_stacks[name] = stack_class() ui.Spacer(height=1) # Assume we want to show the middle stack - the renderer specific one if len(current_renderer_stacks) > 1 and self.have_stack(current_renderer_stacks[1]): self.show_stack_from_name(current_renderer_stacks[1]) def register_renderer(self, name: str, stacks_list: List[str]) -> None: registered_renderers[name] = stacks_list def register_stack(self, name: str, stack_class: Callable) -> None: registered_stacks[name] = stack_class self.build_stacks() def unregister_renderer(self, name): if name in registered_renderers: del registered_renderers[name] def unregister_stack(self, name): if name in registered_stacks: del registered_stacks[name] def set_current_renderer(self, renderer_name: str) -> None: """ sets the current renderer and updates the UI model """ if renderer_name in registered_renderers.keys(): renderer_names = list(registered_renderers.keys()) for cnt, r in enumerate(renderer_names): if r == renderer_name: self._renderer_model.get_item_value_model().set_value(cnt) def get_registered_renderers(self): return list(registered_renderers.keys()) def get_current_renderer(self) -> str: return list(registered_renderers.keys())[self._renderer_model.get_item_value_model().as_int] def have_stack(self, name: str) -> None: return name in self._visible_stacks.keys() def show_stack_from_name(self, name: str) -> None: if name not in self._visible_stacks.keys(): print("RTXSettingsWidget: Error No Key of that Name ") return for _, stack in self._visible_stacks.items(): stack.set_visible(False) # work out which index the named stack is in the current UI stack_index = 0 current_renderer_stack_names = registered_renderers.get(self.get_current_renderer(), None) for cnt, curr_stack_name in enumerate(current_renderer_stack_names): if curr_stack_name == name: stack_index = cnt self._visible_stacks[name].set_visible(True) self._collection.model.set_value(stack_index) def get_current_stack(self) -> str: for name, stack in self._visible_stacks.items(): if stack.get_visible(): return name return "" def get_renderer_stacks(self, renderer_name): return registered_renderers.get(renderer_name, None) def restore_all_settings(btn_widget): omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx") def save_to_usd(self): def save_handler(filename: str, dirname: str, extension: str = "", selections: List[str] = []): final_path = f"{dirname}{filename}{extension}" try: if os.path.exists(final_path): self._show_folder_exist_popup(final_path) else: serialiser = USDSettingsSerialiser() serialiser.save_to_usd(final_path) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback) file_exporter = get_file_exporter() if file_exporter: file_exporter.show_window( title="Save USD File", export_button_label="Save", export_handler=save_handler, file_postfix_options=["settings"]) def load_from_usd(self): def load_handler(filename: str, dirname: str, selections: List[str]): final_path = f"{dirname}{filename}" try: serialiser = USDSettingsSerialiser() serialiser.load_from_usd(final_path) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback) file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Load USD File", import_button_label="Load", import_handler=load_handler, file_postfix_options=["settings"]) def renderer_item_changed(self) -> None: try: self._emit_renderer_changed_event() finally: self.build_stacks() def _emit_renderer_changed_event(self) -> None: payload = {RENDERER_EVT_PAYLOAD_KEY: self.get_current_renderer()} self._event_stream.push( event_type=RENDERER_CHANGED_EVT, payload=payload )
12,147
Python
37.811501
122
0.595044
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_window.py
import omni.ui as ui import carb from typing import Callable, Dict, List from .rtx_settings_widget import RTXSettingsWidget class RTXSettingsWindow: def __init__(self): self._window = None if carb.settings.get_settings().get("/exts/omni.rtx.window.settings/startup/autoCreateWindow"): self._window = ui.Window("Render Settings", dockPreference=ui.DockPreference.RIGHT_TOP) self._window.deferred_dock_in("Stage", ui.DockPolicy.TARGET_WINDOW_IS_ACTIVE) self._settings_widget = RTXSettingsWidget(self._window.frame) self._build_ui() else: self._settings_widget = RTXSettingsWidget(None) def register_renderer(self, name: str, stacks_list: List[str]) -> None: return self._settings_widget.register_renderer(name, stacks_list) def get_registered_renderers(self): return self._settings_widget.get_registered_renderers() def get_current_renderer(self): return self._settings_widget.get_current_renderer() def set_current_renderer(self, renderer_name: str) -> None: return self._settings_widget.set_current_renderer(renderer_name) def register_stack(self, name: str, stack_class: Callable) -> None: return self._settings_widget.register_stack(name, stack_class) def show_stack_from_name(self, name: str) -> None: return self._settings_widget.show_stack_from_name(name) def get_renderer_stacks(self, renderer_name): return self._settings_widget.get_renderer_stacks(renderer_name) def get_current_stack(self) -> str: return self._settings_widget.get_current_stack() def unregister_renderer(self, name): return self._settings_widget.unregister_renderer(name) def unregister_stack(self, name): return self._settings_widget.unregister_stack(name) def set_visibility_changed_listener(self, listener): if self._window: self._window.set_visibility_changed_fn(listener) def set_render_settings_to_viewport_renderer(self, *args, **kwargs): return self._settings_widget.set_render_settings_to_viewport_renderer(*args, **kwargs) def set_visible(self, value: bool) -> None: if self._window: self._window.visible = value def destroy(self) -> None: """ """ self._settings_widget.destroy() self._settings_widget = None self._window = None def _build_ui(self) -> None: """ """ self._settings_widget.build_ui() def _build_stacks(self) -> None: """ "stacks" are the tabs in the Render Settings UI that contain groups of settings They can be reused amongst different renderers. This method is called every time the renderer is changed """ self._settings_widget.build_stacks()
2,843
Python
35.935064
103
0.663384
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/commands.py
import carb import carb.dictionary import carb.settings import omni.kit.commands from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from omni.rtx.window.settings import RendererSettingsFactory class RestoreDefaultRenderSettingCommand(omni.kit.commands.Command): """ Restore default setting for Renderer **Command**. Args: path: Path to the setting to be reset. """ def __init__(self, path: str): self._path = path self._settings = carb.settings.get_settings() def do(self): self._value = self._settings.get(self._path) RenderSettingsDefaults().reset_setting_to_default(self._path) def undo(self): self._settings.set(self._path, self._value) class RestoreDefaultRenderSettingSectionCommand(omni.kit.commands.Command): """ Restore default settings for the whole section **Command**. Args: path: Path to the settings section to be reset. """ def __init__(self, path: str): self._path = path self._settings = carb.settings.get_settings() def do(self): self._section_copy = self._settings.create_dictionary_from_settings(self._path) RenderSettingsDefaults().reset_setting_to_default(self._path) def undo(self): self._settings.destroy_item(self._path) self._settings.update(self._path, self._section_copy, "", carb.dictionary.UpdateAction.OVERWRITE) class SetCurrentRenderer(omni.kit.commands.Command): """ Sets the current renderer Args: renderer_name: name of the renderer """ def __init__(self, renderer_name: str): self._renderer = renderer_name self._prev_renderer = None def do(self): self._prev_renderer = RendererSettingsFactory.get_current_renderer() RendererSettingsFactory.set_current_renderer(self._renderer) def undo(self): if self._prev_renderer: RendererSettingsFactory.set_current_renderer(self._prev_renderer) class SetCurrentStack(omni.kit.commands.Command): """ Sets the current stack (needs to be one which is valid for the current renderer) Args: stack_name: name of the stack """ def __init__(self, stack_name: str): self._stack = stack_name self._prev_stack = None def do(self): self._prev_stack = RendererSettingsFactory.get_current_stack() RendererSettingsFactory.set_current_stack(self._stack) def undo(self): if self._prev_stack: RendererSettingsFactory.set_current_stack(self._prev_stack) omni.kit.commands.register_all_commands_in_module(__name__)
2,664
Python
28.285714
105
0.671547
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_stack.py
import omni.ui as ui from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame class RTXSettingsStack: """ define a stack of Settings Widgets """ def __init__(self) -> None: self._stack: ui.VStack = None def set_visible(self, value: bool): if self._stack: self._stack.visible = value def get_visible(self) -> bool: if self._stack: return self._stack.visible return False def destroy(self): if self in SettingsCollectionFrame.parents: mySettingsFrames = SettingsCollectionFrame.parents[self] for frame in mySettingsFrames: frame.destroy() del SettingsCollectionFrame.parents[self]
751
Python
27.923076
86
0.637816
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/extension.py
from functools import partial from typing import Callable, List import omni.ext import omni.kit.ui import omni.ui as ui import carb.settings from .rtx_settings_window import RTXSettingsWindow class RTXSettingsExtension(omni.ext.IExt): """The entry point for the extension""" WINDOW_NAME = "Render Settings" def __init__(self) -> None: super().__init__() RendererSettingsFactory.render_settings_extension_instance = self self._settings_window = RTXSettingsWindow() self._settings_window.set_visibility_changed_listener(self._visiblity_changed_fn) def on_startup(self): ui.Workspace.set_show_window_fn(self.WINDOW_NAME, partial(self.show_window, None)) window_menu = carb.settings.get_settings().get("exts/omni.rtx.window.settings/window_menu") self._menu_path = f"{window_menu}/{self.WINDOW_NAME}" editor_menu = omni.kit.ui.get_editor_menu() self._menu = None if editor_menu: self._menu = editor_menu.add_item( f"{self._menu_path}", self.show_window, priority=21, toggle=True, value=True, ) ui.Workspace.show_window(self.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._settings_window: self._settings_window.set_visibility_changed_listener(None) self._settings_window.destroy() self._settings_window = None RendererSettingsFactory.render_settings_extension_instance = None ui.Workspace.set_show_window_fn(RTXSettingsExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(f"{self._menu_path}", value) def _visiblity_changed_fn(self, visible): if visible: self._set_menu(visible) else: self.show_window(None, False) def show_window(self, menu, value): self._set_menu(value) self._settings_window.set_visible(value) def show_render_settings(self, hd_engine: str, render_mode: str, show_window: bool = True): self._settings_window.set_render_settings_to_viewport_renderer(hd_engine, render_mode) if not show_window: return self.show_window(self._menu_path, True) async def focus_async(): window = ui.Workspace.get_window(self.WINDOW_NAME) if window: window.focus() import asyncio asyncio.ensure_future(focus_async()) class RendererSettingsFactory: """ entry point for other extensions to register renderers and settings stacks """ render_settings_extension_instance = None @classmethod def _get_render_settings_extension(cls): if not cls.render_settings_extension_instance: cls.render_settings_extension_instance = RTXSettingsExtension() return cls.render_settings_extension_instance @classmethod def register_renderer(cls, name: str, stacks_list: List[str]): rs = cls._get_render_settings_extension() rs._settings_window.register_renderer(name, stacks_list) rs._settings_window._build_ui() @classmethod def unregister_renderer(cls, name): rs = cls._get_render_settings_extension() rs._settings_window.unregister_renderer(name) @classmethod def build_ui(cls): """ This method may be called by either: + a dependent extension that's shutting down or starting up + when the app is shutting down We want to distinguish between them """ if omni.kit.app.get_app().is_running(): rs = cls._get_render_settings_extension() rs._settings_window._build_ui() rs._settings_window._build_stacks() @classmethod def set_current_renderer(cls, renderer_name: str) -> None: """ sets the current stack and updates the UI model """ rs = cls._get_render_settings_extension() rs._settings_window.set_current_renderer(renderer_name) @classmethod def get_current_renderer(cls): rs = cls._get_render_settings_extension() return rs._settings_window.get_current_renderer() @classmethod def register_stack(cls, name: str, stack_class: Callable): rs = cls._get_render_settings_extension() rs._settings_window.register_stack(name, stack_class) @classmethod def unregister_stack(cls, name) -> None: rs = cls._get_render_settings_extension() rs._settings_window.unregister_stack(name) @classmethod def set_current_stack(cls, name) -> None: """ sets the current stack and updates the UI model """ rs = cls._get_render_settings_extension() rs._settings_window.show_stack_from_name(name) @classmethod def get_current_stack(cls) -> str: rs = cls._get_render_settings_extension() return rs._settings_window.get_current_stack() @classmethod def get_registered_renderers(cls) -> list: rs = cls._get_render_settings_extension() return rs._settings_window.get_registered_renderers() @classmethod def get_renderer_stacks(cls, renderer) -> list: rs = cls._get_render_settings_extension() return rs._settings_window.get_renderer_stacks(renderer)
5,518
Python
32.858896
99
0.633563
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/__init__.py
from .extension import * from .commands import *
50
Python
11.749997
24
0.74
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/usd_serializer.py
import carb import os.path import omni.kit.commands import rtx.settings from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from pxr import Usd, Gf class USDSettingsSerialiser: """ Save and Load RTX settings to/from USD @TOOD: get rtx:fog:fogColor working """ def __init__(self): self._settings = carb.settings.get_settings() def iterate_settings(self, usd_dict, d, path_string=""): for k, v in d.items(): key_string = path_string + "/" + str(k) if isinstance(v, dict): self.iterate_settings(usd_dict, v, path_string=path_string + "/" + k) else: default_flags = self._settings.get(rtx.settings.get_associated_setting_flags_path(key_string)) if default_flags is None or (default_flags & rtx.settings.SETTING_FLAGS_TRANSIENT): continue val = self._settings.get(key_string) default_key = RenderSettingsDefaults._get_associated_defaults_path(key_string) default_val = self._settings.get(default_key) usd_str = key_string.replace("/", ":") if default_val != val: # TODO: This code looks fairly dodgy if isinstance(val, list) and len(val) in [3, 4]: if isinstance(val[0], float): usd_dict[usd_str[1:]] = Gf.Vec3f(val) else: usd_dict[usd_str[1:]] = Gf.Vec3d(val) else: usd_dict[usd_str[1:]] = val def save_to_usd(self, stage_file_path=""): if os.path.exists(stage_file_path): curr_stage = Usd.Stage.Open(stage_file_path) # Save or overwrite else: curr_stage = Usd.Stage.CreateNew(stage_file_path) rootLayer = curr_stage.GetRootLayer() customLayerData = rootLayer.customLayerData settings_dict = self._settings.get_settings_dictionary("/rtx") usdDict = {} self.iterate_settings(usdDict, settings_dict.get_dict(), "/rtx") customLayerData["renderSettings"] = usdDict rootLayer.customLayerData = customLayerData curr_stage.Save() carb.log_info(f"saved {stage_file_path} {len(usdDict)} settings") def load_from_usd(self, stage_file_path=""): currStage = Usd.Stage.Open(stage_file_path) rootLayer = currStage.GetRootLayer() customLayerData = rootLayer.customLayerData renderSettingsVtVal = customLayerData["renderSettings"] loaded_count = 0 if renderSettingsVtVal: omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx") for k, v in renderSettingsVtVal.items(): rtx_key = k.replace(":", "/") default_flags = self._settings.get(rtx.settings.get_associated_setting_flags_path(rtx_key)) if default_flags is None or (default_flags & rtx.settings.SETTING_FLAGS_TRANSIENT): continue if isinstance(v, Gf.Vec3f) or isinstance(v, Gf.Vec3d): self._settings.set("/" + rtx_key, [v[0], v[1], v[2]]) else: self._settings.set(rtx_key, v) loaded_count += 1 carb.log_info(f"loaded {stage_file_path} {loaded_count} settings")
3,440
Python
39.011627
110
0.575291
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rendersettingsdefaults.py
import carb.dictionary import carb.settings class SettingsDefaultHandler: def __init__(self): self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() def _get_sanitized_path(self, path): if path is not None and len(path) > 0 and path[0] == "/": return path[1:] return "" def get_type(self, path): settings_dict = self._settings.get_settings_dictionary("") path = self._get_sanitized_path(path) item = self._dictionary.get_item(settings_dict, path) item_type = self._dictionary.get_item_type(item) return item_type def does_exist(self, path): return self.get_type(path) != carb.dictionary.ItemType.COUNT def set_default(self, path): item_type = self.get_type(path) if item_type == carb.dictionary.ItemType.FLOAT: self._settings.set(path, 0.0) elif item_type == carb.dictionary.ItemType.INT: self._settings.set(path, 0) elif item_type == carb.dictionary.ItemType.BOOL: self._settings.set(path, False) else: print("SettingsDefaultHandler unrecognised type", item_type) class RenderSettingsDefaults: """ This is a partial python implementation of Kit/rendering/include/rtx/utils/Settings.h which only provides sufficient functionality for getting/resetting default values by """ _settings = carb.settings.get_settings() _settings_dict = _settings.get_settings_dictionary("") @classmethod def _get_associated_defaults_path(cls, settings_path: str): bits = settings_path.split("/") if len(bits) == 2: return "/" + bits[1] + "-defaults" else: return "/" + bits[1] + "-defaults/" + "/".join(bits[2:]) def reset_setting_to_default(self, settings_path: str): defaultsPathStorage = self._get_associated_defaults_path(settings_path) srcItem = self._settings.get_settings_dictionary(defaultsPathStorage) # If we can't find a dictionary item, it's likely to be leaf node/scalar value if not srcItem: defaultValue = self._settings.get(defaultsPathStorage) self._settings.set(settings_path, defaultValue) # It's a dictionary Item.. just update the whole section elif isinstance(srcItem, carb.dictionary._dictionary.Item): self._settings.update(settings_path, srcItem, "", carb.dictionary.UpdateAction.OVERWRITE) else: print("reset_setting_to_default: unknown type")
2,597
Python
37.205882
101
0.640739
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/settings_collection_frame.py
from typing import Union, Any import carb.settings from omni.kit.widget.settings import SettingType import omni.kit.commands import omni.rtx.window.settings import omni.ui as ui from omni.kit.widget.settings import create_setting_widget, create_setting_widget_combo from omni.kit.widget.settings import SettingsWidgetBuilder, SettingsSearchableCombo import rtx.settings class FrameSessionState: """ stre any state we would like to persist across the Session """ frame_state = {} @classmethod def get_state(cls, frame_id: str, key: str) -> Any: if frame_id not in cls.frame_state: return None if key not in cls.frame_state[frame_id]: return None return cls.frame_state[frame_id][key] @classmethod def has_state(cls, frame_id: str, key: str) -> bool: if frame_id not in cls.frame_state: return False if key not in cls.frame_state[frame_id]: return False return True @classmethod def set_state(cls, frame_id: str, key: str, value: Any) -> None: if frame_id not in cls.frame_state: cls.frame_state[frame_id] = {} cls.frame_state[frame_id][key] = value class SettingsCollectionFrame: parents = {} # For later deletion of parents def __init__(self, frame_label: str, collapsed=True, parent=None) -> None: self.classNamespace = ".".join([self.__class__.__module__, self.__class__.__name__]) self._settings = carb.settings.get_settings() self._collapsedState = collapsed self._setting_path = self._frame_setting_path() if FrameSessionState.has_state(self.classNamespace, "collapsed"): self._collapsedState = FrameSessionState.get_state(self.classNamespace, "collapsed") self._widget = ui.CollapsableFrame( frame_label, height=0, build_fn=self.build_ui, build_header_fn=self.build_header, skip_draw_when_clipped=True, collapsed=self._collapsedState, ) self._widget.identifier = frame_label self._widget.set_collapsed_changed_fn(self.on_collapsed_changed) self.sub_widgets = [] self.sub_models = [] # store a reference to our parent to allow later destruction if parent: if parent in self.parents: self.parents[parent].append(self) else: self.parents[parent] = [self] def _frame_setting_path(self): """ subclass can overtide that to get a checkbox in the frame """ return None def destroy(self): """ We need to explicitly destroy widgets/models - there's usually a number of circular ref between model and Widget which can be difficult to track down and keep widgets alive after the Frame is rebuilt """ for w in self.sub_models: w.destroy() self.sub_models = [] for w in self.sub_widgets: del w self.sub_widgets = [] self._widget.set_collapsed_changed_fn(None) self._widget.set_build_fn(None) self._widget.clear() self._widget = None def _on_change(self, *_): self._rebuild() def on_collapsed_changed(self, collapsed): FrameSessionState.set_state(self.classNamespace, "collapsed", collapsed) def build_header(self, collapsed, title): triangle_alignment = ui.Alignment.RIGHT_CENTER triangle_width = 4 triangle_height = 6 if not collapsed: triangle_alignment = ui.Alignment.CENTER_BOTTOM triangle_width = 7 triangle_height = 5 with ui.HStack(height=20, style={"HStack": {"margin_height": 5}}): ui.Spacer(width=5) with ui.VStack(width=15): ui.Spacer() ui.Triangle( alignment=triangle_alignment, name="title", width=triangle_width, height=triangle_height, # Using the style defined in style.py" # style={"background_color": 0xFFCCCCCC}, ) ui.Spacer() ui.Label(title, name="title", width=0) ui.Spacer() if self._setting_path: with ui.VStack(width=20, content_clipping=True): ui.Spacer(height=4) widget, model = create_setting_widget(self._setting_path, SettingType.BOOL) if widget and model: widget.set_tooltip("Check to Activate") def expand_frame(model, frame): if frame: frame.collapsed = not model.get_value_as_bool() model.add_value_changed_fn(lambda m, frame=self._widget: expand_frame(m, frame)) ui.Spacer() def build_ui(self): with ui.VStack(height=0, spacing=5, style={"VStack": {"margin_width": 10}}): ui.Spacer(height=5) self._build_ui() ui.Spacer(height=5) def _rebuild(self): if self._widget: self._widget.rebuild() def _restore_defaults(self, path: str): omni.kit.commands.execute("RestoreDefaultSetting", path=path) def _add_setting( self, setting_type, name: str, path: str, range_from=0, range_to=0, speed=1, has_reset=True, tooltip="", hard_range=False, cleartext_path=None ): the_stack = ui.HStack(skip_draw_when_clipped=True) the_stack.identifier = "HStack_" + name.replace(" ","_") with the_stack: SettingsWidgetBuilder._create_label(name, path if not cleartext_path else cleartext_path, tooltip) widget, model = create_setting_widget(path, setting_type, range_from, range_to, speed, hard_range=hard_range) self.sub_widgets.append(widget) self.sub_models.append(model) if has_reset: button = SettingsWidgetBuilder._build_reset_button(path) model.set_reset_button(button) return widget def _add_internal_setting( self, setting_type, name: str, path: str, range_from=0, range_to=0, speed=1, has_reset=True, tooltip="" ): internal_path = rtx.settings.get_internal_setting_string(path) return self._add_setting(setting_type, name, internal_path, range_from, range_to, speed, has_reset, tooltip, cleartext_path=path) def _add_setting_combo( self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip="", cleartext_path=None ): the_stack = ui.HStack(skip_draw_when_clipped=True) the_stack.identifier = "HStack_" + name.replace(" ","_") with the_stack: SettingsWidgetBuilder._create_label(name, path if not cleartext_path else cleartext_path, tooltip) widget, model = create_setting_widget_combo(path, items) self.sub_widgets.append(widget) self.sub_models.append(model) if has_reset: button = SettingsWidgetBuilder._build_reset_button(path) model.set_reset_button(button) return widget def _add_setting_searchable_combo(self, name: str, path: str, items: dict, default_item: str, tooltip=""): with ui.HStack(): SettingsWidgetBuilder._create_label(name, path, tooltip) widget = SettingsSearchableCombo(path, items, default_item) self.sub_widgets.append(widget) def _add_internal_setting_combo( self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip="" ): internal_path = rtx.settings.get_internal_setting_string(path) return self._add_setting_combo(name, internal_path, items, callback, has_reset, tooltip, cleartext_path=path) def _get_internal_setting(self, path: str): return self._settings.get(rtx.settings.get_internal_setting_string(path)) def _subscribe_to_internal_setting_change(self, path: str): omni.kit.app.SettingChangeSubscription(rtx.settings.get_internal_setting_string(path), self._on_change) def _build_ui(self): """ virtual function that will be called in the Collapsable frame """ pass
8,412
Python
37.240909
124
0.601046
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_defaults.py
import omni.kit.test import carb.settings from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from omni.rtx.window.settings import commands from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows import omni.kit.commands class TestDefaults(omni.kit.test.AsyncTestCase): async def setUp(self): super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() settings = carb.settings.get_settings() # Am not sure what sets the default normally.. settings.set("/rtx-defaults/pathtracing/maxBounces", 4) async def test_rtx_setting(self): """ Test single item /rtx/pathtracing/maxBounces """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_rtx_setting_section(self): """ Test section /rtx/pathtracing """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx/pathtracing") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx/pathtracing") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_rtx_settings_all(self): """ Test entire section /rtx """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_commands(self): settings = carb.settings.get_settings() settings.set("/rtx/pathtracing/maxBounces", 15) omni.kit.commands.execute("RestoreDefaultRenderSetting", path="/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 16) omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4)
3,336
Python
40.19753
121
0.668465
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_serialiser.py
import os import tempfile import omni.kit.test import carb.settings import omni.kit.commands from omni.rtx.window.settings import RendererSettingsFactory from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows class TestSerialiser(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # After running each test async def tearDown(self): pass async def test_serialiser(self): from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser with tempfile.TemporaryDirectory() as tempdir: file = os.path.join(tempdir, "test.usd") serialiser = USDSettingsSerialiser() serialiser.save_to_usd(file) serialiser.load_from_usd(file)
925
Python
30.931033
121
0.724324
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/__init__.py
from .test_defaults import * from .test_ui import * from .test_serialiser import *
83
Python
19.999995
30
0.746988
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_ui.py
import omni.kit.test import carb.settings import omni.kit.commands from omni.rtx.window.settings import RendererSettingsFactory import random class SettingsIterator(object): def __init__(self, output_dict): self._settings = carb.settings.get_settings() self._output_dict = output_dict def iterate(self, settings_dict, path_string=""): """ iterate rtx settings and get a flat dictionary back we can work with """ for k, v in settings_dict.items(): key_string = path_string + "/" + str(k) if isinstance(v, dict): self.iterate(v, path_string=path_string + "/" + k) else: val = self._settings.get(key_string) self._output_dict[key_string] = val class TestSetRenderSettings: @classmethod def generate_change_setting_command(cls, setting_path, current_value): if isinstance(current_value, bool): bool_choice = random.choice([True, False]) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=bool_choice) elif isinstance(current_value, float): float_choice = 0.0 if abs(current_value) < 0.1: float_choice = random.uniform(0, 100) else: # TODO: We can make a better guess if we have more info about the range float_choice = random.uniform(current_value / 2, current_value * 2) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=float_choice) elif isinstance(current_value, int): int_choice = 0 if current_value == 0: int_choice = random.choice(range(0, 100)) else: int_range = range(int(current_value / 2), int(current_value * 2)) if len(int_range) > 1: int_choice = random.choice(range(int(current_value / 2), int(current_value * 2))) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=int_choice) elif isinstance(current_value, list): # TODO: add pass elif isinstance(current_value, str): # TODO: Without a bit more info (e.g from the "add_setting" calls in the UI) # it's hard to know what to do with strings - they could be filepaths/assets, # combo box elements etc. We should probably look at extracting that data pass else: print("this type is not supported") async def run_test_render_settings_ui(self, settings_path: str): """ we're really not attempting to assert anything here, just cycle through a bunch of commands and hope it doesn't segfault """ settings = carb.settings.get_settings() # if the renderers have initialised properly, this should have items settings_dict = settings.get_settings_dictionary(settings_path) output_dict = {} settingsIt = SettingsIterator(output_dict) settingsIt.iterate(settings_dict.get_dict(), settings_path) setting_list = list(output_dict) # TODO: add in ResetAllSettings and other commands # Set some settings, switch renderer, set stack, and do the same again several times for x in range(0, 20): for y in range(0, 10): key = random.choice(setting_list) self.generate_change_setting_command(key, output_dict[key]) await omni.kit.app.get_app().next_update_async() renderers = RendererSettingsFactory.get_registered_renderers() if renderers: renderer_choice = random.choice(RendererSettingsFactory.get_registered_renderers()) omni.kit.commands.execute("SetCurrentRenderer", renderer_name=renderer_choice) await omni.kit.app.get_app().next_update_async() for y in range(0, 10): key = random.choice(setting_list) self.generate_change_setting_command(key, output_dict[key]) await omni.kit.app.get_app().next_update_async() stacks = RendererSettingsFactory.get_renderer_stacks(renderer_choice) if stacks: stack_choice = random.choice(stacks) omni.kit.commands.execute("SetCurrentStack", stack_name=stack_choice) await omni.kit.app.get_app().next_update_async() # If we have get a crash, we should be able to replay it outside the unit testing framework # with commands... history = omni.kit.undo.get_history().values() for cmd in history: continue # print (cmd) class TestRTXCommandsDefaults(TestSetRenderSettings, omni.kit.test.AsyncTestCase): async def test_rtx_settings_ui(self): import omni.ui as ui w = ui.Workspace.get_window("Render Settings") w.position_x = 0 w.position_y = 20 w.width = 1440 w.height = 840 return await self.run_test_render_settings_ui("/rtx")
5,121
Python
41.683333
101
0.603788
omniverse-code/kit/exts/omni.rtx.window.settings/rtx/settings.pyi
"""pybind11 rtx.settings bindings""" from __future__ import annotations import rtx.settings import typing __all__ = [ "SETTING_FLAGS_NONE", "SETTING_FLAGS_RESET_DISABLED", "SETTING_FLAGS_TRANSIENT", "get_associated_setting_flags_path", "get_internal_setting_string" ] def get_associated_setting_flags_path(arg0: str) -> str: """ Gets the associated internal setting path to modify the behavior flags that are assigned to each rtx setting. It must be set before the app starts or before RTX plugins are loaded to avoid rtx-defaults from being set mistakenly. This path is simply produced by replacing 'rtx' parent in the setting path with 'rtx-flags'. It allows the behavior of RTX settings to be overridden via SETTING_FLAGS_X flags/attributes. Note that using SETTING_FLAGS_TRANSIENT will cause such settings to not be saved to or loaded from USD. Args: settingPath: RTX setting path to get the associated rtx-flags. Returns: The equivalent rtx setting flag path as string. """ def get_internal_setting_string(arg0: str) -> str: pass SETTING_FLAGS_NONE = 0 SETTING_FLAGS_RESET_DISABLED = 2 SETTING_FLAGS_TRANSIENT = 1
1,278
unknown
35.542856
130
0.680751