file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/__init__.py
from .common import human_delay, wait_n_updates, InitExt from .vec2 import Vec2 from .input import ( emulate_mouse_click, emulate_mouse_move, emulate_mouse_move_and_click, emulate_mouse_drag_and_drop, emulate_mouse_scroll, emulate_keyboard_press, emulate_char_press, emulate_key_combo, KeyDownScope, ) from .query import WidgetRef, WindowRef, find, find_all, get_menubar, menu_click from .menu import select_context_menu, get_context_menu
475
Python
28.749998
80
0.730526
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/menu.py
from __future__ import annotations import re import logging from omni import ui from .input import emulate_mouse_move, emulate_mouse_click from .common import human_delay, wait_n_updates_internal from .vec2 import Vec2 logger = logging.getLogger(__name__) def _find_menu_item(query, menu_root): menu_items = ui.Inspector.get_children(menu_root) for menu_item in menu_items: if isinstance(menu_item, ui.MenuItem) or isinstance(menu_item, ui.Menu): name = re.sub(r"[^\x00-\x7F]+", " ", menu_item.text).lstrip() if query == name: return menu_item return None def _find_context_menu_item(query, menu_root, find_fn=_find_menu_item): tokens = re.split(r'(?<!/)/(?!/)', query) child = menu_root for i in range(0, len(tokens)): token = tokens[i].replace("//", "/") child = find_fn(token, child) if not child: break return child async def select_context_menu( menu_path: str, menu_root: ui.Widget = None, offset=Vec2(100, 10), human_delay_speed: int = 4, find_fn=_find_menu_item ): """Emulate selection of context menu item with mouse. Supports nested menus separated by `/`: .. code-block:: python await ui_test.select_context_menu("Option/Select/All") This function waits for current menu for some time first. Unless `menu_root` was passed explicitly. When there are nested menu mouse moves to each of them and makes human delay for it to open. Then is emulates mouse click on final menu item. """ logger.info(f"select_context_menu: {menu_path} (offset: {offset})") MAX_WAIT = 100 # Find active menu for _ in range(MAX_WAIT): menu_root = menu_root or ui.Menu.get_current() if menu_root: break await wait_n_updates_internal(1) if not menu_root: raise Exception("Can't find context menu, wait time exceeded.") for _ in range(MAX_WAIT): if menu_root.shown: break await wait_n_updates_internal(1) if not menu_root.shown: raise Exception("Context menu is not visible, wait time exceeded.") sub_items = re.split(r'(?<!/)/(?!/)', menu_path) sub_menu_item = "" for item in sub_items: sub_menu_item = f"{sub_menu_item}/{item}" if sub_menu_item else f"{item}" menu_item = _find_context_menu_item(sub_menu_item, menu_root, find_fn) if not menu_item: raise Exception(f"Can't find menu item with path: '{menu_path}'. sub_menu_item: '{sub_menu_item}'") await emulate_mouse_move(Vec2(menu_item.screen_position_x, menu_item.screen_position_y) + offset) await human_delay(human_delay_speed) await emulate_mouse_click() await human_delay(human_delay_speed) async def get_context_menu(menu_root: ui.Widget = None, get_all: bool=False): logger.info(f"get_context_menu: {menu_root}") MAX_WAIT = 100 # Find active menu for _ in range(MAX_WAIT): menu_root = menu_root or ui.Menu.get_current() if menu_root: break await wait_n_updates_internal(1) if not menu_root: raise Exception("Can't find context menu, wait time exceeded.") for _ in range(MAX_WAIT): if menu_root.shown: break await wait_n_updates_internal(1) if not menu_root.shown: raise Exception("Context menu is not visible, wait time exceeded.") menu_dict = {} def list_menu(menu_root, menu_dict): for menu_item in ui.Inspector.get_children(menu_root): if not get_all and (not menu_item.enabled or not menu_item.visible): continue if isinstance(menu_item, ui.MenuItem) or isinstance(menu_item, ui.Menu) or (isinstance(menu_item, ui.Separator) and get_all): name = re.sub(r"[^\x00-\x7F]+", " ", menu_item.text).lstrip() if isinstance(menu_item, ui.Menu): if not name in menu_dict: menu_dict[name] = {} list_menu(menu_item, menu_dict[name]) elif menu_item.has_triggered_fn(): if not "_" in menu_dict: menu_dict["_"] = [] menu_dict["_"].append(name) elif get_all: menu_dict["_"].append(name) list_menu(menu_root, menu_dict) return menu_dict
4,409
Python
32.923077
137
0.603311
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/input.py
import carb import carb.input import omni.kit.app import omni.ui as ui import carb.windowing import omni.appwindow from carb.input import MouseEventType, KeyboardEventType, KeyboardInput import logging from functools import lru_cache from itertools import chain from .vec2 import Vec2 from .common import human_delay, wait_n_updates_internal logger = logging.getLogger(__name__) @lru_cache() def _get_windowing() -> carb.windowing.IWindowing: return carb.windowing.acquire_windowing_interface() @lru_cache() def _get_input_provider() -> carb.input.InputProvider: return carb.input.acquire_input_provider() async def emulate_mouse(event_type: MouseEventType, pos: Vec2 = Vec2()): app_window = omni.appwindow.get_default_app_window() mouse = app_window.get_mouse() window_width = ui.Workspace.get_main_window_width() window_height = ui.Workspace.get_main_window_height() pos = pos * ui.Workspace.get_dpi_scale() _get_input_provider().buffer_mouse_event( mouse, event_type, (pos.x / window_width, pos.y / window_height), 0, pos.to_tuple() ) if event_type == MouseEventType.MOVE: _get_windowing().set_cursor_position(app_window.get_window(), (int(pos.x), int(pos.y))) async def emulate_mouse_click(right_click=False, double=False): """Emulate Mouse single or double click.""" for _ in range(2 if double else 1): await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN) await wait_n_updates_internal() await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP) await wait_n_updates_internal() async def emulate_mouse_move(pos: Vec2, human_delay_speed: int = 2): """Emulate Mouse move into position.""" logger.info(f"emulate_mouse_move to: {pos}") await emulate_mouse(MouseEventType.MOVE, pos) await human_delay(human_delay_speed) async def emulate_mouse_move_and_click(pos: Vec2, right_click=False, double=False, human_delay_speed: int = 2): """Emulate Mouse move into position and click.""" logger.info(f"emulate_mouse_move_and_click pos: {pos} (right_click: {right_click}, double: {double})") await emulate_mouse(MouseEventType.MOVE, pos) await emulate_mouse_click(right_click=right_click, double=double) await human_delay(human_delay_speed) async def emulate_mouse_slow_move(start_pos, end_pos, num_steps=8, human_delay_speed: int = 4): """Emulate Mouse slow move. Mouse is moved in steps between start and end with the human delay between each step.""" step = (end_pos - start_pos) / num_steps for i in range(0, num_steps + 1): await emulate_mouse(MouseEventType.MOVE, start_pos + step * i) await human_delay(human_delay_speed) async def emulate_mouse_drag_and_drop(start_pos, end_pos, right_click=False, human_delay_speed: int = 4): """Emulate Mouse Drag & Drop. Click at start position and slowly move to end position.""" logger.info(f"emulate_mouse_drag_and_drop pos: {start_pos} -> {end_pos} (right_click: {right_click})") await emulate_mouse(MouseEventType.MOVE, start_pos) await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN) await human_delay(human_delay_speed) await emulate_mouse_slow_move(start_pos, end_pos, human_delay_speed=human_delay_speed) await human_delay(human_delay_speed) await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP) await human_delay(human_delay_speed) async def emulate_mouse_scroll(delta: Vec2, human_delay_speed: int = 2): """Emulate Mouse scroll by delta.""" logger.info(f"emulate_mouse_scroll: {delta}") await emulate_mouse(MouseEventType.SCROLL, delta) await human_delay(human_delay_speed) async def emulate_keyboard(event_type: KeyboardEventType, key: KeyboardInput, modifier: carb.input.KeyboardInput = 0): logger.info(f"emulate_keyboard event_type: {event_type}, key: {key} modifier:{modifier}") keyboard = omni.appwindow.get_default_app_window().get_keyboard() _get_input_provider().buffer_keyboard_key_event(keyboard, event_type, key, modifier) MODIFIERS_TO_KEY = { carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL: KeyboardInput.LEFT_CONTROL, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT: KeyboardInput.LEFT_SHIFT, carb.input.KEYBOARD_MODIFIER_FLAG_ALT: KeyboardInput.LEFT_ALT, } async def emulate_keyboard_press( key: KeyboardInput, modifier: carb.input.KeyboardInput = 0, human_delay_speed: int = 2 ): """Emulate Keyboard key press. Down and up.""" # Figure out which modifier keys need to be pressed mods = [] for k in MODIFIERS_TO_KEY.keys(): if modifier & k: mods.append(k) modifier = 0 for k in mods: modifier = modifier | k # modifier is added for the press await emulate_keyboard(KeyboardEventType.KEY_PRESS, MODIFIERS_TO_KEY[k], modifier) await human_delay(human_delay_speed) await emulate_keyboard(KeyboardEventType.KEY_PRESS, key, modifier) await human_delay(human_delay_speed) await emulate_keyboard(KeyboardEventType.KEY_RELEASE, key, modifier) await human_delay(human_delay_speed) # Back off the modifiers for k in reversed(mods): modifier = modifier & ~k # modifier is removed for the release await emulate_keyboard(KeyboardEventType.KEY_RELEASE, MODIFIERS_TO_KEY[k], modifier) await human_delay(human_delay_speed) MODIFIERS_MAP = { "CTRL": (KeyboardInput.LEFT_CONTROL, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), "CONTROL": (KeyboardInput.LEFT_CONTROL, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), "SHIFT": (KeyboardInput.LEFT_SHIFT, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT), "ALT": (KeyboardInput.LEFT_ALT, carb.input.KEYBOARD_MODIFIER_FLAG_ALT), } async def emulate_key_combo(combo: str, human_delay_speed: int = 2): """Emulate Keyboard key combination. Parse string of keys separated by '+' sign and treat as a key combo to emulate. Examples: "CTRL+ENTER", "SHIFT+ALT+Y", "Z" """ mods = [] keys = [] modifiers = 0 key_map = KeyboardInput.__members__ # pybind11 way to get enum as dict (name -> value) for key in combo.upper().split("+"): if key in MODIFIERS_MAP: mods.append(MODIFIERS_MAP[key]) continue if key not in key_map: carb.log_error(f"Can't parse key: '{key}' in combo: '{combo}'") return keys.append(key_map[key]) # press modifier keys first for k in mods: modifiers = modifiers | k[1] # modifier is added for the press await emulate_keyboard(KeyboardEventType.KEY_PRESS, k[0], modifiers) await human_delay(human_delay_speed) # press non-modifier keys for k in keys: await emulate_keyboard(KeyboardEventType.KEY_PRESS, k, modifiers) await human_delay(human_delay_speed) # release non-modifier keys and modifier keys in reverse order for k in reversed(keys): await emulate_keyboard(KeyboardEventType.KEY_RELEASE, k, modifiers) await human_delay(human_delay_speed) for k in reversed(mods): modifiers = modifiers & ~k[1] # modifier is removed for the release await emulate_keyboard(KeyboardEventType.KEY_RELEASE, k[0], modifiers) await human_delay(human_delay_speed) async def emulate_char_press(chars: str, delay_every_n_symbols: int = 20, human_delay_speed: int = 2): """Emulate Keyboard char input. Type N chars immediately and do a delay, then continue.""" keyboard = omni.appwindow.get_default_app_window().get_keyboard() for i, char in enumerate(chars): _get_input_provider().buffer_keyboard_char_event(keyboard, char, 0) if (i + 1) % delay_every_n_symbols == 0: await human_delay(human_delay_speed) # Key is down when enter the scope and released when exit # Usage: # async with KeyDownScope(carb.input.KeyboardInput.LEFT_CONTROL): # await ui_test.emulate_mouse_drag_and_drop(Vec2(50, 50), Vec2(350, 350)) class KeyDownScope: def __init__( self, key: carb.input.KeyboardInput, modifier: carb.input.KeyboardInput = 0, human_delay_speed: int = 2 ): self._key = key self._modifier = modifier self._human_delay_speed = human_delay_speed async def __aenter__(self): await emulate_keyboard(carb.input.KeyboardEventType.KEY_PRESS, self._key, self._modifier) await human_delay(self._human_delay_speed) async def __aexit__(self, exc_type, exc, tb): await emulate_keyboard(carb.input.KeyboardEventType.KEY_RELEASE, self._key, self._modifier) if self._modifier: await emulate_keyboard(carb.input.KeyboardEventType.KEY_RELEASE, self._modifier) await human_delay(self._human_delay_speed)
8,918
Python
40.483721
120
0.697017
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/tests/test_ui_test.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import unittest import omni.kit.app from omni.kit.test import AsyncTestCase import omni.ui as ui import omni.kit.ui_test as ui_test import carb.input import omni.appwindow from carb.input import KeyboardInput, KeyboardEventType from contextlib import asynccontextmanager @asynccontextmanager async def capture_keyboard(): input = carb.input.acquire_input_interface() keyboard = omni.appwindow.get_default_app_window().get_keyboard() events = [] def on_input(e): events.append((e.input, e.type, e.modifiers)) sub = input.subscribe_to_keyboard_events(keyboard, on_input) try: yield events finally: input.unsubscribe_to_keyboard_events(keyboard, sub) @asynccontextmanager async def capture_mouse(): input = carb.input.acquire_input_interface() mouse = omni.appwindow.get_default_app_window().get_mouse() events = [] def on_input(e): events.append((e.input, e.type)) sub = input.subscribe_to_mouse_events(mouse, on_input) try: yield events finally: input.unsubscribe_to_mouse_events(mouse, sub) class TestUITest(AsyncTestCase): async def setUp(self): self._clicks = 0 self._window = ui.Window("Cool Window") with self._window.frame: # the frame can only have 1 widget under it with ui.HStack(): with ui.VStack(): ui.Label("Test2") with ui.VStack(width=150): with ui.HStack(height=30): ui.Label("Test1") ui.StringField() def on_click(*_): self._clicks += 1 ui.Button("TestButton", clicked_fn=on_click) await ui_test.wait_n_updates(2) async def tearDown(self): self._window = None async def test_find(self): # Click a button button = ui_test.find("Cool Window//Frame/**/Button[*]") self.assertEqual(button.realpath, "Cool Window//Frame/HStack[0]/VStack[1]/HStack[0]/Button[0]") await button.click() self.assertEqual(self._clicks, 1) # Move mouse away, click and then click button again, that should be +1 click: await ui_test.emulate_mouse_move(ui_test.Vec2(0, 0)) await ui_test.emulate_mouse_click() await ui_test.find("Cool Window//Frame/**/Button[*]").click() self.assertEqual(self._clicks, 2) async def test_nested_find(self): # Multiple nested finds h_stack = ui_test.find("Cool Window//Frame/HStack[0]") self.assertEqual(h_stack.realpath, "Cool Window//Frame/HStack[0]") await h_stack.find("**/Button[0]").click() self.assertEqual(self._clicks, 1) window = ui_test.find("Cool Window") h_stack = window.find("HStack[0]") self.assertEqual(h_stack.realpath, "Cool Window//Frame/HStack[0]") await h_stack.find("**/Button[0]").click() self.assertEqual(self._clicks, 2) async def test_find_all(self): labels = ui_test.find_all("Cool Window//Frame/**/Label[*]") self.assertSetEqual({s.widget.text for s in labels}, {"Test1", "Test2"}) h_stack = ui_test.find("Cool Window//Frame/HStack[0]") labels = h_stack.find_all("**/Label[*]") self.assertSetEqual({s.widget.text for s in labels}, {"Test1", "Test2"}) class TestInput(AsyncTestCase): async def test_emulate_keyboard(self): async with capture_keyboard() as events: await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.X, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL) self.assertListEqual( events, [ (KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), (KeyboardInput.X, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), (KeyboardInput.X, KeyboardEventType.KEY_RELEASE, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), (KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_RELEASE, 0), ], ) async def test_emulate_key_combo(self): async with capture_keyboard() as events: await ui_test.emulate_key_combo("SHIFT+ctrl+w") self.assertListEqual( events, [ (KeyboardInput.LEFT_SHIFT, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT), (KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), (KeyboardInput.W, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), (KeyboardInput.W, KeyboardEventType.KEY_RELEASE, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL), (KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_RELEASE, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT), (KeyboardInput.LEFT_SHIFT, KeyboardEventType.KEY_RELEASE, 0), ], ) events.clear() await ui_test.emulate_key_combo("Y") self.assertListEqual( events, [(KeyboardInput.Y, KeyboardEventType.KEY_PRESS, 0), (KeyboardInput.Y, KeyboardEventType.KEY_RELEASE, 0)], ) @unittest.skip("Subscribe to mouse in carbonite doesn't seem to work") async def test_emulate_mouse_scroll(self): async with capture_mouse() as events: await ui_test.emulate_mouse_scroll(ui_test.Vec2(5.5, 6.5)) print(events) self.assertListEqual( events, [] # TODO )
6,332
Python
37.615853
163
0.624131
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/tests/__init__.py
from .test_ui_test import * from .test_ui_test_doc_snippets import *
69
Python
22.333326
40
0.73913
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/tests/test_ui_test_doc_snippets.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 builtins import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.ui as ui import omni.kit.ui_test as ui_test class TestUITestDocSnippet(AsyncTestCase): async def test_doc_snippet(self): clicks = 0 def on_click(*_): nonlocal clicks clicks += 1 printed_text = "" def print(*args, **kwargs): nonlocal printed_text printed_text += str(args[0]) + "\n" return builtins.print(*args, **kwargs) # begin-doc-1 # Demo: import omni.kit.ui_test as ui_test import omni.ui as ui # Build some UI window = ui.Window("Nice Window") with window.frame: # the frame can only have 1 widget under it with ui.HStack(): ui.Label("Test1") with ui.VStack(width=150): ui.Label("Test2") ui.Button("TestButton", clicked_fn=on_click) # Let UI build await ui_test.wait_n_updates(2) # Find a button button = ui_test.find("Nice Window//Frame/**/Button[*]") # Real / Unique path: print(button.realpath) # Nice Window//Frame/HStack[0]/VStack[0]/Button[0] # button is a reference, actual omni.ui.Widget can be accessed: print(type(button.widget)) # <class 'omni.ui._ui.Button'> # Click on button await button.click() # Find can be nested same_button = ui_test.find("Nice Window").find("**/Button[*]") # Find multiple: labels = ui_test.find_all("Nice Window//Frame/**/Label[*]") print(labels[0].widget.text) # Test 1 print(labels[1].widget.text) # Test 2 # end-doc-1 # Verify snippet operations: self.assertEqual( printed_text, """Nice Window//Frame/HStack[0]/VStack[0]/Button[0] <class 'omni.ui._ui.Button'> Test1 Test2 """, ) self.assertEqual(button.widget, same_button.widget) self.assertEqual(clicks, 1) self.assertEqual(len(labels), 2)
2,565
Python
29.188235
82
0.604678
omniverse-code/kit/exts/omni.kit.ui_test/docs/index.rst
omni.kit.ui_test ########################### UI Testing Helper functions .. toctree:: :maxdepth: 1 CHANGELOG.md Usage Example: ================ .. literalinclude:: ../python/omni/kit/ui_test/tests/test_ui_test_doc_snippets.py :language: python :start-after: begin-doc-1 :end-before: end-doc-1 :dedent: 8 API: ================ .. automodule:: omni.kit.ui_test :platform: Windows-x86_64, Linux-x86_64, Linux-aarch64 :members: :undoc-members: :imported-members:
506
reStructuredText
13.911764
81
0.583004
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/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__ = ["CollaborationColumnsWidgetExtension"] import omni.ext from .delegates import * from omni.kit.widget.stage.stage_column_delegate_registry import StageColumnDelegateRegistry class CollaborationColumnsWidgetExtension(omni.ext.IExt): """The entry point for Stage Window""" def on_startup(self): # Register column delegates self._live_column_sub = StageColumnDelegateRegistry().register_column_delegate( "Live", LiveColumnDelegate ) self._reload_column_sub = StageColumnDelegateRegistry().register_column_delegate( "Reload", ReloadColumnDelegate ) self._participants_column_sub = StageColumnDelegateRegistry().register_column_delegate( "Participants", ParticipantsColumnDelegate ) def on_shutdown(self): self._live_column_sub = None self._reload_column_sub = None self._participants_column_sub = None
1,376
Python
36.216215
95
0.728924
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/__init__.py
""" * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ from .extension import *
459
Python
40.818178
76
0.795207
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/icons.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__ = ["Icons"] from .singleton import Singleton from pathlib import Path from typing import Union import omni.kit.app EXTENSION_FOLDER_PATH = Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) @Singleton class Icons: """A singleton that scans the icon folder and returns the icon depending on the type""" def __init__(self): # Read all the svg files in the directory self.__icons = {icon.stem: str(icon) for icon in EXTENSION_FOLDER_PATH.joinpath("icons").glob("*.svg")} def get(self, prim_type: str, default: Union[str, Path] = None) -> str: """Checks the icon cache and returns the icon if exists""" found = self.__icons.get(prim_type) if not found and default: found = self._icons.get(default) if found: return found return ""
1,317
Python
31.146341
111
0.694002
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/singleton.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
696
Python
33.849998
76
0.727011
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/models/reload_model.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__ = ["ReloadModel"] import omni.ui as ui from omni.kit.widget.live_session_management.utils import reload_outdated_layers class ReloadModel(ui.AbstractValueModel): def __init__(self, stage_item): super().__init__() self._stage_item = stage_item def destroy(self): self._stage_item = None def get_value_as_bool(self) -> bool: """Reimplemented get bool""" return self._stage_item.is_outdated def set_value(self, value: bool): """Reimplemented set bool""" prim = self._stage_item.prim if not prim: return prim_path = prim.GetPath() if prim_path: reload_outdated_layers(self._stage_item.payrefs, self._stage_item.usd_context)
1,190
Python
30.342104
90
0.679832
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/models/__init__.py
""" * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ from .live_model import * from .reload_model import *
488
Python
39.749997
76
0.790984
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/models/live_model.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__ = ["LiveModel"] import omni.ui as ui import omni.kit.usd.layers as layers import omni.kit.notification_manager as nm class LiveModel(ui.AbstractValueModel): def __init__(self, stage_item): super().__init__() self._stage_item = stage_item def destroy(self): self._stage_item = None def get_value_as_bool(self) -> bool: """Reimplemented get bool""" return self._stage_item.in_session def set_value(self, value: bool): """Reimplemented set bool""" live_syncing = layers.get_live_syncing(self._stage_item.usd_context) if self._stage_item.in_session: live_syncing.stop_live_session(prim_path=self._stage_item.path) elif self._stage_item.payrefs: if len(self._stage_item.payrefs) > 1: nm.post_notification( f"Cannot join default session for prim {self._stage_item.path} as it" " includes multiple references or payloads. Please join from Property" " Window instead." ) else: payref = self._stage_item.payrefs[0] default_session = live_syncing.find_live_session_by_name(payref, "Default") if not default_session: default_session = live_syncing.create_live_session("Default", payref) if default_session: live_syncing.join_live_session(default_session, self._stage_item.path)
1,936
Python
38.530611
91
0.635847
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/delegates/participants_column_delegate.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__ = ["ParticipantsColumnDelegate"] from omni.kit.widget.stage.abstract_stage_column_delegate import AbstractStageColumnDelegate, StageColumnItem from omni.kit.widget.stage import StageItem from pxr import UsdGeom from ..icons import Icons from typing import List import omni.ui as ui import omni.kit.widget.live_session_management as lsm class ParticipantsColumnDelegate(AbstractStageColumnDelegate): """The column delegate that represents the Live column""" def __init__(self): super().__init__() self.WIDGET_STYLE = { "TreeView.Header::participants": {"image_url": Icons().get("participants"), "color": 0xFF888888}, } self.__user_list = {} def destroy(self): for user_list in self.__user_list.values(): user_list.destroy() self.__user_list = {} @property def initial_width(self): """The width of the column""" return ui.Pixel(64) def build_header(self, **kwargs): """Build the header""" with ui.HStack(style=self.WIDGET_STYLE): ui.Spacer() with ui.VStack(width=0): ui.Spacer() ui.Image(width=22, height=14, name="participants", style_type_name_override="TreeView.Header") ui.Spacer() ui.Spacer() async def build_widget(self, item: StageColumnItem, **kwargs): """Build the participants widget""" stage_item = kwargs.get("stage_item", None) if not stage_item: return user_list = self.__user_list.pop(stage_item, None) if user_list: user_list.destroy() prim = stage_item.prim if not prim: return payrefs = stage_item.payrefs if not prim.IsA(UsdGeom.Camera) and not payrefs: return with ui.HStack(): ui.HStack(width=4) with ui.HStack(): ui.Spacer() if payrefs: user_list = lsm.LiveSessionUserList( stage_item.usd_context, payrefs[0], show_myself=False, maximum_users=2, prim_path=stage_item.path ) else: user_list = lsm.LiveSessionCameraFollowerList( stage_item.usd_context, stage_item.path, maximum_users=2, show_my_following_users=True ) self.__user_list[stage_item] = user_list ui.Spacer() ui.HStack(width=4) def on_stage_items_destroyed(self, items: List[StageItem]): if not items: return for item in items: user_list = self.__user_list.pop(item, None) if user_list: user_list.destroy() @property def order(self): return -105 @property def sortable(self): return False @property def minimum_width(self): return ui.Pixel(40)
3,460
Python
30.463636
110
0.584104
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/delegates/__init__.py
""" * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * NVIDIA CORPORATION and its licensors retain all intellectual property * and proprietary rights in and to this software, related documentation * and any modifications thereto. Any use, reproduction, disclosure or * distribution of this software and related documentation without an express * license agreement from NVIDIA CORPORATION is strictly prohibited. """ from .live_column_delegate import * from .reload_column_delegate import * from .participants_column_delegate import *
552
Python
41.538458
76
0.797101
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/delegates/reload_column_delegate.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__ = ["ReloadColumnDelegate"] from omni.kit.widget.stage.abstract_stage_column_delegate import AbstractStageColumnDelegate, StageColumnItem from omni.kit.widget.stage import StageItem from typing import List from ..models.reload_model import ReloadModel from ..icons import Icons from functools import partial from omni.ui import color as cl from enum import Enum import weakref import omni.ui as ui import omni.kit.app import omni.kit.usd.layers as layers import carb class ReloadColumnSortPolicy(Enum): DEFAULT = 0 OUTDATE_TO_LATEST = 1 LATEST_TO_OUTDATE = 2 class ReloadColumnDelegate(AbstractStageColumnDelegate): """The column delegate that represents the Auto Reload column""" def __init__(self): super().__init__() self.__reload_layout = None self.__stage_item_models = {} ITEM_DARK = 0x7723211F ICON_DARK = 0x338A8777 RELOAD = cl("#eb9d00") RELOAD_H = cl("#ffaa00") AUTO_RELOAD = cl("#34C7FF") AUTO_RELOAD_H = cl("#82dcff") self.WIDGET_STYLE = { "Button.Image::reload": {"image_url": Icons().get("reload"), "color": ICON_DARK}, "Button.Image::reload:checked": {"color": RELOAD_H}, "Button.Image::reload:disabled": {"color": 0x608A8777}, "Button.Image::reload:selected": {"color": ITEM_DARK}, "Button.Image::reload:checked:hovered": {"color": 0xFFFFFFFF}, "Button.Image::auto_reload": {"image_url": Icons().get("reload"), "color": AUTO_RELOAD}, "Button.Image::auto_reload:checked": {"color": AUTO_RELOAD}, "Button.Image::auto_reload:disabled": {"color": AUTO_RELOAD}, "Button.Image::auto_reload:checked:hovered": {"color": AUTO_RELOAD_H}, "Button::reload": {"background_color": 0x0, "margin": 0, "margin_width": 1}, "Button::reload:checked": {"background_color": 0x0}, "Button::reload:hovered": {"background_color": 0x0, "color": 0xFFFFFFFF}, "Button::reload:pressed": {"background_color": 0x0}, "Button::auto_reload": {"background_color": 0x0, "margin": 0, "margin_width": 1}, "Button::auto_reload:checked": {"background_color": 0x0}, "Button::auto_reload:hovered": {"background_color": 0x0, "color": 0xFFFFFFFF}, "Button::auto_reload:pressed": {"background_color": 0x0}, "TreeView.Item.Outdated": {"color": RELOAD}, "TreeView.Item.Outdated:hovered": {"color": RELOAD_H}, "TreeView.Item.Outdated:selected": {"color": RELOAD_H}, # Top of the column section (that has sorting options) "TreeView.Header::reload_header": {"image_url": Icons().get("reload_dark")}, } self.__stage_model = None self.__items_sort_policy = ReloadColumnSortPolicy.DEFAULT def destroy(self): if self.__reload_layout: self.__reload_layout.set_mouse_pressed_fn(None) self.__reload_layout = None for model in self.__stage_item_models.values(): model.destroy() self.__stage_item_models = {} self.__stage_model = None @property def initial_width(self): """The width of the column""" return ui.Pixel(24) @property def minimum_width(self): return ui.Pixel(24) def __on_policy_changed(self): stage_model = self.__stage_model if not stage_model: return if self.__items_sort_policy == ReloadColumnSortPolicy.OUTDATE_TO_LATEST: stage_model.set_items_sort_key_func( lambda item: item.is_outdated if item.payrefs else len(item.payrefs) == 0 ) elif self.__items_sort_policy == ReloadColumnSortPolicy.LATEST_TO_OUTDATE: stage_model.set_items_sort_key_func( lambda item: item.is_outdated if item.payrefs else len(item.payrefs) == 0, reverse=True ) else: stage_model.set_items_sort_key_func(None) def __on_reload_clicked(self, weakref_stage_model, x, y, b, m): stage_model = weakref_stage_model() if not stage_model or not stage_model.stage: return if b == 1: usd_context = omni.usd.get_context_from_stage(stage_model.stage) if not usd_context: return layers_state = layers.get_layers_state(usd_context) from omni.kit.widget.live_session_management.utils import reload_outdated_layers ref_ids = layers_state.get_outdated_non_sublayer_identifiers() reload_outdated_layers(ref_ids, usd_context) elif b == 0: if self.__items_sort_policy == ReloadColumnSortPolicy.OUTDATE_TO_LATEST: self.__items_sort_policy = ReloadColumnSortPolicy.LATEST_TO_OUTDATE elif self.__items_sort_policy == ReloadColumnSortPolicy.LATEST_TO_OUTDATE: self.__items_sort_policy = ReloadColumnSortPolicy.DEFAULT else: self.__items_sort_policy = ReloadColumnSortPolicy.OUTDATE_TO_LATEST self.__on_policy_changed() def build_header(self, **kwargs): """Build the header""" stage_model = kwargs.get("stage_model", None) self.__stage_model = stage_model if stage_model: with ui.ZStack(style=self.WIDGET_STYLE): tooltip = "RMB: Reload All References/Payloads" ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header", tooltip=tooltip) self.__reload_layout = ui.HStack() with self.__reload_layout: ui.Spacer() with ui.VStack(width=0): ui.Spacer() ui.Image(width=22, height=14, name="reload_header", style_type_name_override="TreeView.Header") ui.Spacer() ui.Spacer() weakref_stage_model = weakref.ref(stage_model) self.__reload_layout.set_mouse_pressed_fn( partial(self.__on_reload_clicked, weakref_stage_model) ) else: with ui.HStack(style=self.WIDGET_STYLE): ui.Spacer() with ui.VStack(width=0): ui.Spacer() ui.Image(width=22, height=14, name="reload_header", style_type_name_override="TreeView.Header") ui.Spacer() ui.Spacer() async def build_widget(self, item: StageColumnItem, **kwargs): """Build the reload widget""" stage_item = kwargs.get("stage_item", None) reloadable = (stage_item.payloads or stage_item.references) if not stage_item or not stage_item.prim or not reloadable: return g_auto_reload = carb.settings.get_settings().get_as_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS) with ui.ZStack(height=20, style=self.WIDGET_STYLE): # Min size ui.Spacer(width=22) reload_model = self.__stage_item_models.get(stage_item, None) if not reload_model: reload_model = ReloadModel(stage_item) self.__stage_item_models[stage_item] = reload_model button = ui.ToolButton(reload_model) stub = "payloads" if stage_item.payloads else "references" if not reload_model.get_value_as_bool(): tooltip = "All {} up to date".format(stub) else: tooltip = "Reload {} on prim".format(stub) if stage_item.auto_reload: tooltip = "Auto Reload All Enabled" if g_auto_reload else "Auto Reload Enabled" button.enabled = False if stage_item.is_outdated and g_auto_reload and stage_item.in_session: tooltip = "Auto Reload Blocked by Live Session" button.tooltip = tooltip button.name = "auto_reload" if stage_item.auto_reload else "reload" def on_stage_items_destroyed(self, items: List[StageItem]): if not items: return for item in items: live_model = self.__stage_item_models.pop(item, None) if live_model: live_model.destroy() @property def order(self): return -104 @property def sortable(self): return True
8,866
Python
38.941441
119
0.596661
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/delegates/live_column_delegate.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__ = ["LiveColumnDelegate"] from omni.kit.widget.stage.abstract_stage_column_delegate import AbstractStageColumnDelegate, StageColumnItem from omni.kit.widget.stage import StageItem, StageModel from typing import List from ..models import LiveModel from ..icons import Icons from enum import Enum import omni.ui as ui class LiveColumnSortPolicy(Enum): DEFAULT = 0 LIVE_TO_OFFLINE = 1 OFFLINE_TO_LIVE = 2 class LiveColumnDelegate(AbstractStageColumnDelegate): """The column delegate that represents the Live column""" def __init__(self): super().__init__() self.__stage_item_models = {} from omni.ui import color as cl ITEM_DARK = 0x7723211F ICON_DARK = 0x338A8777 LIVE_GREEN = cl("#76b800") LIVE_SEL = cl("#90e203") self.WIDGET_STYLE = { "Button.Image::live": {"image_url": Icons().get("lightning"), "color": ICON_DARK}, "Button.Image::live:checked": {"color": LIVE_GREEN}, "Button.Image::live:checked:hovered": {"color": LIVE_SEL}, "Button.Image::live:disabled": {"color": 0x608A8777}, "Button.Image::live:selected": {"color": ITEM_DARK}, "Button::live": {"background_color": 0x0, "margin": 0, "margin_width": 1}, "Button::live:checked": {"background_color": 0x0}, "Button::live:hovered": {"background_color": 0x0}, "Button::live:pressed": {"background_color": 0x0}, "TreeView.Item.Live": {"color": LIVE_GREEN}, "TreeView.Item.Live:hovered": {"color": LIVE_SEL}, "TreeView.Item.Live:selected": {"color": LIVE_SEL}, # Top of the column section (that has sorting options) "TreeView.Header::live_header": {"image_url": Icons().get("lightning"), "color": 0xFF888888}, } self.__stage_model: StageModel = None self.__items_sort_policy = LiveColumnSortPolicy.DEFAULT self.__live_header_layout = None def destroy(self): for model in self.__stage_item_models.values(): model.destroy() self.__stage_item_models = {} self.__stage_model = None if self.__live_header_layout: self.__live_header_layout.set_mouse_pressed_fn(None) self.__live_header_layout = None @property def initial_width(self): """The width of the column""" return ui.Pixel(24) @property def minimum_width(self): return ui.Pixel(24) def __on_policy_changed(self): stage_model = self.__stage_model if not stage_model: return if self.__items_sort_policy == LiveColumnSortPolicy.LIVE_TO_OFFLINE: stage_model.set_items_sort_key_func( lambda item: item.in_session if item.payrefs else len(item.payrefs) == 0 ) elif self.__items_sort_policy == LiveColumnSortPolicy.OFFLINE_TO_LIVE: stage_model.set_items_sort_key_func( lambda item: item.in_session if item.payrefs else len(item.payrefs) == 0, reverse=True ) else: stage_model.set_items_sort_key_func(None) def __on_header_clicked(self, x, y, b, m): if b != 0 or not self.__stage_model: return if self.__items_sort_policy == LiveColumnSortPolicy.LIVE_TO_OFFLINE: self.__items_sort_policy = LiveColumnSortPolicy.OFFLINE_TO_LIVE elif self.__items_sort_policy == LiveColumnSortPolicy.OFFLINE_TO_LIVE: self.__items_sort_policy = LiveColumnSortPolicy.DEFAULT else: self.__items_sort_policy = LiveColumnSortPolicy.LIVE_TO_OFFLINE self.__on_policy_changed() def build_header(self, **kwargs): """Build the header""" self.__stage_model = kwargs.get("stage_model", None) with ui.ZStack(style=self.WIDGET_STYLE): tooltip = "LMB:Sort Live" ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header", tooltip=tooltip) self.__live_header_layout = ui.HStack() with self.__live_header_layout: ui.Spacer() with ui.VStack(width=0): ui.Spacer() ui.Image(width=22, height=14, name="live_header", style_type_name_override="TreeView.Header") ui.Spacer() ui.Spacer() self.__live_header_layout.set_tooltip(tooltip) self.__live_header_layout.set_mouse_pressed_fn(self.__on_header_clicked) async def build_widget(self, item: StageColumnItem, **kwargs): """Build the live widget""" stage_item = kwargs.get("stage_item", None) reloadable = (stage_item.payloads or stage_item.references) if not stage_item or not stage_item.prim or not reloadable: return with ui.ZStack(height=20, style=self.WIDGET_STYLE): # Min size ui.Spacer(width=22) live_model = self.__stage_item_models.get(stage_item, None) if not live_model: live_model = LiveModel(stage_item) self.__stage_item_models[stage_item] = live_model tooltip = "Live session status" ui.ToolButton(live_model, enabled=True, name="live", tooltip=tooltip) def on_stage_items_destroyed(self, items: List[StageItem]): if not items: return for item in items: live_model = self.__stage_item_models.pop(item, None) if live_model: live_model.destroy() @property def order(self): return -103 @property def sortable(self): return True
6,147
Python
36.260606
113
0.605661
omniverse-code/kit/exts/omni.kit.audio.test.usd/PACKAGE-LICENSES/omni.kit.audio.test.usd-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.audio.test.usd/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.1" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "USD Audio Tests" description="Tests that had to be moved out of omni.usd due to dependency issues" # URL of the extension source repository. repository = "" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). #preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. #icon = "data/icon.png" # Keywords for the extension keywords = ["kit", "usd", "tests", "audio", "sound"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ #changelog="docs/CHANGELOG.md" # Path (relative to the root) or content of readme markdown file for UI. #readme = "docs/README.md" [dependencies] "omni.usd" = {} "carb.audio" = {} [[python.module]] name = "omni.kit.audio.test.usd" [[test]] args = [ "--/app/file/ignoreUnsavedOnExit=true", "--/app/asyncRendering=false", # OM-20773: Use legacy bitmask to control audio-on state "--/persistent/app/viewport/displayOptions=4096", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.ui", "omni.kit.property.usd", "omni.kit.property.audio", "omni.kit.test_helpers_gfx", "omni.hydra.rtx", "omni.kit.window.viewport", "omni.kit.test_suite.helpers" ] stdoutFailPatterns.exclude = [ "*prim '*' is of type 'Sound', not 'Listener'*", "*sound '*' was in the incorrect position in m_sounds*", "*failed to open the new device {result = 0x00000005}*", "*failed to open the new device {result = 0x00000002}*", "*failed to create a new output streamer*", "*the asset for sound * failed to load*" ] # RTX regression OM-51983 timeout = 600
2,065
TOML
28.098591
93
0.689588
omniverse-code/kit/exts/omni.kit.audio.test.usd/omni/kit/audio/test/usd/__init__.py
pass
6
Python
1.333333
4
0.666667
omniverse-code/kit/exts/omni.kit.audio.test.usd/omni/kit/audio/test/usd/tests/test_audio.py
import asyncio import time from collections import defaultdict import pathlib from PIL import Image from PIL import ImageEnhance import random import omni.kit.test_helpers_gfx.compare_utils import carb import carb.tokens import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd.audio import os from omni.ui.tests.test_base import OmniUiTest from omni.kit.test_suite.helpers import wait_stage_loading OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) def wait_for_asset(test, audio, prim): i = 0 while audio.get_sound_asset_status(prim) == omni.usd.audio.AssetLoadStatus.IN_PROGRESS: time.sleep(0.001) if i > 5000: raise Exception("asset load timed out") i += 1 test.assertEqual(audio.get_sound_asset_status(prim), omni.usd.audio.AssetLoadStatus.DONE) async def wait_for_prim_change(test, context, audio, prim): await context.next_frame_async() # the asset may reload, so we need to wait for it wait_for_asset(test, audio, prim) class TestStageAudioMinimal(omni.kit.test.AsyncTestCase): async def setUp(self): self._context = omni.usd.get_context() self.assertIsNotNone(self._context) self._context.new_stage() self._stage = self._context.get_stage() self.assertIsNotNone(self._stage) self._audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(self._audio) async def test_hydra_plugin(self): # check that the hydra plugin still works self.assertTrue(omni.usd.audio.test_hydra_plugin(), "the hydra audio plugin failed to load") async def test_device(self): self._audio.set_device("default") time.sleep(2.0) self._audio.set_device("apple") time.sleep(2.0) self._audio.set_device("Speakers") time.sleep(2.0) async def test_set_doppler_default(self): self._audio.set_doppler_default(omni.usd.audio.FeatureDefault.FORCE_OFF) self.assertEqual(self._audio.get_doppler_default(), omni.usd.audio.FeatureDefault.FORCE_OFF) self._audio.set_doppler_default() self.assertEqual(self._audio.get_doppler_default(), omni.usd.audio.FeatureDefault.OFF) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_set_distance_delay_default(self): self._audio.set_distance_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF) self.assertEqual(self._audio.get_distance_delay_default(), omni.usd.audio.FeatureDefault.FORCE_OFF) self._audio.set_distance_delay_default() self.assertEqual(self._audio.get_distance_delay_default(), omni.usd.audio.FeatureDefault.OFF) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_set_interaural_delay_default(self): self._audio.set_interaural_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF) self.assertEqual(self._audio.get_interaural_delay_default(), omni.usd.audio.FeatureDefault.FORCE_OFF) self._audio.set_interaural_delay_default() self.assertEqual(self._audio.get_interaural_delay_default(), omni.usd.audio.FeatureDefault.OFF) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_set_concurrent_voices(self): self._audio.set_concurrent_voices(32) self.assertEqual(self._audio.get_concurrent_voices(), 32) self._audio.set_concurrent_voices() self.assertEqual(self._audio.get_concurrent_voices(), 64) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_speed_of_sound(self): self._audio.set_speed_of_sound(120.0) self.assertEqual(self._audio.get_speed_of_sound(), 120.0) self._audio.set_speed_of_sound() self.assertLess(abs(self._audio.get_speed_of_sound() - 340.0), 0.1) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_doppler_scale(self): self._audio.set_doppler_scale(4.0) self.assertEqual(self._audio.get_doppler_scale(), 4.0) self._audio.set_doppler_scale() self.assertEqual(self._audio.get_doppler_scale(), 1.0) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_doppler_limit(self): self._audio.set_doppler_limit(4.0) self.assertEqual(self._audio.get_doppler_limit(), 4.0) self._audio.set_doppler_limit() self.assertEqual(self._audio.get_doppler_limit(), 2.0) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_spatial_time_scale(self): self._audio.set_spatial_time_scale(4.0) self.assertEqual(self._audio.get_spatial_time_scale(), 4.0) self._audio.set_spatial_time_scale() self.assertEqual(self._audio.get_spatial_time_scale(), 1.0) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_nonspatial_time_scale(self): self._audio.set_nonspatial_time_scale(4.0) self.assertEqual(self._audio.get_nonspatial_time_scale(), 4.0) self._audio.set_nonspatial_time_scale() self.assertEqual(self._audio.get_nonspatial_time_scale(), 1.0) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_get_metadata_change_stream(self): callbacks = 0 event_type = None def event_callback(event): nonlocal event_type nonlocal callbacks event_type = event.type callbacks += 1 def wait_for_callback(initial): nonlocal callbacks i = 0 while callbacks == initial: time.sleep(0.001) if i > 1000: raise Exception("asset load timed out") i += 1 self._events = self._audio.get_metadata_change_stream() self.assertIsNotNone(self._events) self._stage_event_sub = self._events.create_subscription_to_pop( event_callback, name="stage audio test callback" ) initial = callbacks self._audio.set_doppler_default(omni.usd.audio.FeatureDefault.FORCE_OFF) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) # try the same thing twice to verify that the value needs to change to # trigger a callback initial = callbacks self._audio.set_doppler_default(omni.usd.audio.FeatureDefault.FORCE_OFF) try: wait_for_callback(initial) self.assertTrue(False) except Exception: pass self.assertEqual(callbacks, initial) initial = callbacks self._audio.set_distance_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) initial = callbacks self._audio.set_interaural_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) initial = callbacks self._audio.set_concurrent_voices(32) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) initial = callbacks self._audio.set_speed_of_sound(120.0) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) initial = callbacks self._audio.set_doppler_scale(4.0) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) initial = callbacks self._audio.set_doppler_limit(4.0) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) initial = callbacks self._audio.set_spatial_time_scale(4.0) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) initial = callbacks self._audio.set_nonspatial_time_scale(4.0) wait_for_callback(initial) self.assertEqual(callbacks, initial + 1) self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE)) class TestStageAudio(omni.kit.test.AsyncTestCase): async def setUp(self): self._context = omni.usd.get_context() self.assertIsNotNone(self._context) self._context.new_stage() self._stage = self._context.get_stage() self.assertIsNotNone(self._stage) self._audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(self._audio) extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}") self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() self._golden_path = self._test_path.joinpath("golden") self._prim_no_filename_path = "/sound_no_filename" self._prim_no_filename = self._stage.DefinePrim(self._prim_no_filename_path, "Sound") self.assertIsNotNone(self._prim_no_filename) self._prim_bad_asset_path = "/sound_bad_asset" self._prim_bad_asset = self._stage.DefinePrim(self._prim_bad_asset_path, "Sound") self.assertIsNotNone(self._prim_bad_asset) self._prim_bad_asset.GetAttribute("filePath").Set("/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/x/y/z") self._test_sound_1ch_path = self._test_path.joinpath("short-1ch.oga").absolute() self._prim_1ch_path = "/sound_1ch" self._prim_1ch = self._stage.DefinePrim(self._prim_1ch_path, "Sound") self.assertIsNotNone(self._prim_1ch) self._prim_1ch.GetAttribute("filePath").Set(str(self._test_sound_1ch_path)) self._test_sound_2ch_path = self._test_path.joinpath("short-2ch.oga").absolute() self._prim_2ch_path = "/sound_2ch" self._prim_2ch = self._stage.DefinePrim(self._prim_2ch_path, "Sound") self.assertIsNotNone(self._prim_2ch) self._prim_2ch.GetAttribute("filePath").Set(str(self._test_sound_2ch_path)) self._test_sound_long_path = self._test_path.joinpath("long.oga").absolute() self._prim_long_path = "/sound_long" self._prim_long = self._stage.DefinePrim(self._prim_long_path, "Sound") self.assertIsNotNone(self._prim_long) self._prim_long.GetAttribute("filePath").Set(str(self._test_sound_long_path)) wait_for_asset(self, self._audio, self._prim_1ch) wait_for_asset(self, self._audio, self._prim_2ch) wait_for_asset(self, self._audio, self._prim_long) try: os.mkdir(OUTPUTS_DIR) except FileExistsError: pass async def tearDown(self): self._stage.RemovePrim(self._prim_no_filename_path) self._stage.RemovePrim(self._prim_bad_asset_path) self._stage.RemovePrim(self._prim_1ch_path) self._stage.RemovePrim(self._prim_2ch_path) self._stage.RemovePrim(self._prim_long_path) async def test_get_sound_count(self): # sounds are only counted if they have a valid asset self.assertEqual(self._audio.get_sound_count(), 3); self._audio.draw_waveform(self._prim_no_filename, 1, 1) self._audio.draw_waveform(self._prim_bad_asset, 1, 1) self.assertEqual(self._audio.get_sound_count(), 5); async def test_is_sound_playing(self): self.assertFalse(self._audio.is_sound_playing(self._prim_long)) # the sound asset for this prim is silent, so the test shouldn't bother testers # play the sound self._audio.play_sound(self._prim_long) self.assertTrue(self._audio.is_sound_playing(self._prim_long)) # stop the sound self._audio.stop_sound(self._prim_long) self.assertFalse(self._audio.is_sound_playing(self._prim_long)) # do it again, but use stop_all_sounds() instead self._audio.play_sound(self._prim_long) self.assertTrue(self._audio.is_sound_playing(self._prim_long)) self._audio.stop_all_sounds() self.assertFalse(self._audio.is_sound_playing(self._prim_long)) # do it again but with spawn_voice() voice = self._audio.spawn_voice(self._prim_long) # the voice is not managed by IStageAudio self.assertFalse(self._audio.is_sound_playing(self._prim_long)) self.assertTrue(voice.is_playing()) voice.stop() self.assertFalse(voice.is_playing()) async def test_subscribe_to_asset_load(self): loaded = False def load_callback(): self.assertEqual(self._audio.get_sound_asset_status(self._prim_long), omni.usd.audio.AssetLoadStatus.DONE) nonlocal loaded loaded = True # try it with something that's already loaded to ensure a callback will occur in this case self.assertTrue(self._audio.subscribe_to_asset_load(self._prim_long, load_callback)) while not loaded: time.sleep(0.001) if i > 5000: raise Exception("asset load timed out") i += 1 # switch the file path and try again, so a load will actually be needed self._prim_2ch.GetAttribute("filePath").Set(str(self._test_sound_2ch_path)) loaded = False self.assertTrue(self._audio.subscribe_to_asset_load(self._prim_long, load_callback)) while not loaded: time.sleep(0.001) if i > 5000: raise Exception("asset load timed out") i += 1 async def test_draw_waveform(self): # toggle in case you want to regenerate waveforms GENERATE_GOLDEN_IMAGES = False if GENERATE_GOLDEN_IMAGES: print("!!!!! Golden images are being regenerated to '" + str(pathlib.Path(OUTPUTS_DIR)) + "'.") print("!!!!! Once regenerated, these files should be copied to '" + str(self._golden_path) + "'.") print("!!!!! Note: the `GENERATE_GOLDEN_IMAGES` variable being set to 'True' above should never be committed.") W = 256 H = 256 BASE_NAME = "test_stage_audio.draw_waveform" TEST_NAMES = [ BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.png", BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.BACKGROUNDCOLOR.png", BASE_NAME + ".2ch.USE_LINES.SPLIT_CHANNELS.png", BASE_NAME + ".2ch.USE_LINES.SPLIT_CHANNELS.PARTIAL_COLOR.png", BASE_NAME + ".2ch.USE_LINES.SPLIT_CHANNELS.COLOR.png", BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.MEDIA_OFFSET_START.png", BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.MEDIA_OFFSET_START.MEDIA_OFFSET_END.png", BASE_NAME + ".1ch.png", BASE_NAME + ".1ch.ALPHA_BLEND.png", BASE_NAME + ".2ch.ch_2.png", BASE_NAME + ".2ch.ALPHA_BLEND.MULTI_CHANNEL.png", BASE_NAME + ".2ch.NOISE_COLOR.2bit.png", ] raw = self._audio.draw_waveform(self._prim_no_filename, W, H) self.assertEqual(len(raw), 0) raw = self._audio.draw_waveform(self._prim_bad_asset, W, H) self.assertEqual(len(raw), 0) # render the mono waveform raw = self._audio.draw_waveform(self._prim_1ch, W, H) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[0]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[0]), self._golden_path.joinpath(TEST_NAMES[0]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[0] + ".diff.png")), 0.1) # render it with a custom background color raw = self._audio.draw_waveform(self._prim_1ch, W, H, background = [1.0, 1.0, 1.0, 1.0]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[1]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[1]), self._golden_path.joinpath(TEST_NAMES[1]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[1] + ".diff.png")), 0.1) # render the stereo waveform raw = self._audio.draw_waveform(self._prim_2ch, W, H) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[2]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[2]), self._golden_path.joinpath(TEST_NAMES[2]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[2] + ".diff.png")), 0.1) # add custom channel colors, but only set it for 4 channel to verify that the default still works raw = self._audio.draw_waveform(self._prim_2ch, W, H, colors = [[1.0, 0, 1.0, 1.0]]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[3]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[3]), self._golden_path.joinpath(TEST_NAMES[3]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[3] + ".diff.png")), 0.1) # try 2 custom channel colors now raw = self._audio.draw_waveform(self._prim_2ch, W, H, colors = [[1.0, 0, 0, 1.0], [0, 0, 1.0, 1.0]]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[4]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[4]), self._golden_path.joinpath(TEST_NAMES[4]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[4] + ".diff.png")), 0.1) # this sound asset is 0.693 seconds, so 0.2 is substantial self._prim_1ch.GetAttribute("mediaOffsetStart").Set(0.2); await wait_for_prim_change(self, self._context, self._audio, self._prim_1ch) raw = self._audio.draw_waveform(self._prim_1ch, W, H) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[5]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[5]), self._golden_path.joinpath(TEST_NAMES[5]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[5] + ".diff.png")), 0.1) self._prim_1ch.GetAttribute("mediaOffsetEnd").Set(0.4); await wait_for_prim_change(self, self._context, self._audio, self._prim_1ch) raw = self._audio.draw_waveform(self._prim_1ch, W, H) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[6]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[6]), self._golden_path.joinpath(TEST_NAMES[6]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[6] + ".diff.png")), 0.1) # reset prim parameters self._prim_1ch.GetAttribute("mediaOffsetStart").Set(0.0); self._prim_1ch.GetAttribute("mediaOffsetEnd").Set(0.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_1ch) # test it with no flags raw = self._audio.draw_waveform(self._prim_1ch, W, H, flags = 0) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[7]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[7]), self._golden_path.joinpath(TEST_NAMES[7]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[7] + ".diff.png")), 0.1) # test it with alpha blending raw = self._audio.draw_waveform(self._prim_1ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_ALPHA_BLEND, colors = [[1.0, 1.0, 1.0, 0.2]]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[8]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[8]), self._golden_path.joinpath(TEST_NAMES[8]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[8] + ".diff.png")), 0.1) # test choosing the second channel in a multi-channel image raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = 0, channel = 1) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[9]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[9]), self._golden_path.joinpath(TEST_NAMES[9]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[9] + ".diff.png")), 0.1) # test choosing the second channel in a multi-channel image raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_MULTI_CHANNEL | carb.audio.AUDIO_IMAGE_FLAG_ALPHA_BLEND, colors = [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]]) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[10]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[10]), self._golden_path.joinpath(TEST_NAMES[10]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[10] + ".diff.png")), 0.1) # the colors are going to be random, so turn all the pixels to white before comparing raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_NOISE_COLOR) self.assertEqual(len(raw), W * H * 4) with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img: # increase contrast by a factor of 256.0 ImageEnhance.Contrast(img.convert("RGB")).enhance(256.0).convert("1").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[11]))) if not GENERATE_GOLDEN_IMAGES: self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare( pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[11]), self._golden_path.joinpath(TEST_NAMES[11]), pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[11] + ".diff.png")), 2.0) # this won't crash or fail, but which flag is chosen is undefined raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_MULTI_CHANNEL | carb.audio.AUDIO_IMAGE_FLAG_SPLIT_CHANNELS) self.assertEqual(len(raw), W * H * 4) async def test_sound_length(self): FUZZ = 0.00001 ASSET_LENGTH = 120.0 self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # start time shouldn't change anything self._prim_long.GetAttribute("startTime").Set(12.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # end time that exceeds the asset length shouldn't change anything self._prim_long.GetAttribute("endTime").Set(ASSET_LENGTH + 20.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # end time 6 seconds after start time self._prim_long.GetAttribute("endTime").Set(18.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 6.0), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 6.0), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # trim the audio track itself start_trim = 30.0 trimmed_length = ASSET_LENGTH - start_trim self._prim_long.GetAttribute("mediaOffsetStart").Set(start_trim); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 6.0), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 6.0), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # excessive end offset has no effect self._prim_long.GetAttribute("mediaOffsetEnd").Set(ASSET_LENGTH + 1.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 6.0), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 6.0), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); end_trim = 32.0 trimmed_length = end_trim - start_trim # use a real trim now self._prim_long.GetAttribute("mediaOffsetEnd").Set(end_trim); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # speed it up by a factor of 2 self._prim_long.GetAttribute("timeScale").Set(2.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - trimmed_length / 2), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - trimmed_length / 2), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length / 2), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # try adding a loop count to double the time now self._prim_long.GetAttribute("loopCount").Set(1); self._prim_long.GetAttribute("timeScale").Set(1.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 2 * trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 2 * trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); # try looping infinitely and remove end time self._prim_long.GetAttribute("loopCount").Set(-1); self._prim_long.GetAttribute("endTime").Set(-1.0); await wait_for_prim_change(self, self._context, self._audio, self._prim_long) # check that it's some enormous number self.assertGreater(self._audio.get_sound_length(self._prim_long), 2**24); self.assertGreater(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH), 2**24); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ); self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ); class TestCaptureStreamer(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}") self._usd_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() try: os.mkdir(OUTPUTS_DIR) except FileExistsError: pass async def test_capture_streamer(self): # ****** test setup ****** audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(audio) usd_context = omni.usd.get_context() self.assertIsNotNone(usd_context) # load a test stage that has some audio prims in it. test_file_path = self._usd_path.joinpath("audio_test.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() # ****** create and setup the streamers ****** # create a streamer to capture the audio from the stage. streamer = audio.create_capture_streamer() self.assertNotEqual(streamer, audio.INVALID_STREAMER_ID) streamer2 = audio.create_capture_streamer() self.assertNotEqual(streamer2, audio.INVALID_STREAMER_ID) self.assertNotEqual(streamer, streamer2) streamer3 = audio.create_capture_streamer() self.assertNotEqual(streamer3, audio.INVALID_STREAMER_ID) self.assertNotEqual(streamer, streamer3) serial = random.randrange(2**32) def gen_name(name): return str(OUTPUTS_DIR.joinpath(str(serial) + "-" + name)) audio.set_capture_filename(streamer, gen_name("streamer1.wav")) audio.set_capture_filename(streamer2, gen_name("streamer2.wav")) # intentionally don't set the filename for streamer3. # ****** test some captures ****** # perform a capture on a single streamer with an overridden filename. success = audio.start_capture(streamer, gen_name("streamer3.wav")) self.assertTrue(success) await asyncio.sleep(0.5) success = audio.stop_capture(streamer) self.assertTrue(success) self.assertTrue(audio.wait_for_capture(streamer, 10000)) self.assertTrue(os.path.exists(gen_name("streamer3.wav"))) self.assertTrue(os.path.isfile(gen_name("streamer3.wav"))) self.assertFalse(os.path.exists(gen_name("streamer1.wav"))) self.assertFalse(os.path.exists(gen_name("streamer2.wav"))) streamer3_mtime = os.path.getmtime(gen_name("streamer3.wav")) await asyncio.sleep(0.5) self.assertEqual(streamer3_mtime, os.path.getmtime(gen_name("streamer3.wav"))) # perform a capture on multiple streamers simultaneously. success = audio.start_captures([streamer, streamer2]) self.assertTrue(success) await asyncio.sleep(0.5) success = audio.stop_captures([streamer2, streamer]) self.assertTrue(success) self.assertTrue(audio.wait_for_capture(streamer, 10000)) self.assertTrue(audio.wait_for_capture(streamer2, 10000)) self.assertTrue(os.path.exists(gen_name("streamer1.wav"))) self.assertTrue(os.path.exists(gen_name("streamer2.wav"))) self.assertTrue(os.path.isfile(gen_name("streamer1.wav"))) self.assertTrue(os.path.isfile(gen_name("streamer2.wav"))) # streamer3 shouldn't have been modified self.assertEqual(streamer3_mtime, os.path.getmtime(gen_name("streamer3.wav"))) streamer1_mtime = os.path.getmtime(gen_name("streamer1.wav")) streamer2_mtime = os.path.getmtime(gen_name("streamer2.wav")) # perform a capture on multiple streamers simultaneously where one has not had a filename set. audio.set_capture_filename(streamer, gen_name("streamer4.wav")) success = audio.start_captures([streamer, streamer3]) self.assertTrue(success) await asyncio.sleep(0.5) success = audio.stop_captures([streamer3, streamer]) self.assertTrue(audio.wait_for_capture(streamer3, 10000)) self.assertTrue(audio.wait_for_capture(streamer, 10000)) self.assertTrue(os.path.exists(gen_name("streamer4.wav"))) self.assertEqual(streamer1_mtime, os.path.getmtime(gen_name("streamer1.wav"))) self.assertEqual(streamer2_mtime, os.path.getmtime(gen_name("streamer2.wav"))) self.assertTrue(os.path.isfile(gen_name("streamer4.wav"))) self.assertEqual(streamer3_mtime, os.path.getmtime(gen_name("streamer3.wav"))) # start a capture while another streamer is already running. audio.set_capture_filename(streamer, gen_name("streamer5.wav")) audio.set_capture_filename(streamer2, gen_name("streamer6.wav")) success = audio.start_capture(streamer, None) self.assertTrue(success) await asyncio.sleep(0.5) success = audio.start_captures([streamer2]) self.assertTrue(success) await asyncio.sleep(0.5) success = audio.stop_captures([streamer2, streamer]) self.assertTrue(audio.wait_for_capture(streamer, 10000)) self.assertTrue(audio.wait_for_capture(streamer2, 10000)) self.assertTrue(os.path.exists(gen_name("streamer5.wav"))) self.assertTrue(os.path.exists(gen_name("streamer6.wav"))) self.assertTrue(os.path.isfile(gen_name("streamer5.wav"))) self.assertTrue(os.path.isfile(gen_name("streamer6.wav"))) # start a capture on an invalid filename. success = audio.start_capture(streamer, "path/does/not/exist/streamer7.wav") self.assertFalse(success) if success: await asyncio.sleep(0.5) success = audio.stop_capture(streamer) self.assertFalse(success) self.assertFalse(os.path.exists("path/does/not/exist/streamer7.wav")) success = audio.set_capture_filename(streamer, "other/bad/path/streamer.wav") self.assertFalse(success) success = audio.set_capture_filename(streamer, "other/bad/path") self.assertFalse(success) success = audio.set_capture_filename(streamer, "") self.assertFalse(success) # try starting the streamer before destroying them success = audio.start_capture(streamer2, None) self.assertTrue(success) await asyncio.sleep(0.5) # ****** clean up ****** # destroy the streamers. audio.destroy_capture_streamer(streamer) audio.destroy_capture_streamer(streamer2) audio.destroy_capture_streamer(streamer3) # try starting a capture on a destroyed streamer. success = audio.start_capture(streamer, gen_name("streamer8.wav")) self.assertFalse(success) self.assertFalse(os.path.exists(gen_name("streamer8.wav"))) success = audio.start_capture(streamer2, gen_name("streamer9.wav")) self.assertFalse(success) self.assertFalse(os.path.exists(gen_name("streamer9.wav"))) # Need to wait for an additional frames for omni.ui rebuild to take effect await wait_stage_loading() await usd_context.new_stage_async() await omni.kit.app.get_app().next_update_async() class TestCaptureEvents(omni.kit.test.AsyncTestCase): async def setUp(self): self._context = omni.usd.get_context() self.assertIsNotNone(self._context) await self._context.new_stage_async() self._stage = self._context.get_stage() self.assertIsNotNone(self._stage) self._audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(self._audio) extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}") self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() self._test_sound_1ch_path = self._test_path.joinpath("short-1ch.oga").absolute() self._prim_1ch_path = "/sound_1ch" self._prim_1ch = self._stage.DefinePrim(self._prim_1ch_path, "Sound") self.assertIsNotNone(self._prim_1ch) self._prim_1ch.GetAttribute("filePath").Set(str(self._test_sound_1ch_path)) self._prim_1ch.GetAttribute("startTime").Set(-1.0) self._streamer = self._audio.create_capture_streamer() self.assertNotEqual(self._streamer, omni.usd.audio.INVALID_STREAMER_ID) async def tearDown(self): self._audio.destroy_capture_streamer(self._streamer) async def test_capture_events(self): fmt = None open_count = 0 close_count = 0 data = [] def open_impl(stream_fmt): nonlocal fmt nonlocal open_count fmt = stream_fmt open_count += 1 def write_impl(stream_data): nonlocal data data += stream_data def close_impl(): nonlocal close_count close_count += 1 events = self._audio.create_event_stream_for_capture(self._streamer) self.assertIsNotNone(events) self.assertTrue(events) # create the listener in the middle of the stream and verify that nothing # is actually produced self._audio.start_capture(self._streamer) await asyncio.sleep(0.2) listener = omni.usd.audio.StreamListener(events, open_impl, write_impl, close_impl) self.assertIsNotNone(listener) self._audio.stop_capture(self._streamer) await asyncio.sleep(0.2) self.assertIsNone(fmt) self.assertEqual(open_count, 0); self.assertEqual(close_count, 0); self.assertEqual(len(data), 0); # this time, it should actually do something self._audio.start_capture(self._streamer) await asyncio.sleep(0.2) self.assertEqual(open_count, 1); self.assertIsNotNone(fmt) self.assertEqual(close_count, 0); self.assertGreater(len(data), 0); self._audio.stop_capture(self._streamer) await asyncio.sleep(0.2) self.assertEqual(open_count, 1); self.assertIsNotNone(fmt) self.assertEqual(close_count, 1); self.assertGreater(len(data), 0); # check that nothing was played silence = 0 if fmt.format == carb.audio.SampleFormat.PCM8: silence = 127 for v in data: self.assertEqual(v, silence); # this time we'll actually play a sound with it data = [] self._audio.start_capture(self._streamer) await asyncio.sleep(0.1) voice = self._audio.spawn_voice(self._prim_1ch) i = 0 while voice.is_playing(): await asyncio.sleep(0.01) i += 1 if (i == 2000): self.assertFalse("test timed out") self._audio.stop_capture(self._streamer) await asyncio.sleep(0.2) self.assertEqual(open_count, 2); self.assertIsNotNone(fmt) self.assertEqual(close_count, 2); self.assertGreater(len(data), 0); silent = True for v in data: if v != silence: silent = False break self.assertFalse(silent) class TestListenerEnum(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}") self._usd_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() async def test_listener_enum(self): # ****** test setup ****** audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(audio) usd_context = omni.usd.get_context() self.assertIsNotNone(usd_context) # load a test stage that has some audio prims in it. test_file_path = self._usd_path.joinpath("audio_test2.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() await wait_stage_loading() # ****** try some bad parameters ****** count = audio.get_listener_count() self.assertNotEqual(count, 0) # try an out of range index. Note that we can't try a negative number here because # pybind freaks out and throws a TypeError exception because it doesn't match the # `size_t` argument. prim = audio.get_listener_by_index(count) self.assertIsNone(prim) prim = audio.get_listener_by_index(count + 1) self.assertIsNone(prim) prim = audio.get_listener_by_index(count + 20000) self.assertIsNone(prim) prim = audio.get_listener_by_index(count - 1) self.assertIsNotNone(prim) prim = None # ****** enumerate the stage listeners ****** count = audio.get_listener_count() self.assertNotEqual(count, 0) for i in range(0, count): prim = audio.get_listener_by_index(i) self.assertIsNotNone(prim) # Need to wait for an additional frames for omni.ui rebuild to take effect await wait_stage_loading() await usd_context.new_stage_async() await omni.kit.app.get_app().next_update_async() class TestStageAudioListeners(omni.kit.test.AsyncTestCase): async def setUp(self): self._context = omni.usd.get_context() self.assertIsNotNone(self._context) self._context.new_stage() self._stage = self._context.get_stage() self.assertIsNotNone(self._stage) self._audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(self._audio) extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}") self._prim_path = "/listener" self._prim = self._stage.DefinePrim(self._prim_path, "Listener") self.assertIsNotNone(self._prim) await self._context.next_frame_async() async def tearDown(self): self._stage.RemovePrim(self._prim_path) async def test_get_listener_count(self): self.assertEqual(self._audio.get_listener_count(), 1) self._new_prim_path = "/listener1" self._new_prim = self._stage.DefinePrim(self._new_prim_path, "Listener") await self._context.next_frame_async() self.assertEqual(self._audio.get_listener_count(), 2) self._stage.RemovePrim(self._new_prim_path) async def test_set_active_listener(self): self.assertIsNone(self._audio.get_active_listener()) self._new_prim_path = "/sound" self._new_prim = self._stage.DefinePrim(self._new_prim_path, "Sound") await self._context.next_frame_async() self.assertFalse(self._audio.set_active_listener(self._new_prim)) self._stage.RemovePrim(self._new_prim_path) self.assertTrue(self._audio.set_active_listener(self._prim)) self.assertEqual(self._audio.get_active_listener(), self._prim) self.assertTrue(self._audio.set_active_listener(None)) self.assertIsNone(self._audio.get_active_listener()) # FIXME: This is just verifying that we can get/set this value. # This test should somehow verify that this feature is actually # detectable in the output audio. async def test_get_listener_by_index(self): # full enumeration of the 1 sound in the scene self.assertEqual(self._audio.get_listener_by_index(0), self._prim) self.assertIsNone(self._audio.get_listener_by_index(1))
49,917
Python
44.421292
209
0.638861
omniverse-code/kit/exts/omni.kit.audio.test.usd/omni/kit/audio/test/usd/tests/__init__.py
from .test_audio import *
26
Python
12.499994
25
0.730769
omniverse-code/kit/exts/omni.kit.audio.test.usd/docs/CHANGELOG.md
# Changelog ## [1.0.1] - 2022-06-03 ### Changed - Pass tests with either new or old Viewport.
96
Markdown
15.166664
45
0.645833
omniverse-code/kit/exts/omni.kit.audio.test.usd/docs/index.rst
omni.kit.audio.test.usd ########################### .. toctree:: :maxdepth: 1 CHANGELOG
96
reStructuredText
11.124999
27
0.458333
omniverse-code/kit/exts/omni.graph.rtxtest/PACKAGE-LICENSES/omni.graph.rtxtest-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.graph.rtxtest/config/extension.toml
[package] version = "1.0.0" title = "OmniGraph Regression Testing For Tests Requiring RTX" category = "Graph" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains test scripts and files used to test the OmniGraph functionality that exercises rendering." repository = "" keywords = ["kit", "omnigraph", "tests"] # Main module for the Python interface [[python.module]] name = "omni.graph.rtxtest" [[native.plugin]] path = "bin/*.plugin" recursive = false # Python array data uses numpy as its format [python.pipapi] requirements = ["numpy"] # Other extensions that need to load in order for this one to work [dependencies] "omni.graph.nodes" = {} "omni.kit.pipapi" = {} "omni.kit.renderer.core" = {} "omni.kit.renderer.capture" = {} "omni.kit.window.viewport" = {} "omni.usd" = {} "omni.rtx.tests" = {} [[test]] timeout = 600 stdoutFailPatterns.exclude = [ # Exclude carb.events leak that only shows up locally "*[Error] [carb.events.plugin]*PooledAllocator*", # Exclude messages which say they should be ignored "*Ignore this error/warning*", ] pythonTests.unreliable = [ "*test_prerender_gpuinterop", # OM-55399 ] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,248
TOML
23.490196
114
0.697917
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/__init__.py
"""There is no public API to this module.""" __all__ = [] from ._impl.extension import _PublicExtension # noqa: F401
119
Python
22.999995
59
0.663866
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/OgnScaleAOVTextureInPlaceDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTextureInPlace Test node for the post render graph, to scale (brighten or darken) an AOV texture in place. """ import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnScaleAOVTextureInPlaceDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTextureInPlace Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.height inputs.inputAOV inputs.multiplier inputs.rp inputs.width Outputs: outputs.exec outputs.gpu outputs.outputAOVPtr outputs.rp outputs.scheduleResult """ # 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:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:height', 'int', 0, None, 'The output RP height', {ogn.MetadataKeys.DEFAULT: '1080'}, True, 1080, False, ''), ('inputs:inputAOV', 'token', 0, None, 'The name of the AOV used during processing', {ogn.MetadataKeys.DEFAULT: '"LdrColor"'}, True, "LdrColor", False, ''), ('inputs:multiplier', 'float', 0, None, 'Multiplier applied on the inputAOV to obtain the output', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''), ('inputs:width', 'int', 0, None, 'The output RP width', {ogn.MetadataKeys.DEFAULT: '1920'}, True, 1920, False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, None, False, ''), ('outputs:outputAOVPtr', 'uint64', 0, None, 'The output AOV cuda pointer', {}, True, None, False, ''), ('outputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, None, False, ''), ('outputs:scheduleResult', 'bool', 0, None, 'If set, the cuda task was scheduled, otherwise it was not.', {}, 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.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.height) data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def inputAOV(self): data_view = og.AttributeValueHelper(self._attributes.inputAOV) return data_view.get() @inputAOV.setter def inputAOV(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.inputAOV) data_view = og.AttributeValueHelper(self._attributes.inputAOV) data_view.set(value) @property def multiplier(self): data_view = og.AttributeValueHelper(self._attributes.multiplier) return data_view.get() @multiplier.setter def multiplier(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.multiplier) data_view = og.AttributeValueHelper(self._attributes.multiplier) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.width) data_view = og.AttributeValueHelper(self._attributes.width) data_view.set(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 = { } """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 exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def outputAOVPtr(self): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) return data_view.get() @outputAOVPtr.setter def outputAOVPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def scheduleResult(self): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) return data_view.get() @scheduleResult.setter def scheduleResult(self, value): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) data_view.set(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) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnScaleAOVTextureInPlaceDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnScaleAOVTextureInPlaceDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnScaleAOVTextureInPlaceDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,784
Python
42.14
164
0.629915
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/OgnScaleAOVTextureDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTexture Helper node that tests the ComputeParams and ComputeParamsBuilder APIs in Post Render Graph nodes. """ import carb import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnScaleAOVTextureDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTexture Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.height inputs.inputAOV inputs.multiplier inputs.outputAOV inputs.rp inputs.width Outputs: outputs.exec outputs.gpu outputs.outputAOVPtr outputs.rp outputs.scheduleResult """ # 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:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:height', 'int', 0, None, 'The output RP height', {ogn.MetadataKeys.DEFAULT: '1080'}, True, 1080, False, ''), ('inputs:inputAOV', 'token', 0, None, 'The name of the AOV used during processing', {ogn.MetadataKeys.DEFAULT: '"LdrColor"'}, True, "LdrColor", False, ''), ('inputs:multiplier', 'float', 0, None, 'Multiplier applied on the inputAOV to obtain the output', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''), ('inputs:outputAOV', 'token', 0, None, 'The name of the AOV used during processing', {ogn.MetadataKeys.DEFAULT: '"scaledAOV"'}, True, "scaledAOV", False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''), ('inputs:width', 'int', 0, None, 'The output RP width', {ogn.MetadataKeys.DEFAULT: '1920'}, True, 1920, False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, None, False, ''), ('outputs:outputAOVPtr', 'uint64', 0, None, 'The output AOV cuda pointer', {}, True, None, False, ''), ('outputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, None, False, ''), ('outputs:scheduleResult', 'bool', 0, None, 'If set, the cuda task was scheduled, otherwise it was not.', {}, 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.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """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._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.height) data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def inputAOV(self): data_view = og.AttributeValueHelper(self._attributes.inputAOV) return data_view.get() @inputAOV.setter def inputAOV(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.inputAOV) data_view = og.AttributeValueHelper(self._attributes.inputAOV) data_view.set(value) @property def multiplier(self): data_view = og.AttributeValueHelper(self._attributes.multiplier) return data_view.get() @multiplier.setter def multiplier(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.multiplier) data_view = og.AttributeValueHelper(self._attributes.multiplier) data_view.set(value) @property def outputAOV(self): data_view = og.AttributeValueHelper(self._attributes.outputAOV) return data_view.get() @outputAOV.setter def outputAOV(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputAOV) data_view = og.AttributeValueHelper(self._attributes.outputAOV) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.width) data_view = og.AttributeValueHelper(self._attributes.width) data_view.set(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 = { } """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 exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def outputAOVPtr(self): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) return data_view.get() @outputAOVPtr.setter def outputAOVPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def scheduleResult(self): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) return data_view.get() @scheduleResult.setter def scheduleResult(self, value): data_view = og.AttributeValueHelper(self._attributes.scheduleResult) data_view.set(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) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnScaleAOVTextureDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnScaleAOVTextureDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnScaleAOVTextureDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,380
Python
42.109848
166
0.628207
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnScaleAOVTextureInPlace.cpp
// 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. // #include <OgnScaleAOVTextureInPlaceDatabase.h> #include "OgnTestPostRenderGraphNodeCuda.h" #include <carb/cuda/CudaRuntime.h> #include <omni/graph/image/unstable/ComputeParamsBuilder.h> #include <string> namespace omni { namespace graph { namespace rtxtest { using namespace omni::graph::image::unstable; namespace { /// A wrapper around a texture object class ScopedCudaTextureObject final { cudaTextureObject_t _texObj = 0; public: ScopedCudaTextureObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, mipLevel)); if (!levelArray) return; struct cudaResourceDesc resDesc; memset(&resDesc, 0, sizeof(resDesc)); resDesc.resType = cudaResourceTypeArray; resDesc.res.array.array = levelArray; struct cudaTextureDesc texDesc; memset(&texDesc, 0, sizeof(texDesc)); texDesc.addressMode[0] = cudaAddressModeClamp; texDesc.addressMode[1] = cudaAddressModeClamp; texDesc.filterMode = cudaFilterModePoint; texDesc.readMode = cudaReadModeElementType; texDesc.normalizedCoords = 1; CUDA_CHECK(cudaCreateTextureObject(&_texObj, &resDesc, &texDesc, nullptr)); } ~ScopedCudaTextureObject() { if (_texObj) { CUDA_CHECK(cudaDestroyTextureObject(_texObj)); } } operator cudaTextureObject_t&() { return _texObj; } }; /// A wrapper around a suface object class ScopedCudaSurfaceObject final { cudaSurfaceObject_t _surfObj = 0; public: ScopedCudaSurfaceObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, 0)); if (!levelArray) return; struct cudaResourceDesc surfResDesc; memset(&surfResDesc, 0, sizeof(surfResDesc)); surfResDesc.resType = cudaResourceTypeArray; surfResDesc.res.array.array = levelArray; CUDA_CHECK(cudaCreateSurfaceObject(&_surfObj, &surfResDesc)); } ~ScopedCudaSurfaceObject() { if (_surfObj) { CUDA_CHECK(cudaDestroySurfaceObject(_surfObj)); } } operator cudaSurfaceObject_t&() { return _surfObj; } }; } // anonymous namespace class OgnScaleAOVTextureInPlace { public: static bool compute(OgnScaleAOVTextureInPlaceDatabase& db) { // The gpu and rp inputs are passed through to the output. // They are only present here so that the nodes GpuInteropGpuToCpuCopy and GpuInteropCpuToDisk can be connected // after the current test node, to establish the correct topological order in the graph. // An alternate way to do this is to use a dummy execution port for this purpose (this is what the SDG nodes do). // In the future, the data protocol for post render graph nodes should standardize the inputs of the nodes and // prevent the need for passing raw pointers around. db.outputs.gpu() = db.inputs.gpu(); db.outputs.rp() = db.inputs.rp(); auto gpu = reinterpret_cast<GpuFoundationsInterfaces*>(db.inputs.gpu()); auto rp = reinterpret_cast<omni::usd::hydra::HydraRenderProduct*>(db.inputs.rp()); // This node is called in tests and has to fail hard CARB_ASSERT(gpu); CARB_ASSERT(rp); auto result = ComputeParamsBuilder<std::string>{ gpu, rp, db } .addValue("multiplier", db.inputs.multiplier()) .addInputTexture("inputAOV", db.inputs.inputAOV(), [&db](cudaMipmappedArray_t cudaPtr, carb::graphics::TextureDesc const* desc, ComputeParams<std::string>& params) { // the desc pointer is guaranteed to be valid params.add("width", desc->width); params.add("height", desc->height); db.outputs.outputAOVPtr() = reinterpret_cast<uint64_t>(cudaPtr); }) .scheduleCudaTask("TestCudaTask", [](ComputeParams<std::string>* data, cudaStream_t stream) { auto multiplier = data->get<float>("multiplier"); auto inputAOV = data->get<cudaMipmappedArray_t>("inputAOV"); auto width = data->get<uint32_t>("width"); auto height = data->get<uint32_t>("height"); CARB_ASSERT(multiplier != 0.0f); CARB_ASSERT(width != 0.0f); CARB_ASSERT(height != 0.0f); ScopedCudaSurfaceObject textureData(inputAOV); cudaScaleImageInPlace(textureData, multiplier, width, height, stream); }, [](ComputeParams<std::string> const& params) -> bool { return params.hasKey("inputAOV") && params.get<cudaMipmappedArray_t>("inputAOV") != nullptr; }); db.outputs.scheduleResult() = result; return result; } }; REGISTER_OGN_NODE() } // test } // namespace graph } // namespace omni
5,717
C++
33.865853
128
0.629701
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnTestPostRenderGraphNodeCuda.h
// 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. // #pragma once #include <carb/cuda/CudaRuntime.h> #include <carb/cudainterop/CudaInterop.h> extern "C" void cudaScaleImage(cudaTextureObject_t inputTexture, float multiplier, uint32_t width, uint32_t height, cudaSurfaceObject_t outputTexture, cudaStream_t stream); extern "C" void cudaScaleImageInPlace(cudaSurfaceObject_t textureData, float multiplier, uint32_t width, uint32_t height, cudaStream_t stream);
1,131
C
44.279998
77
0.599469
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/nodes/OgnScaleAOVTexture.cpp
// 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. // #include <OgnScaleAOVTextureDatabase.h> #include "OgnTestPostRenderGraphNodeCuda.h" #include <carb/cuda/CudaRuntime.h> #include <omni/graph/image/unstable/ComputeParamsBuilder.h> #include <string> namespace omni { namespace graph { namespace rtxtest { using namespace omni::graph::image::unstable; namespace { /// A wrapper around a texture object class ScopedCudaTextureObject final { cudaTextureObject_t _texObj = 0; public: ScopedCudaTextureObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, mipLevel)); if (!levelArray) return; struct cudaResourceDesc resDesc; memset(&resDesc, 0, sizeof(resDesc)); resDesc.resType = cudaResourceTypeArray; resDesc.res.array.array = levelArray; struct cudaTextureDesc texDesc; memset(&texDesc, 0, sizeof(texDesc)); texDesc.addressMode[0] = cudaAddressModeClamp; texDesc.addressMode[1] = cudaAddressModeClamp; texDesc.filterMode = cudaFilterModePoint; texDesc.readMode = cudaReadModeElementType; texDesc.normalizedCoords = 1; CUDA_CHECK(cudaCreateTextureObject(&_texObj, &resDesc, &texDesc, nullptr)); } ~ScopedCudaTextureObject() { if (_texObj) { CUDA_CHECK(cudaDestroyTextureObject(_texObj)); } } operator cudaTextureObject_t&() { return _texObj; } }; /// A wrapper around a suface object class ScopedCudaSurfaceObject final { cudaSurfaceObject_t _surfObj = 0; public: ScopedCudaSurfaceObject(cudaMipmappedArray_t mmarr, int mipLevel = 0) { if (!mmarr) return; cudaArray_t levelArray = 0; CUDA_CHECK(cudaGetMipmappedArrayLevel(&levelArray, mmarr, 0)); if (!levelArray) return; struct cudaResourceDesc surfResDesc; memset(&surfResDesc, 0, sizeof(surfResDesc)); surfResDesc.resType = cudaResourceTypeArray; surfResDesc.res.array.array = levelArray; CUDA_CHECK(cudaCreateSurfaceObject(&_surfObj, &surfResDesc)); } ~ScopedCudaSurfaceObject() { if (_surfObj) { CUDA_CHECK(cudaDestroySurfaceObject(_surfObj)); } } operator cudaSurfaceObject_t&() { return _surfObj; } }; } class OgnScaleAOVTexture { public: static bool compute(OgnScaleAOVTextureDatabase& db) { // The gpu and rp inputs are passed through to the output. // They are only present here so that the nodes GpuInteropGpuToCpuCopy and GpuInteropCpuToDisk can be connected // after the current test node, to establish the correct topological order in the graph. // An alternate way to do this is to use a dummy execution port for this purpose (this is what the SDG nodes do). // In the future, the data protocol for post render graph nodes should standardize the inputs of the nodes and // prevent the need for passing raw pointers around. db.outputs.gpu() = db.inputs.gpu(); db.outputs.rp() = db.inputs.rp(); auto gpu = reinterpret_cast<GpuFoundationsInterfaces*>(db.inputs.gpu()); auto rp = reinterpret_cast<omni::usd::hydra::HydraRenderProduct*>(db.inputs.rp()); // This node is called in tests and has to fail hard CARB_ASSERT(gpu); CARB_ASSERT(rp); auto result = ComputeParamsBuilder<std::string>{ gpu, rp, db } .addValue("multiplier", db.inputs.multiplier()) .addInputTexture("inputAOV", db.inputs.inputAOV(), [&db](cudaMipmappedArray_t cudaPtr, carb::graphics::TextureDesc const* desc, ComputeParams<std::string>& params) { // the desc pointer is guaranteed to be valid params.add("width", desc->width); params.add("height", desc->height); }) .addOutputTexture("outputAOV", db.inputs.outputAOV(), db.inputs.width(), db.inputs.height(), carb::graphics::Format::eRGBA8_UNORM, "TestTexture", [&db](cudaMipmappedArray_t ptr) { db.outputs.outputAOVPtr() = reinterpret_cast<uint64_t>(ptr); }) .scheduleCudaTask("TestCudaTask", [](ComputeParams<std::string>* data, cudaStream_t stream) { auto multiplier = data->get<float>("multiplier"); auto inputAOV = data->get<cudaMipmappedArray_t>("inputAOV"); auto outputAOV = data->get<cudaMipmappedArray_t>("outputAOV"); auto width = data->get<uint32_t>("width"); auto height = data->get<uint32_t>("height"); CARB_ASSERT(multiplier != 0.0f); CARB_ASSERT(width != 0.0f); CARB_ASSERT(height != 0.0f); ScopedCudaTextureObject inputTex(inputAOV); ScopedCudaSurfaceObject outputTex(outputAOV); cudaScaleImage(inputTex, multiplier, width, height, outputTex, stream); }, [](ComputeParams<std::string> const& params) -> bool { return params.hasKey("inputAOV") && params.get<cudaMipmappedArray_t>("inputAOV") != nullptr && params.hasKey("outputAOV") && params.get<cudaMipmappedArray_t>("outputAOV") != nullptr; }); db.outputs.scheduleResult() = result; return result; } }; REGISTER_OGN_NODE() } // test } // namespace graph } // namespace omni
6,189
C++
34.988372
128
0.620456
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/_impl/extension.py
"""Support required by the Carbonite extension loader""" import omni.ext from ..bindings._omni_graph_rtxtest import acquire_interface as _acquire_interface # noqa: PLE0402 from ..bindings._omni_graph_rtxtest import release_interface as _release_interface # noqa: PLE0402 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.__interface = None def on_startup(self): """Set up initial conditions for the Python part of the extension""" self.__interface = _acquire_interface() def on_shutdown(self): """Shutting down this part of the extension prepares it for hot reload""" if self.__interface is not None: _release_interface(self.__interface) self.__interface = None
905
Python
36.749998
99
0.669613
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
201
Python
32.666661
112
0.716418
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_viewport_nodes.py
"""test viewport nodes""" import asyncio import inspect import pathlib import carb.input import omni.graph.core as og import omni.usd from omni.kit.ui_test.input import emulate_keyboard_press from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings from omni.rtx.tests.test_common import wait_for_update from omni.ui.tests.compare_utils import CompareMetric, capture_and_compare from pxr import UsdGeom EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) GOLDEN_IMG_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden") # ====================================================================== class TestViewportNodes(RtxTest): def __init__(self, tests=()): super().__init__(tests) self.test_graph_path = "/World/TestGraph" async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def tearDown(self): await super().tearDown() await omni.kit.stage_templates.new_stage_async() @property def __test_name(self) -> str: """ The full name of the test. It has the name of the module, class and the current test function. We use the stack to get the name of the test function and since it's only called from create_test_window and finalize_test, we get the third member. """ return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def capture_and_compare(self, image_name: str, threshold=RtxTest.THRESHOLD, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED): """ RtxTest.capture_and_compare() captures directly from the viewport's texture, however, we need to capture from the swap chain in order to take into account the overlay image that hides the current frame during viewport render lock. """ diff = await capture_and_compare(image_name, threshold, GOLDEN_IMG_DIR, True, cmp_metric) if diff != 0: carb.log_warn(f"[{self.__test_name}] the generated image {image_name} has max difference {diff}") if diff >= threshold: self._failedImages.append(image_name) return diff def create_mesh(self, name): """Create a cube mesh""" cube = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) cube.CreatePointsAttr( [ (-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50), ] ) cube.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) cube.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) cube.CreateSubdivisionSchemeAttr("none") return cube async def test_lock_viewport_render(self): """Validate viewport render lock & unlock for OgnLockViewportRender""" # create a cube mesh cube = self.create_mesh("/World/cube") # create action graph controller = og.Controller() graph = controller.create_graph({"graph_path": self.test_graph_path, "evaluator_name": "execution"}) controller.edit( graph, { og.Controller.Keys.CREATE_NODES: [ ("on_keyboard_input_l", "omni.graph.action.OnKeyboardInput"), ("on_keyboard_input_u", "omni.graph.action.OnKeyboardInput"), ("lock_viewport_render", "omni.graph.ui_nodes.LockViewportRender"), ], og.Controller.Keys.CONNECT: [ ("on_keyboard_input_l.outputs:released", "lock_viewport_render.inputs:lock"), ("on_keyboard_input_u.outputs:released", "lock_viewport_render.inputs:unlock"), ], og.Controller.Keys.SET_VALUES: [ ("on_keyboard_input_l.inputs:keyIn", "L"), ("on_keyboard_input_l.inputs:onlyPlayback", False), ("on_keyboard_input_u.inputs:keyIn", "U"), ("on_keyboard_input_u.inputs:onlyPlayback", False), ], }, ) # Initial await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.initial.png") # Lock viewport render await emulate_keyboard_press(carb.input.KeyboardInput.L) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.locked.png") # Scale the cube scale_op = UsdGeom.Xformable(cube).AddScaleOp() scale = 2.0 scale_op.Set((scale, scale, scale)) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.scaled.png") # Unlock viewport render and wait for the fading duration (1 second by default) to complete await emulate_keyboard_press(carb.input.KeyboardInput.U) await asyncio.sleep(1.1) await self.capture_and_compare("test_lock_viewport_render.unlocked.png") # Lock viewport render and scale the cube again await emulate_keyboard_press(carb.input.KeyboardInput.L) scale = 3.0 scale_op.Set((scale, scale, scale)) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.relocked.png") # Remove the node. The viewport render will be automatically unlocked. controller.edit(graph, { og.Controller.Keys.DELETE_NODES: "lock_viewport_render" }) await wait_for_update(self.ctx) await self.capture_and_compare("test_lock_viewport_render.removed.png")
6,018
Python
38.339869
131
0.601695
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_post_render_graph.py
"""Tests for the post render graph scaffolding APIs""" import carb import inspect import pathlib import omni.graph.core as og import omni.graph.core.tests as ogts import omni.hydratexture from omni.kit.viewport.utility import get_active_viewport import omni.kit.test from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings, OUTPUTS_DIR from omni.rtx.tests.test_common import wait_for_update from pxr import Gf, Sdf, Usd, UsdGeom EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden") THRESHOLD = 1e-4 class TestPostRenderGraphs(RtxTest): @staticmethod def get_aov_list(stage: Usd.Stage, rp_prim_path) -> list[str]: aovs : list[str] = [] render_vars = stage.GetPrimAtPath(rp_prim_path).GetRelationship("orderedVars").GetForwardedTargets() for render_var in render_vars: aov_name = stage.GetPrimAtPath(render_var).GetAttribute("sourceName").Get() aovs.append(aov_name) return aovs @property def __test_name(self) -> str: """ The full name of the test. It has the name of the module, class and the current test function. We use the stack to get the name of the test function and since it's only called from create_test_window and finalize_test, we get the third member. """ return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" def render_product_path(self, hydra_texture) -> str: '''Return a string to the UsdRender.Product used by the texture''' render_product = hydra_texture.get_render_product_path() if render_product and (not render_product.startswith('/')): render_product = '/Render/RenderProduct_' + render_product return render_product def compare_output_image(self, golden_img_name, threshold, output_img_dir: pathlib.Path, golden_img_dir: pathlib.Path, metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED): """Compare an arbitrary image with a golden image. The image generated in the test could be produced by OgnGpuInteropCpuToDisk or some other method.""" diff = finalize_capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric=metric) if diff != 0: carb.log_warn(f"[{self.__test_name}] the generated image {golden_img_name} has max difference {diff}") if (diff is not None) and diff >= threshold: self._failedImages.append(golden_img_name) return diff async def setUpProps(self, stage): # add a couple of prims in the scene cube = ogts.create_cube(stage, "Cube", (255, 0, 0)) sphere = ogts.create_sphere(stage, "Sphere", (0, 255, 0)) xform_cube = UsdGeom.Xformable(cube) xform_cube.AddTranslateOp().Set((0, 30, 40)) xform_cube.AddScaleOp().Set(Gf.Vec3f(30.0)) xform_sphere = UsdGeom.Xformable(sphere) xform_sphere.AddTranslateOp().Set((0, 30, -40)) xform_sphere.AddScaleOp().Set(Gf.Vec3f(25.0)) await wait_for_update(self.ctx, 10) async def setUp(self): await super().setUp() # must apply the test settings to the renderer to ensure that the test setup matches the SDG setup self.set_settings(testSettings) # set up the stage omni.usd.get_context().new_stage() self.add_dir_light() self.add_floor() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) # renderer renderer = "rtx" if renderer not in self.ctx.get_attached_hydra_engine_names(): omni.usd.add_hydra_engine(renderer, self.ctx) self._stage = self.ctx.get_stage() session_layer = self._stage.GetSessionLayer() with Usd.EditContext(self._stage, session_layer): # set the render product on the active viewport viewport_api = get_active_viewport() if viewport_api: self._render_product_path_0 = viewport_api.render_product_path # create the post render graph pipeline_stage = og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER execution_model = "push" orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage) top_graph = orchestration_graphs[0] self._og_graph_path = f"{self._render_product_path_0}/TestPostRender" compound_node1 = top_graph.create_graph_as_node( "TestPostRender", self._og_graph_path, evaluator=execution_model, is_global_graph=True, is_backed_by_usd=True, backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED, pipeline_stage=pipeline_stage) self._post_render_graph = compound_node1.get_wrapped_graph() # set the ogPostProcessPath attribute to associate the graph with this render product attr_name = "ogPostProcessPath" self._stage.GetPrimAtPath(self._render_product_path_0).CreateAttribute(attr_name, Sdf.ValueTypeNames.String).Set(self._og_graph_path) # debug sanity check # carb.log_info(f"!!! rp_path:{self._render_product_path_0}") # carb.log_info(f"!!! og_path:{self._og_graph_path}") # carb.log_info(f"!!! rp_aovs: {self.get_aov_list(self._stage, self._render_product_path_0)}") # carb.log_info(f"!!! rp.ogPostProcessPath={self._stage.GetPrimAtPath(self._render_product_path_0).GetAttribute(attr_name).Get()}") # carb.log_info(f"!!! og.nodes={self._post_render_graph.get_nodes()}") async def tearDown(self): await super().tearDown() # ----------------------------------------------------------------------------- async def test_modify_aov(self): """Validate that the post render graph can modify an AOV in place.""" await self.setUpProps(self._stage) await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.graph.rtxtest", golden_img_name="test_modify_aov.initial.png", threshold=THRESHOLD) keys = og.Controller.Keys (_, (_, test_node), _, _) = og.Controller.edit( self._post_render_graph, { keys.CREATE_NODES: [ ("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"), ("TestNode", "omni.graph.rtxtest.ScaleAOVTextureInPlace"), ], keys.CONNECT: [ ("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"), ("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"), ("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"), ], keys.SET_VALUES: [ ("TestNode.inputs:inputAOV", "LdrColor"), ("TestNode.inputs:multiplier", 1.5), ("TestNode.inputs:width", self.WINDOW_SIZE[0]), ("TestNode.inputs:height", self.WINDOW_SIZE[1]), ] }, ) await wait_for_update(self.ctx, 10) # Validate that the outputAOVPtr attribute is set. # This attribute is set after getting from the RenderProduct # the pointer of the AOV with the token set on the "inputAOV" attribute. actual = og.Controller.get(og.Controller.attribute("outputs:outputAOVPtr", test_node)) self.assertNotEqual(0, actual) # validate that the scheduleCudaTask() method returned true schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node)) self.assertEqual(True, schedule_result) await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.graph.rtxtest", golden_img_name="test_modify_aov.scaled.png", threshold=THRESHOLD) # ----------------------------------------------------------------------------- async def test_create_new_aov(self): """Validate that the post render graph can create new AOVs without throwing.""" # This test allocates a new AOV, saves it to disk and compares it with a golden image # NOTE: the image produced by the test seems to be missing the expected details, indicating # a bug in the test nodes. Since this test does not rely on the actual data in the buffer # being correct, the test is considered valid. await self.setUpProps(self._stage) output_image_dir = OUTPUTS_DIR.joinpath("omni.graph.rtxtest") keys = og.Controller.Keys (_, (_, test_node, _, _), _, _) = og.Controller.edit( self._post_render_graph, { keys.CREATE_NODES: [ ("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"), ("TestNode", "omni.graph.rtxtest.ScaleAOVTexture"), ("GpuToCpuCopy", "omni.graph.examples.cpp.GpuInteropGpuToCpuCopy"), ("CpuToDisk", "omni.graph.examples.cpp.GpuInteropCpuToDisk"), ], keys.CONNECT: [ ("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"), ("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"), ("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"), ("TestNode.outputs:gpu", "GpuToCpuCopy.inputs:gpu"), ("TestNode.outputs:rp", "GpuToCpuCopy.inputs:rp"), ("GpuToCpuCopy.outputs:gpu", "CpuToDisk.inputs:gpu"), ("GpuToCpuCopy.outputs:rp", "CpuToDisk.inputs:rp"), ("GpuToCpuCopy.outputs:aovCpu", "CpuToDisk.inputs:aovCpu"), ], keys.SET_VALUES: [ ("TestNode.inputs:inputAOV", "LdrColor"), ("TestNode.inputs:outputAOV", "scaledColor"), ("TestNode.inputs:multiplier", 1.5), ("TestNode.inputs:width", self.WINDOW_SIZE[0]), ("TestNode.inputs:height", self.WINDOW_SIZE[1]), ("GpuToCpuCopy.inputs:aovGpu", "scaledColor"), ("CpuToDisk.inputs:aovGpu", "scaledColor"), ("CpuToDisk.inputs:frameCount", 1), ("CpuToDisk.inputs:saveLocation", str(output_image_dir)), ("CpuToDisk.inputs:fileName", "test_create_new_aov"), # final name: test_create_new_aov_scaledColor.png ("CpuToDisk.inputs:autoFileNumber", 0), ] }, ) await wait_for_update(self.ctx, 10) # validate that the outputAOVPtr attribute is set - this attribute is set after the new AOV is allocated actual = og.Controller.get(og.Controller.attribute("outputs:outputAOVPtr", test_node)) self.assertNotEqual(0, actual) # validate that the scheduleCudaTask() method returned true schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node)) self.assertEqual(True, schedule_result) self.compare_output_image( "test_create_new_aov_scaledColor.png", THRESHOLD, output_image_dir, GOLDEN_DIR) # ----------------------------------------------------------------------------- async def test_invalid_input_aov_param__fails(self): """Validate that nodes accessing invalid AOVs do not schedule cuda tasks""" keys = og.Controller.Keys (_, (_, test_node), _, _) = og.Controller.edit( self._post_render_graph, { keys.CREATE_NODES: [ ("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"), ("TestNode", "omni.graph.rtxtest.ScaleAOVTextureInPlace"), ], keys.CONNECT: [ ("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"), ("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"), ("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"), ], keys.SET_VALUES: [ ("TestNode.inputs:inputAOV", "InvalidAOVToken"), ("TestNode.inputs:multiplier", 1.5), ("TestNode.inputs:width", self.WINDOW_SIZE[0]), ("TestNode.inputs:height", self.WINDOW_SIZE[1]), ] }, ) await wait_for_update(self.ctx, 10) # the builder will log a warning if an AOV is not found self.assertEqual(len(test_node.get_compute_messages(og.WARNING)), 1) # validate that the scheduleCudaTask() method returned false schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node)) self.assertEqual(False, schedule_result)
13,459
Python
45.413793
159
0.58838
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_gpu_interop.py
"""test gpu interop nodes""" import pathlib import omni.graph.core as og import omni.kit.commands import omni.kit.stage_templates import omni.kit.test import omni.usd from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings from omni.rtx.tests.test_common import wait_for_update from pxr import UsdGeom EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden") # ====================================================================== class TestPreRender(RtxTest): async def setUp(self): await super().setUp() self.set_settings(testSettings) omni.usd.get_context().new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() self.set_settings(postLoadTestSettings) async def tearDown(self): await super().tearDown() await omni.kit.stage_templates.new_stage_async() def create_mesh(self, name): box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name) box.CreatePointsAttr( [ (-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50), ] ) box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4]) box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]) box.CreateSubdivisionSchemeAttr("none") return box # ---------------------------------------------------------------------- async def test_prerender_gpuinterop(self): controller = og.Controller() keys = og.Controller.Keys() (_, _, _, _) = controller.edit( {"graph_path": "/PushGraph", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_PRERENDER}, { keys.CREATE_NODES: [ ("ConstantString", "omni.graph.nodes.ConstantString"), ("ToToken", "omni.graph.nodes.ToToken"), ("ReadPoints", "omni.graph.nodes.ReadPrimAttribute"), ("Entry", "omni.graph.nodes.RenderPreProcessEntry"), ("Allocator", "omni.graph.nodes.RpResourceExampleAllocator"), ("Deformer", "omni.graph.nodes.RpResourceExampleDeformer"), ("ToHydra", "omni.graph.nodes.RpResourceExampleHydra"), ], keys.CONNECT: [ ("ConstantString.inputs:value", "ToToken.inputs:value"), ("ToToken.outputs:converted", "ReadPoints.inputs:primPath"), ("ToToken.outputs:converted", "Allocator.inputs:primPath"), ("ReadPoints.outputs:value", "Allocator.inputs:points"), ("Entry.outputs:stream", "Allocator.inputs:stream"), ("Allocator.outputs:pointCountCollection", "Deformer.inputs:pointCountCollection"), ("Allocator.outputs:primPathCollection", "Deformer.inputs:primPathCollection"), ("Allocator.outputs:resourcePointerCollection", "Deformer.inputs:resourcePointerCollection"), ("Allocator.outputs:stream", "Deformer.inputs:stream"), ("Deformer.outputs:pointCountCollection", "ToHydra.inputs:pointCountCollection"), ("Deformer.outputs:primPathCollection", "ToHydra.inputs:primPathCollection"), ("Deformer.outputs:resourcePointerCollection", "ToHydra.inputs:resourcePointerCollection"), ], keys.SET_VALUES: [ ("ConstantString.inputs:value", "/World/box"), ("ReadPoints.inputs:usePath", True), ("ReadPoints.inputs:name", "points"), ("Deformer.inputs:deformScale", 50.0), ("Deformer.inputs:positionScale", 100.0), ("ToHydra.inputs:sendToHydra", True), ], }, ) self.create_mesh("/World/box") await wait_for_update(self.ctx, 30) await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.graph.rtxtest", golden_img_name="gpuinterop_prerender_deformer.png", threshold=1e-4, )
4,519
Python
42.461538
113
0.547466
omniverse-code/kit/exts/omni.graph.rtxtest/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.0] - 2022-08-30 ### Added - Migrated the prerender graph tests from omni.graph.test
345
Markdown
30.454543
87
0.736232
omniverse-code/kit/exts/omni.graph.rtxtest/docs/README.md
# OmniGraph Integration Testing With RTX [omni.graph.rtxtest] This extension contains support for tests that exercise RTX features such as the pre-render graph. ## Published Documentation The automatically-published user guide from this repo can be viewed :ref:`here<index.rst>`
282
Markdown
34.374996
98
0.801418
omniverse-code/kit/exts/omni.graph.rtxtest/docs/index.rst
.. _omni.graph.rtxtest: OmniGraph Integration RTX Testing ################################# .. tabularcolumns:: |L|R| .. csv-table:: :width: 100% **Extension**: omni.graph.rtxtest,**Documentation Generated**: |today| There were some instabilities in `omni.graph.test` tests that were related to what looked like rendering issues. This extension was created to isolate the requirement for rendering-related libraries so that the other tests could run in headless mode, minimizing the chance of random failures. .. toctree:: :maxdepth: 1 CHANGELOG
565
reStructuredText
25.95238
117
0.702655
omniverse-code/kit/exts/omni.graph.rtxtest/docs/Overview.md
# OmniGraph Integration RTX Testing ```{csv-table} **Extension**: omni.graph.action,**Documentation Generated**: {sub-ref}`today` ``` There were some instabilities in `omni.graph.test` tests that were related to what looked like rendering issues. This extension was created to isolate the requirement for rendering-related libraries so that the other tests could run in headless mode, minimizing the chance of random failures.
428
Markdown
46.666661
117
0.787383
omniverse-code/kit/exts/omni.rtx.shadercache.vulkan/omni/rtx/shadercache/vulkan/__init__.py
from .shadercache_vulkan import ShaderCacheConfig
50
Python
24.499988
49
0.88
omniverse-code/kit/exts/omni.rtx.shadercache.vulkan/omni/rtx/shadercache/vulkan/shadercache_vulkan.py
import omni.ext class ShaderCacheConfig(omni.ext.IExt): def on_startup(self, ext_id): """Callback when the extension is starting up""" pass def on_shutdown(self): """Callback when the extension is shutting down""" pass
261
Python
22.81818
58
0.636015
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/PACKAGE-LICENSES/omni.kit.widget.nucleus_connector-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/config/extension.toml
[package] title = "Kit Nucleus Connector" version = "1.0.3" category = "Internal" description = "Helper extension for connecting to Nucleus servers" authors = ["NVIDIA"] slackids = ["UQY4RMR3N"] repository = "" keywords = ["kit", "ui", "nucleus"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.kit.window.popup_dialog" = {} "omni.client" = {} [[python.module]] name = "omni.kit.widget.nucleus_connector" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.ui_test", ]
628
TOML
19.966666
66
0.660828
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/connector.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 asyncio import omni.client import carb from typing import Callable from functools import partial from .ui import ConnectorDialog, AlertPane class NucleusConnector: """ NucleusConnector object helps with connecting to Nucleus servers. """ def __init__(self): self._dialog = None def start_auth_flow(self, host_name, auth_handle: int): """ Called at the start of the authentication cycle. Most importantly, prepares a cancel button so that the user can cancel out of the process if it hangs for any reason. Args: host_name (str): The server host name that the authentication is for auth_handle (int): An integer handle that should be passed to cancel authentication """ # OM-76995: for authentication callback, it is okay to re-use dialogs created since it most often comes from # connection operations already if not self._dialog: self._dialog = ConnectorDialog() # Set dialog fields only if they're empty name = self._dialog.get_value('name') or host_name url = omni.client.make_url(scheme='omniverse', host=self._dialog.get_value('url') or host_name) self._dialog.show_authenticate(name=name, url=url) self._dialog.set_cancel_clicked_fn(partial(self.cancel_auth, auth_handle)) def end_auth_flow(self, auth_handle: int): """Called at the end of the authentication cycle; hides the app dialog""" if self._dialog: self._dialog.hide() self._dialog = None def cancel_auth(self, auth_handle: int, dialog: ConnectorDialog): """ This callback is attached to the dialog's cancel button. It cancels the authentication process. Args: auth_handle (int): An integer handle that should be passed to cancel authentication """ # Cancel the dialog task if self._dialog: self._dialog.cancel_task() self._dialog.hide() self._dialog = None # Cancel the auth flow in the browser omni.client.authentication_cancel(auth_handle) def connect_with_callback(self, name: str = None, url: str = None, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Unless specified, prompts for server name and Url and proceeds to connect to it. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ def on_connect_server(on_success_fn: Callable, on_failed_fn: Callable, dialog: ConnectorDialog, name: str = None, url: str = None, show_waiting: bool = True): if not name: name = dialog.get_value("name") if not url: url = dialog.get_value("url") # OMFP-2249: If no name/url is present, we do nothing (when "ok" button is clicked) if not url and not name: return if show_waiting: dialog.show_waiting() # Give dialog ownership of the task so that it can cancel at will. asyncio.ensure_future(dialog.run_cancellable_task( self.connect_server_async(name, url, on_success_fn, on_failed_fn, dialog=dialog))) def on_cancel(dialog): dialog.cancel_task() dialog.hide() # OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly self._dialog = ConnectorDialog() if url: self._dialog.show_authenticate(name=name, url=url) # If server is explicitly specified, then proceed to connect rather than wait for user input. on_connect_server(on_success_fn, on_failed_fn, self._dialog, name=name, url=url) return self._dialog.show(name=name, url=url) self._dialog.set_okay_clicked_fn(partial(on_connect_server, on_success_fn, on_failed_fn)) self._dialog.set_cancel_clicked_fn(on_cancel) async def connect_server_async(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None, retry: bool = False, dialog: ConnectorDialog = None): """ Connects to the named server. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) retry (bool): True if re-trying for second time. dialog (ConnectorDialog): A dialog instance to re-use from parent operation. """ if not url: carb.log_warn(f"Error connecting server, missing Url.") return elif not url.startswith("omniverse://"): url = f"omniverse://{url}" if not name: # If no name specified, then use name of child directory name = list(filter(None, url.split("/")))[-1] if not dialog: dialog = ConnectorDialog() dialog.show_authenticate(name=name, url=url) result, stats = None, None try: # This stat triggers the start of the authentication flow result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: dialog.hide() dialog.destroy() if on_success_fn: on_success_fn(name, url) elif result == omni.client.Result.ERROR_CONNECTION and not retry: # Note: Strangely, omni.client returns error if the user has previously connected or disconnected from # this server. In this case, only a reconnect will succeed. omni.client.reconnect(url) await self.connect_server_async( name, url, on_success_fn=on_success_fn, on_failed_fn=on_failed_fn, retry=True, dialog=dialog) else: msg = f"Unable to connect server '{url}'. Please check your internet connection then try again." dialog.show_alert(msg, AlertPane.Warn) if on_failed_fn: on_failed_fn(name, url) async def reconnect_server_async(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Re-connects to the named server. Args: url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if not url: carb.log_warn(f"Error reconnecting server, missing Url.") return name = list(filter(None, url.split("/")))[-1] # OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly self._dialog = ConnectorDialog() self._dialog.show_authenticate(name=name, url=url) # Do the reconnect omni.client.reconnect(url) result, stats = None, None try: result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: if self._dialog: self._dialog.hide() self._dialog = None if on_success_fn: on_success_fn(name, url) else: msg = f"Unable to connect server '{url}'. Please check your internet connection then try again." if not self._dialog: self._dialog = ConnectorDialog() self._dialog.show_alert(msg, AlertPane.Warn) if on_failed_fn: on_failed_fn(name, url) def destroy(self): """Destructor.""" if self._dialog: self._dialog.destroy() self._dialog = None
9,046
Python
40.884259
178
0.609441
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/style.py
from omni import ui from pathlib import Path CURRENT_PATH = Path(__file__).parent DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data") ICON_PATH = DATA_PATH.joinpath("icons") class Colors: Background = ui.color.shade(0xFF23211F, light=0xFF535354) Border = ui.color.shade(0xFFA1A1A1, light=0xFFE0E0E0) ButtonHovered = ui.color.shade(0xFF9A9A9A, light=0xFF9A9A9A) ButtonSelected = ui.color.shade(0xFF9A9A9A, light=0xFF9A9A9A) Text = ui.color.shade(0xFFA1A1A1, light=0xFFE0E0E0) TextWarn = ui.color.shade(0xFF3333A1, light=0xFF3333E0) Url = ui.color.shade(0xFFE8AD4B, light=0xFFE00000) Image = ui.color.shade(0xFFA8A8A8, light=0xFFA8A8A8) ProgressBackground = ui.color.shade(0xFF24211F, light=0xFF24211F) ProgressBorder = ui.color.shade(0xFF323434, light=0xFF323434) ProgressBar = ui.color.shade(0xFFC9974C, light=0xFFC9974C) AlertPaneBackground = ui.color.shade(0xFF3A3A3A, light=0xFF323434) InfoPaneBorder = ui.color.shade(0xFFC9974C, light=0xFFC9974C) WarningPaneBorder = ui.color.shade(0xFF318693, light=0xFF318693) UI_STYLES = { "Dialog": { "background_color": Colors.Background, "margin_width": 8, "margin_height": 8, }, "Image": { "background_color": 0x0, "margin": 0, "padding": 0, "color": Colors.Image, "alignment": ui.Alignment.CENTER, }, "QrCode": { "background_color": 0x0, "margin": 10, "padding": 0, "alignment": ui.Alignment.CENTER, }, "Image.Label": {"color": Colors.Text, "alignment": ui.Alignment.CENTER}, "ProgressBar": { "background_color": Colors.ProgressBackground, "border_width": 2, "border_radius": 0, "border_color": Colors.ProgressBorder, "color": Colors.ProgressBar, "margin": 0, "padding": 0, "alignment": ui.Alignment.LEFT_CENTER, }, "ProgressBar.Frame": { "background_color": 0xFF23211F, "margin": 0, "padding": 0, }, "ProgressBar.Puck": { "background_color": Colors.ProgressBar, "margin": 2, }, "StringField.Url": { "color": Colors.Url, "background_color": 0x0, }, "Label": {"color": Colors.Text}, "Label.Code": { "color": Colors.Text, "alignment": ui.Alignment.CENTER, "font_size": 40, }, "Label.TimeRemaining": {"color": Colors.Url}, "Label.Expired": { "color": Colors.TextWarn, "alignment": ui.Alignment.CENTER }, "AlertPane": { "background_color": Colors.AlertPaneBackground, "color": Colors.Text, "margin": 0, "border_radius": 0.0 }, "AlertPane::info": { "border_color": Colors.InfoPaneBorder, "border_width": 2, }, "AlertPane::warn": { "border_color": Colors.WarningPaneBorder, "border_width": 2, }, "AlertPane.Content": { "background_color": 0x0, "margin_width": 8, "margin_height": 12 }, "AlertPanePane.Clear": { "background_color": 0x0, "border_radius": 0.0, "border_color": Colors.Text, "border_width": 1, "margin": 0, "padding": 2, }, "AlertPane.Clear:hovered": {"background_color": Colors.ButtonHovered}, "AlertPane.Clear.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": Colors.Text}, }
3,437
Python
30.833333
91
0.601688
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/device_auth.py
# Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import omni.client import carb from typing import Callable from functools import partial from .ui import DeviceAuthFlowDialog, ConnectorDialog, AlertPane class DeviceAuthConnector: """ DeviceAuthConnector object that helps with connecting to Nucleus servers via device flow. """ def __init__(self): self._conn_status_sub = omni.client.register_connection_status_callback(self._connection_status_changed) self._pending_results = {} # url: (auth_handle, dialog instance) def start_auth_flow(self, auth_handle: int, params: omni.client.AuthDeviceFlowParams): """ Called at the start of the authentication cycle. Shows the user a qrcode of auth url and code that needs to be entered in the auth page. User can cancel the process by clicking the cancel button. Args: auth_handle (int): An integer handle that should be passed to cancel authentication """ dialog = DeviceAuthFlowDialog(params) self._pending_results[params.server] = (auth_handle, dialog) dialog.set_cancel_clicked_fn(partial(self.cancel_auth, auth_handle, params.server)) def end_auth_flow(self, auth_handle: int): """Called at the end of the authentication cycle; hides the app dialog""" # find server from auth handle server = None for server_name, (handle, _) in self._pending_results.items(): if handle == auth_handle: server = server_name break if not server: return _, dialog = self._pending_results.pop(server) if dialog: dialog.hide() dialog = None def cancel_auth(self, auth_handle: int, server: str, dialog: DeviceAuthFlowDialog): """ This callback is attached to the dialog's cancel button. It cancels the authentication process. Args: auth_handle (int): An integer handle that should be passed to cancel authentication server (str): The server url that the auth handle is binding to """ if dialog: dialog.hide() dialog = None if server in self._pending_results: self._pending_results.pop(server) # Cancel the auth flow omni.client.authentication_cancel(auth_handle) def _connection_status_changed(self, server: str, status: omni.client.ConnectionStatus) -> None: """Collect signed in server's service information based upon server status changed.""" # need to strip off the omniverse:// here from the server if server.startswith("omniverse://"): server = server[12:] if server not in self._pending_results: return if status == omni.client.ConnectionStatus.CONNECTED: _, dialog = self._pending_results.pop(server) if dialog: dialog.hide() dialog = None def connect_with_callback(self, name: str = None, url: str = None, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Unless specified, prompts for server name and Url and proceeds to connect to it. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ def on_connect_server(on_success_fn: Callable, on_failed_fn: Callable, dialog: ConnectorDialog, name: str = None, url: str = None, show_waiting: bool = True): if show_waiting: dialog.show_waiting() if not name: name = dialog.get_value("name") if not url: url = dialog.get_value("url") # Give dialog ownership of the task so that it can cancel at will. asyncio.ensure_future(dialog.run_cancellable_task( self.connect_server_async(name, url, on_success_fn, on_failed_fn, dialog=dialog))) def on_cancel(dialog): dialog.cancel_task() dialog.hide() # OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly self._dialog = ConnectorDialog() if url: # If server is explicitly specified, then proceed to connect rather than wait for user input. on_connect_server(on_success_fn, on_failed_fn, self._dialog, name=name, url=url) return self._dialog.show(name=name, url=url) self._dialog.set_okay_clicked_fn(partial(on_connect_server, on_success_fn, on_failed_fn)) self._dialog.set_cancel_clicked_fn(on_cancel) async def connect_server_async(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None, retry: bool = False, dialog: ConnectorDialog = None): """ Connects to the named server. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) retry (bool): True if re-trying for second time. dialog (ConnectorDialog): A dialog instance to re-use from parent operation. """ if not url: carb.log_warn(f"Error connecting server, missing Url.") return elif not url.startswith("omniverse://"): url = f"omniverse://{url}" if not name: # If no name specified, then use name of child directory name = list(filter(None, url.split("/")))[-1] result, stats = None, None try: # This stat triggers the start of the authentication flow result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: if dialog: dialog.hide() if on_success_fn: on_success_fn(name, url) elif result == omni.client.Result.ERROR_CONNECTION and not retry: # Note: Strangely, omni.client returns error if the user has previously connected or disconnected from # this server. In this case, only a reconnect will succeed. omni.client.reconnect(url) await self.connect_server_async( name, url, on_success_fn=on_success_fn, on_failed_fn=on_failed_fn, retry=True, dialog=dialog) else: msg = f"Unable to connect server '{url}'. Please check your internet connection then try again." if not dialog: dialog = ConnectorDialog() dialog.show_alert(msg, AlertPane.Warn) if on_failed_fn: on_failed_fn(name, url) async def reconnect_server_async(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Re-connects to the named server. Args: url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if not url: carb.log_warn(f"Error reconnecting server, missing Url.") return name = list(filter(None, url.split("/")))[-1] # Do the reconnect omni.client.reconnect(url) result, stats = None, None try: result, stats = await omni.client.stat_async(url) except asyncio.CancelledError: # If this task is cancelled, then sign out completely in order to clear the auth process omni.client.sign_out(url) carb.log_warn(f"Cancelled attempted connection to '{url}'.") return if result == omni.client.Result.OK: if on_success_fn: on_success_fn(name, url) else: if on_failed_fn: on_failed_fn(name, url) def destroy(self): """Destructor.""" if self._pending_results: self._pending_results.clear() self._conn_status_sub = None # Cleanup temp img files created for qrcode import os if os.path.exists(DeviceAuthFlowDialog.TEMP_DIR): try: import shutil shutil.rmtree(DeviceAuthFlowDialog.TEMP_DIR) except OSError as e: carb.log_warn( f"Failed to clean up temp directory {DeviceAuthFlowDialog.TEMP_DIR}, error encountered: {str(e)}")
9,463
Python
40.69163
178
0.609426
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.settings import omni.ext import omni.kit.app import omni.client import asyncio from typing import Callable from functools import partial from .connector import NucleusConnector from .device_auth import DeviceAuthConnector from . import NUCLEUS_CONNECTION_SUCCEEDED_EVENT g_singleton = None # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class NucleusConnectorExtension(omni.ext.IExt): """Helper extension for connecting to Nucleus servers""" def __init__(self): super().__init__() self._connector = None def on_startup(self, ext_id): # Save away this instance as singleton global g_singleton g_singleton = self # OM-98449: Register device auth flow callback if device auth flow is turned on in settings self._device_auth_sub = None settings = carb.settings.get_settings() device_auth = settings.get_as_bool("exts/omni.kit.widget.nucleus_connector/device_auth_flow") if device_auth: # pragma: no cover self._connector = DeviceAuthConnector() self._device_auth_sub = omni.client.register_device_flow_auth_callback(self._on_device_auth) else: self._connector = NucleusConnector() # Set the callback to invoke when authentication requires opening a web browser to complete sign-in. omni.client.set_authentication_message_box_callback(self._on_authenticate) def _on_device_auth(self, auth_handle: int, params: omni.client.AuthDeviceFlowParams): """ This callback is invoked when authentication for device auth flow, instead of auth in the web browser. Args: auth_handle (int): The auth handle that could be used for canceling. params (omni.client.AuthDeviceFlowParams): An object containing info to display to user to complete the auth. if it is None, it means the auth attempt is finished. """ if self._connector: if not params: # Auth is done, either succeeded or failed, result needed to be determined from status callback; # Here we just close out the dialog. self._connector.end_auth_flow(auth_handle) return self._connector.start_auth_flow(auth_handle, params) def _on_authenticate(self, show_alert: bool, host_name: str, auth_handle: int): """ This callback is invoked when the application should show a dialog box letting the user know that a browser window has opened and to complete signing in using the web browser. Args: show_alert (bool): True means to start the authentication cycle and False means to end it host_name (str): The server host name that the authentication is for auth_handle (int): An integer handle that should be passed to cancel authentication """ if self._connector: if show_alert: self._connector.start_auth_flow(host_name, auth_handle) else: self._connector.end_auth_flow(auth_handle) def _on_connect_succeeded(self, callback: Callable, name: str, url: str): """Called when connection is made successfully; invokes the given callback""" # Emit event on successful connection event_stream = omni.kit.app.get_app().get_message_bus_event_stream() if event_stream: event_stream.push(NUCLEUS_CONNECTION_SUCCEEDED_EVENT, payload={"url": url}) if callback: callback(name, url) def _on_connect_failed(self, callback: Callable, name: str, url: str): """Called when connection fails; invokes the given callback""" if callback: callback(name, url) def connect_with_dialog(self, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Prompts for server name and Url and proceeds to connect to it. Args: on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if self._connector: self._connector.connect_with_callback( on_success_fn=partial(self._on_connect_succeeded, on_success_fn), on_failed_fn=partial(self._on_connect_failed, on_failed_fn)) def connect(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Connects to the named server. Args: name (str): Name of server url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str) """ if self._connector: self._connector.connect_with_callback(name=name, url=url, on_success_fn=partial(self._on_connect_succeeded, on_success_fn), on_failed_fn=partial(self._on_connect_failed, on_failed_fn)) def reconnect(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None): """ Reconnects to the named server. Args: url (str): Url of server on_success_fn (Callable): Invoked when successful, on_success_fn(url: str) on_faild_fn (Callable): Invoked when failed, on_faild_fn(url: str) """ if self._connector: asyncio.ensure_future(self._connector.reconnect_server_async( url, partial(self._on_connect_succeeded, on_success_fn), partial(self._on_connect_failed, on_failed_fn))) def disconnect(self, url: str): """ Disconnects from the server. Args: url (str): Url of server """ omni.client.sign_out(url) def on_shutdown(self): # Clears the auth callback omni.client.set_authentication_message_box_callback(None) # OM-98449: Clears device auth flow connector and callback self._device_auth_sub = None # Clean up the connector if self._connector: self._connector.destroy() self._connector = None global g_singleton g_singleton = None def get_instance(): return g_singleton
6,993
Python
40.141176
142
0.648649
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/__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. # import carb.events NUCLEUS_CONNECTION_SUCCEEDED_EVENT: int = carb.events.type_from_string("omni.kit.widget.nucleus_connector.CONNECTION_SUCCEEDED") from .extension import NucleusConnectorExtension, get_instance def get_nucleus_connector() -> NucleusConnectorExtension: """Returns :class:`NucleusConnectorExtension` interface""" return get_instance()
795
Python
40.894735
128
0.801258
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/test_helper.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 asyncio from typing import Optional, Union import omni.kit.app from omni.kit import ui_test from .ui import ConnectorDialog, DeviceAuthFlowDialog from . import get_nucleus_connector from .connector import NucleusConnector from .device_auth import DeviceAuthConnector class NucleusConnectorTestHelper: # NOTE Since the file dialog is a singleton, use an async lock to ensure mutex access in unit tests. # During run-time, this is not a issue because the dialog is effectively modal. __async_lock = asyncio.Lock() async def __aenter__(self): await self.__async_lock.acquire() return self async def __aexit__(self, *args): self.__async_lock.release() def get_connector_dialog(self, url: str = None) -> Optional[Union[ConnectorDialog, DeviceAuthFlowDialog]]: ext = get_nucleus_connector() if ext and ext._connector: if isinstance(ext._connector, NucleusConnector) or url is None: return ext._connector._dialog if isinstance(ext._connector, DeviceAuthConnector) and url: return ext._connector._pending_results.get(url, (None, None))[1] return None # pragma: no cover async def wait_for_popup(self, timeout: int = 100, url: str = None): dialog = self.get_connector_dialog(url=url) if dialog: for _ in range(timeout): if dialog.visible: return await omni.kit.app.get_app().next_update_async() raise Exception("Error: The connector dialog never opened.") async def wait_for_close(self, timeout: int = 100, url: str = None): dialog = self.get_connector_dialog(url=url) # OM-76995: Since we are creating the dialog on demand, it is considered ok if the dialog doesn't exist if dialog: for _ in range(timeout): if not dialog.visible: return await omni.kit.app.get_app().next_update_async() raise Exception("Error: The connector dialog never closed.") # pragma: no cover async def click_apply_async(self, name: str = None, url: str = None): """Helper function to click the apply button""" dialog = self.get_connector_dialog() if dialog: dialog.set_value('name', name) dialog.set_value('url', url) ok_button = ui_test.find(f"{dialog._window.title}//Frame/**/Button[0]") await ok_button.click() await ui_test.human_delay() async def click_cancel_async(self, url: str = None): """Helper function to click the cancel button""" dialog = self.get_connector_dialog(url=url) if dialog: cancel_button = ui_test.find(f"{dialog._window.title}//Frame/**/Button[1]") await cancel_button.click() await ui_test.human_delay()
3,329
Python
42.246753
111
0.648243
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/ui.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 os import sys import tempfile import carb import carb.settings import omni.ui as ui import asyncio import omni.kit.app from omni.kit.async_engine import run_coroutine from typing import Coroutine, Any, Callable, Union from omni.kit.window.popup_dialog.dialog import PopupDialog from omni.kit.window.popup_dialog.form_dialog import FormDialog, FormWidget from .style import UI_STYLES, ICON_PATH class ConnectorDialog(PopupDialog): """The main connection dialog""" def __init__(self): super().__init__( width=400, title="Add Nucleus connection", ok_label="Ok", cancel_label="Cancel", modal=True ) self._form_widget = None self._progress_bar = None self._alert_pane = None self._task = None self._build_ui() def _build_ui(self): field_defs = [ FormDialog.FieldDef("url", "Omniverse:// ", ui.StringField, "", True), FormDialog.FieldDef("name", "Optional Name: ", ui.StringField, ""), ] with self._window.frame: with ui.VStack(style=UI_STYLES, style_type_name_override="Dialog"): # OM-81873: This is a temporary solution for the authentication dialog; add the form widget in a frame # so that it could be easily hidden/shown self._form_frame = ui.Frame() with self._form_frame: self._form_widget = FormWidget("Add a new connection with optional name.", field_defs) with ui.ZStack(): ui.Spacer(height=60) with ui.VStack(): ui.Spacer(height=8) self._progress_bar = LoopProgressBar(puck_size=40) ui.Spacer() # OM-86699: Fix issue with randomly resized connector dialog, specify ZStack width with window width # OM-98771: Substract padding from window width when specifying AlertPane width self._alert_pane = AlertPane(width=self._window.width - 24) self._build_ok_cancel_buttons() self.hide() self.set_cancel_clicked_fn(lambda _: self._on_cancel_fn()) def _on_cancel_fn(self): self.cancel_task() self.hide() def get_value(self, name: str) -> str: if self._form_widget: return self._form_widget.get_value(name) return None def set_value(self, name: str, value: str): if self._form_widget: field = self._form_widget.get_field(name) if field: field.model.set_value(value or '') def destroy(self): self.cancel_task() if self._form_widget: self._form_widget.destroy() self._form_widget = None if self._form_frame: self._form_frame = None self._progress_bar = None if self._alert_pane: self._alert_pane.destroy() self._alert_pane = None super().destroy() def __del__(self): self.destroy() async def run_cancellable_task(self, task: Coroutine) -> Any: """Manages running and cancelling the given task""" if self._task: self.cancel_task() self._task = asyncio.create_task(task) try: return await self._task except asyncio.CancelledError: carb.log_info(f"Cancelling task ... {self._task}") raise except Exception as e: raise finally: self._task = None def cancel_task(self): """Cancels the managed task""" if self._task is not None: self._task.cancel() self._task = None @property def frame(self): return self._window.frame @property def visible(self) -> bool: if self._window: return self._window.visible return False def show(self, name: str = None, url: str = None): """Shows the dialog after resetting to a default state""" broken_url = omni.client.break_url(url or '') host = broken_url.host if broken_url.scheme == 'omniverse' else None self.set_value('url', host) self.set_value('name', name) self._progress_bar.hide() self._alert_pane.hide() self._okay_button.enabled = True self._cancel_button.enabled = True self._okay_button.visible = True self._form_frame.visible = True self._window.visible = True # focus fields on show self._form_widget.focus() def hide(self): self._window.visible = False # reset window title on hide; authentication mode might have reset the window title. self._window.title = self._title def show_waiting(self): if self._alert_pane: self._alert_pane.hide() if self._progress_bar: self._progress_bar.show() # Disable apply button self._okay_button.enabled = False def show_alert(self, msg: str = "", alert_type: int = 0): # hide form widget and OK button self._okay_button.visible = False self._form_frame.visible = False if self._alert_pane: self._alert_pane.show(msg, alert_type=alert_type) if self._progress_bar: self._progress_bar.hide() # Disable apply button self._okay_button.enabled = False self._window.visible = True def show_authenticate(self, name: str, url: str): """Shows the dialog for authentication, when the name and url is already given.""" # hide form widget and OK button self._okay_button.visible = False self._form_frame.visible = False # show login info broken_url = omni.client.break_url(url or '') host = broken_url.host if broken_url.scheme == 'omniverse' else None if self._alert_pane: msg = f"Connecting to ({host}) requires login authentication. Please login from your web browser." self._alert_pane.show(msg, alert_type=AlertPane.Info) # update window title self._window.title = "Login Required" self._window.visible = True class LoopProgressBar: """A looping progress bar""" def __init__(self, puck_size: int = 20, period: float = 120): self._puck_size = puck_size self._period = period self._widget = None self._spacer_left = None self._spacer_right = None self._loop_task = None self._build_ui() def _build_ui(self): self._widget = ui.Frame(visible=False) with self._widget: with ui.ZStack(height=20): ui.Rectangle(style_type_name_override="ProgressBar") with ui.HStack(): self._spacer_left = ui.Spacer(width=ui.Fraction(0)) ui.Rectangle(width=self._puck_size, style_type_name_override="ProgressBar.Puck") self._spacer_right = ui.Spacer(width=ui.Fraction(1)) async def _inf_loop(self): counter = 0 while True: await omni.kit.app.get_app().next_update_async() width = float(counter % self._period) / self._period # Ping-pong width = width * 2 if width > 1.0: width = 2.0 - width self._spacer_left.width = ui.Fraction(width) self._spacer_right.width = ui.Fraction(1.0 - width) counter += 1 def __del__(self): self.hide() self._widget = None def show(self): if self._widget: self._loop_task = asyncio.ensure_future(self._inf_loop()) self._widget.visible = True def hide(self): if self._widget: if self._loop_task is not None: self._loop_task.cancel() self._loop_task = None self._widget.visible = False class AlertPane: """An alert pane for the app dialog.""" Info = 0 Warn = 1 def __init__(self, width: int = 400): self._widget: ui.Frame = None self._frame: ui.Frame = None self._icon_frame: ui.Frame = None self._label: ui.Label = None self._build_ui(width=width) def destroy(self): self._label = None self._frame = None self._widget = None def _build_ui(self, width: int = 400): self._widget = ui.Frame(visible=False, height=0) with self._widget: with ui.ZStack(width=width, style=UI_STYLES): self._frame = ui.Frame() with ui.HStack(spacing=4, style_type_name_override="AlertPane.Content"): self._icon_frame = ui.Frame() self._label = ui.Label("", height=20, word_wrap=True, style_type_name_override="Label") def show(self, msg: str = "", alert_type: int = 0): if self._widget: with self._frame: style_name = "warn" if alert_type == AlertPane.Warn else "info" ui.Rectangle(style_type_name_override="AlertPane", name=style_name) with self._icon_frame: icon = f"{ICON_PATH}/warn.svg" if alert_type == AlertPane.Warn else f"{ICON_PATH}/info.svg" ui.ImageWithProvider(icon, width=16, height=16, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style_type_name_override="Image") if self._label: self._label.text = msg self._widget.visible = True def hide(self): if self._widget: self._widget.visible = False # OM-98450: Add UI for device auth flow class DeviceAuthFlowDialog(PopupDialog): TEMP_DIR = os.path.join(tempfile.gettempdir(), "kit_device_auth_qrcode/") """The main authentication dialog for device auth flow.""" def __init__(self, params: omni.client.AuthDeviceFlowParams): super().__init__( width=400, title="Device Authentication", ok_label="Retry", cancel_label="Cancel", modal=True ) self._image = None self._time_remaining = params.expiration self._server = params.server self._expiration_frame = None self._build_ui(params) self._count_down_task = run_coroutine(self._count_expiration_async()) self._generate_qrcode(params.url) @property def visible(self) -> bool: if self._window: return self._window.visible return False def _build_ui(self, params: omni.client.AuthDeviceFlowParams): with self._window.frame: with ui.VStack(style=UI_STYLES, style_type_name_override="Dialog"): ui.Label(f"Connecting to {params.server}", alignment=ui.Alignment.CENTER) with ui.HStack(): ui.Spacer() self._image = ui.Image(width=128, height=128, style_type_name_override="QrCode") ui.Spacer() with ui.HStack(): ui.Label(f"Please go to ", width=0) # OM-102092: Change URL to be a string field so it is selectable and could be copied # TODO: Note that if the URL is too long, currently it could get clipped and will not display the # entire url; Solution could be: # 1) Have both a label and a string field, and when mouse pressed, switch to string field for # selection; which is a bit hacky, since the string field height need to be dynamically adjusted # 2) have omni.ui.Label support selection of text ui.StringField(ui.SimpleStringModel(params.url), style=UI_STYLES, style_type_name_override="StringField.Url", read_only=True) ui.Label("or scan the qrcode above, and enter the code below:") ui.Spacer(height=2) ui.Label(params.code, style_type_name_override="Label.Code") ui.Spacer(height=2) self._expiration_frame = ui.Frame() with self._expiration_frame: with ui.HStack(spacing=4): ui.Spacer() ui.Label("Code expires in", width=0) self._time_remaining_label = ui.Label( str(self._time_remaining), style_type_name_override="Label.TimeRemaining", width=0) ui.Label("seconds", width=0) ui.Spacer() ui.Spacer(height=10) self._build_ok_cancel_buttons() ui.Spacer(height=30) self.set_cancel_clicked_fn(lambda _: self._on_cancel_fn()) self.set_okay_clicked_fn(lambda _: self._on_retry()) self._okay_button.visible = False def _on_cancel_fn(self): self._count_down_task.cancel() self.hide() def _on_retry(self): self._on_cancel() if not self._server.startswith("omniverse://"): server = "omniverse://" + self._server else: server = self._server omni.client.reconnect(server) def destroy(self): if self._count_down_task: self._count_down_task.cancel() self._count_down_task = None super().destroy() def __del__(self): self.destroy() def hide(self): self._window.visible = False # reset window title on hide; authentication mode might have reset the window title. self._window.title = self._title def show_expired(self): """Show the user when the code has expired.""" with self._expiration_frame: ui.Label("Code has expired. Please try again.", style_type_name_override="Label.Expired") self._okay_button.visible = True def _generate_qrcode(self, url: str): # pragma: no cover """Generates a qrcode from the given url.""" if not os.path.exists(self.TEMP_DIR): os.mkdir(self.TEMP_DIR) # Swap out the : && / since the url we are dealing with are usually something like: "https://a.b.c/x/y", # replacing these special characters with "_" here so we don't end up violating OS naming conventions img_name = url.replace("/", "_").replace(":", "_") img_path = os.path.join(self.TEMP_DIR, f"qr_{img_name}.png") # we could skip generating the qrcode for the same url, since the image would be the same with the same encoding if not os.path.exists(img_path): # try to use qrcode module to generate the image try: import qrcode except ImportError: carb.log_error("Package qrcode not installed. Skipping qr code generation.") return img = qrcode.make(url) img.save(img_path) # update image source url self._image.source_url = img_path async def _count_expiration_async(self): """Counts down the remaining time in seconds before expiration.""" while(self._time_remaining > 0): await asyncio.sleep(1) self._time_remaining -= 1 self._time_remaining_label.text = str(self._time_remaining) self.show_expired()
15,818
Python
37.026442
120
0.573145
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/__init__.py
## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .test_connector import * from .test_device_auth import * from .test_ui import *
525
Python
46.818178
77
0.786667
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_ui.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 asyncio from unittest.mock import patch, Mock import carb.settings import omni.kit.test import omni.ui as ui import omni.kit.ui_test as ui_test from ..ui import ConnectorDialog, DeviceAuthFlowDialog class TestConnectorDialog(omni.kit.test.AsyncTestCase): """Tests for dialog base class""" async def setUp(self): pass async def tearDown(self): pass async def _mock_task_with_results(self): return 1, 2, 3 async def _mock_cancellable_task(self): """After a short delay, hide the dialog. This should result in cancelling this long-lasting task.""" while True: try: await asyncio.sleep(1) except asyncio.CancelledError: return async def test_dialog_resturns_task_results(self): """Test that the dialog returns the results from it child task""" dialog = ConnectorDialog() dialog.show() with dialog.frame: ui.Label("Test label", height=20) results = await dialog.run_cancellable_task(self._mock_task_with_results()) # Confirm returned result self.assertEqual(results, (1, 2, 3)) dialog.destroy() async def test_dialog_cancels_task(self): """Test that hiding the dialog window cancels child task""" dialog = ConnectorDialog() # Hide the dialog a short time later. loop = asyncio.get_event_loop() loop.call_later(2, dialog.cancel_task) dialog.show() with dialog.frame: ui.Label("Test label") await dialog.run_cancellable_task(self._mock_cancellable_task()) # Confirm that child task was cancelled self.assertEqual(dialog._task, None) dialog.destroy() class TestDeviceAuthFlowDialog(omni.kit.test.AsyncTestCase): """Tests for DeviceAuthFlowDialog.""" # omni.client.AuthDeviceFlowParams can't be initiated directly in python since it didn't define constructors; so # for testing had to fake an object with those attrs. class _MockParams(): def __init__(self, server, url, expiration, code) -> None: self.server = server self.url = url self.expiration = expiration self.code = code async def setUp(self): pass async def tearDown(self): pass @staticmethod def _mock_params(server, url, expiration, code): return TestDeviceAuthFlowDialog._MockParams(server, url, expiration, code) async def test_display_and_count_down(self): """Test that the dialog displays correctly and counts down correctly.""" # mock qrcode generation so we don't actually generate that with patch.object(DeviceAuthFlowDialog, "_generate_qrcode") as mock_gen_qrcode: dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 100, "FOOBAR42")) self.assertEqual(100, dialog._time_remaining) # test count down await asyncio.sleep(1.5) self.assertGreaterEqual(99, dialog._time_remaining) # test that qrcode generation is triggered mock_gen_qrcode.assert_called_once_with("https://dummy/auth/url") dialog.hide() dialog.destroy() async def test_cancel(self): """Test that the dialog cancel cancels the authentication and closes.""" # mock qrcode generation so we don't actually generate that with patch.object(DeviceAuthFlowDialog, "_generate_qrcode"): dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 100, "FOOBAR42")) self.assertTrue(dialog.window.visible) self.assertIsNotNone(dialog._count_down_task) await ui_test.human_delay(5) button = ui_test.find_all("Device Authentication//Frame/**/Button[*]")[-1] self.assertIsNotNone(button) self.assertEqual(button.widget.text, "Cancel") await button.click() await ui_test.human_delay(5) # check that count down is cancelled and window is hidden self.assertTrue(dialog._count_down_task.cancelled()) self.assertFalse(dialog.window.visible) async def test_dialog_expiration_and_retry(self): """Test that the dialog correctly counts down and expires, and retry works.""" # mock qrcode generation so we don't actually generate that with patch.object(DeviceAuthFlowDialog, "_generate_qrcode"), patch("omni.client.reconnect") as mock_reconnect: dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 1, "FOOBAR42")) await ui_test.human_delay(5) buttons = ui_test.find_all("Device Authentication//Frame/**/Button[*]") retry, cancel = buttons[0], buttons[1] self.assertFalse(retry.widget.visible) self.assertTrue(cancel.widget.visible) # make sure we meet expiration await asyncio.sleep(1.5) # retry button should be enabled now self.assertTrue(retry.widget.visible) self.assertTrue(cancel.widget.visible) # click retry should cancel and hide the window, and issue a new reconnect await retry.click() await ui_test.human_delay(10) mock_reconnect.assert_called_once_with("omniverse://dummy") self.assertFalse(dialog.window.visible)
5,927
Python
39.054054
118
0.650076
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_device_auth.py
## Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import asyncio from unittest.mock import patch, Mock import carb.settings import omni.kit.test import omni.client import omni.kit.ui_test as ui_test from .. import get_nucleus_connector from ..test_helper import NucleusConnectorTestHelper from ..device_auth import DeviceAuthConnector from ..ui import DeviceAuthFlowDialog class TestAddServerWithValidationDeviceAuth(omni.kit.test.AsyncTestCase): """Testing FilePickerView.add_server_with_validation""" # omni.client.AuthDeviceFlowParams can't be initiated directly in python since it didn't define constructors; so # for testing had to fake an object with those attrs. class _MockParams(): def __init__(self, server, url, expiration, code) -> None: self.server = server self.url = url self.expiration = expiration self.code = code async def setUp(self): self._test_name = "ov-test" self._test_url = "omniverse://ov-test" self._expected_stat_results = [omni.client.Result.OK, omni.client.Result.OK] self._stat_latency = 1 self._iter = 0 # patch qrcode generation so we don't acutally install qrcode module and generates the image patch_qrcode_gen = patch.object(DeviceAuthFlowDialog, "_generate_qrcode") patch_qrcode_gen.start() self.addCleanup(patch_qrcode_gen.stop) async def tearDown(self): pass async def _mock_stat_async_impl(self, url: str): # During a stat, omni.client triggers the device auth callback. # The callback was previously set via the subscription method: omni.client.register_device_flow_auth_callback. ext = get_nucleus_connector() if self._iter == 0: if ext: mock_param = TestAddServerWithValidationDeviceAuth._MockParams(url, "https://dummy/auth", 10, "FOOBAR42") ext._on_device_auth(1, mock_param) result = self._expected_stat_results[self._iter] self._iter += 1 # Simulates the latency due to user signing in through device auth await asyncio.sleep(self._stat_latency) ext._on_device_auth(1, None) return result, {} def _mock_auth_cancel_impl(self, auth_handle: int): # A cancellation event also executes the device auth callback, but with the params set to None. ext = get_nucleus_connector() if ext: ext._on_device_auth(auth_handle, None) async def test_connect_with_dialog_succeeds(self): """Testing that connecting to server through dialog succeeds""" under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) # Connector dialog will show up first prompting for user input await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close() # The device auth flow dialog will show up displaying the qrcode etc. await connector_helper.wait_for_popup(url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # Confirm on_success callback called await ui_test.human_delay(10) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_given_url_succeeds(self): under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await ui_test.human_delay(10) # Only the device auth dialog will show up await connector_helper.wait_for_popup(url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # Confirm on_success callback called await ui_test.human_delay(10) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_then_reconnect_succeeds(self): """Testing that when connect fails the first time, retries with a reconnect""" under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() # In this case, the first stat will result in an error, but will succeed after a reconnect self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await ui_test.human_delay(10) await connector_helper.wait_for_popup(url=self._test_url) #await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # auth dialog is closed during second stat_async, need wait more time for connect completed await asyncio.sleep(self._stat_latency) # Confirm reconnect attempted and connection succeeded mock_reconnect.assert_called_once_with(self._test_url) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_url_cancelled(self): """Testing that user is able to cancel out of connection flow""" under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.authentication_cancel", side_effect=self._mock_auth_cancel_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await ui_test.human_delay(10) # Only the device auth dialog will show up await connector_helper.wait_for_popup(url=self._test_url) # Click cancel after some time await asyncio.sleep(.5*self._stat_latency) await connector_helper.click_cancel_async(url=self._test_url) await connector_helper.wait_for_close(timeout=1000, url=self._test_url) # Confirm neither callbacks invoked mock_success_fn.assert_not_called() mock_failed_fn.assert_not_called() # make sure we finish the mock stat return await asyncio.sleep(0.5* self._stat_latency) async def test_reconnect_with_given_url_succeeds(self): under_test = get_nucleus_connector() under_test._connector = DeviceAuthConnector() self._expected_stat_results = [omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.reconnect(self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) for _ in range(1000): await omni.kit.app.get_app().next_update_async() # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() mock_reconnect.assert_called_once_with(self._test_url)
9,286
Python
53.629411
127
0.645919
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_connector.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 asyncio import omni.kit.test import omni.client from unittest.mock import patch, Mock from .. import get_nucleus_connector from ..test_helper import NucleusConnectorTestHelper class TestAddServerWithValidation(omni.kit.test.AsyncTestCase): """Testing FilePickerView.add_server_with_validation""" async def setUp(self): self._test_name = "ov-test" self._test_url = "omniverse://ov-test" self._expected_stat_results = [omni.client.Result.OK, omni.client.Result.OK] self._stat_latency = 1 self._iter = 0 async def tearDown(self): pass async def _mock_stat_async_impl(self, url: str): # During a stat, omni.client triggers the browser sign in flow by executing the _on_authenticate callback. # The callback was previously set via the subscription method: omni.client.set_authentication_message_box_callback. if self._iter == 0: ext = get_nucleus_connector() if ext: ext._on_authenticate(True, url, 1) result = self._expected_stat_results[self._iter] self._iter += 1 # Simulates the latency due to user signing in through brower await asyncio.sleep(self._stat_latency) return result, {} def _mock_auth_cancel_impl(self, auth_handle: int): # A cancellation event also executes the _on_authenticate callback, but with the first input set to False. ext = get_nucleus_connector() if ext: ext._on_authenticate(False, None, auth_handle) async def test_connect_with_dialog_succeeds(self): """Testing that connecting to server through dialog succeeds""" under_test = get_nucleus_connector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close(timeout=1000) # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_given_url_succeeds(self): under_test = get_nucleus_connector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() # Note that it's not necessary to click the apply button; the dialog automatically proceeds to make the # connection, using the given server name and url. await connector_helper.wait_for_close(timeout=1000) # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_with_dialog_cancelled(self): """Testing that user is able to cancel out of connection flow""" under_test = get_nucleus_connector() async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.authentication_cancel", side_effect=self._mock_auth_cancel_impl): mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) # Click cancel after some time await asyncio.sleep(.5*self._stat_latency) await connector_helper.click_cancel_async() await connector_helper.wait_for_close(timeout=1000) # Confirm neither callbacks invoked mock_success_fn.assert_not_called() mock_failed_fn.assert_not_called() async def test_connect_then_reconnect_succeeds(self): """Testing that when connect fails the first time, retries with a reconnect""" under_test = get_nucleus_connector() # In this case, the first stat will result in an error, but will succeed after a reconnect self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) await connector_helper.wait_for_close(timeout=1000) # Confirm reconnect attempted and connection succeeded mock_reconnect.assert_called_once_with(self._test_url) mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() async def test_connect_and_reconnect_fails(self): """Testing that both the connect and reconnect attempts fail""" under_test = get_nucleus_connector() # In this case, the first stat will result in an error, but will succeed after a reconnect self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.ERROR_CONNECTION] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) await connector_helper.wait_for_popup() await connector_helper.click_apply_async(name=self._test_name, url=self._test_url) # Cancel to close the dialog after some time await asyncio.sleep(2.5*self._stat_latency) await connector_helper.click_cancel_async() await connector_helper.wait_for_close(timeout=1000) # Confirm reconnect attempted and connection succeeded mock_reconnect.assert_called_once_with(self._test_url) mock_failed_fn.assert_called_once_with(self._test_name, self._test_url) mock_success_fn.assert_not_called() async def test_reconnect_with_given_url_succeeds(self): under_test = get_nucleus_connector() self._expected_stat_results = [omni.client.Result.OK] async with NucleusConnectorTestHelper() as connector_helper: with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\ patch("omni.client.reconnect") as mock_reconnect: mock_success_fn, mock_failed_fn = Mock(), Mock() under_test.reconnect(self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn) for _ in range(100): dialog = connector_helper.get_connector_dialog() if dialog and dialog.visible: break await omni.kit.app.get_app().next_update_async() await connector_helper.wait_for_close(timeout=1000) # Confirm on_success callback called mock_success_fn.assert_called_once_with(self._test_name, self._test_url) mock_failed_fn.assert_not_called() mock_reconnect.assert_called_once_with(self._test_url)
8,946
Python
55.626582
127
0.645093
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.3] - 2023-02-17 ### Added - Adds authentication mode to ConnectorDialog, shows a simplified UI with only login info and cancel button - Connecting to named server/reconnect/auth will now use authentication mode of ConnectorDialog ## [1.0.2] - 2022-12-08 ### Added - No longer cancels unaccounted authentication - Emits event upon successful connection ## [1.0.1] - 2022-09-23 ### Added - Fixes hang on browser login page. ## [1.0.0] - 2022-07-20 ### Added - Initial commit to master.
590
Markdown
25.863635
107
0.718644
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/docs/index.rst
omni.kit.widget.nucleus_connector ################################# A helper extension for connecting to the Nucleus server. .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.widget.nucleus_connector :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: .. autoclass:: NucleusConnectorExtension :members:
387
reStructuredText
18.399999
56
0.633075
omniverse-code/kit/exts/omni.graph.expression/PACKAGE-LICENSES/omni.graph.expression-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.graph.expression/config/extension.toml
[package] title = "OmniGraph Expression Node" version = "1.1.2" category = "Graph" keywords = ["omnigraph", "expression"] # Main module for the Python interface [[python.module]] name = "omni.graph.expression" # Other extensions that need to load in order for this one to work [dependencies] "omni.graph" = {} "omni.graph.tools" = {} "omni.kit.pipapi" = {} # numpy might be used by the expressions [python.pipapi] requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231 [[native.plugin]] path = "bin/*.plugin" recursive = false [[test]] waiver = "Extension will be deprecated soon" [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph refs until that workflow is moved ] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
798
TOML
21.194444
108
0.689223
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/__init__.py
"""There is no public API to this module.""" __all__ = [] from ._impl.extension import _PublicExtension # noqa: F401 import omni.graph.tools as ogt ogt.DeprecatedImport("Use the omni.graph.scriptnode extension instead")
223
Python
26.999997
71
0.735426
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/_impl/extension.py
"""Support required by the Carbonite extension loader.""" import omni.ext # binding for C++ plugin interface from ..bindings._omni_graph_expression import acquire_interface as _acquire_interface # noqa: PLE0402 from ..bindings._omni_graph_expression import release_interface as _release_interface # noqa: PLE0402 # python scripted node from ..nodes.OgnExpression import OgnExpression as _OgnExpression # noqa: PLE0402 class _PublicExtension(omni.ext.IExt): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__interface = None def on_startup(self): self.__interface = _acquire_interface() def on_shutdown(self): if self.__interface is not None: _release_interface(self.__interface) self.__interface = None _OgnExpression.on_shutdown()
845
Python
32.839999
102
0.680473
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/nodes/OgnExpression.py
import asteval import carb import carb.settings import numpy as np import omni.graph.core as cg import omni.kit.pipapi import omni.stageupdate from pxr import Sdf __IMPORT_WHITELIST__ = ["torch", "carb"] def do_import(module, as_name=""): if not as_name: as_name = module as_name = as_name[as_name.rfind(".") + 1 :] if not module.startswith("omni."): exec( # noqa: PLW0122 f""" try: globals()["{as_name}"] = __import__("{module}") except ImportError: print("{module} not found. attempting to install...") omni.kit.pipapi.install("{module}") globals()["{as_name}"] = __import__("{module}") """ ) return as_name, globals()[as_name] def filter_import_list(modules): out = [] for m in modules: if m not in __IMPORT_WHITELIST__: carb.log_warn(f"OgnExpression: import of {m} is not allowed") else: out.append(m) return out __expr_cache__ = {} __stage_subscription__ = None # dummy class for attribute placeholder class Attrs: def __init__(self): return class ExprCache: def __init__(self, node): global __stage_subscription__ self.node = node if not __stage_subscription__: stage_update = omni.stageupdate.get_stage_update_interface() __stage_subscription__ = stage_update.create_stage_update_node( "OgnExpression", None, OgnExpression.on_detach, None, None, None, OgnExpression.on_removed ) self.symTable = asteval.make_symbol_table(use_numpy=False, np=np) self.symTable["inputs"] = Attrs() # self.symTable["outputs"] = Attrs() self.eval = asteval.Interpreter(symtable=self.symTable) @staticmethod def get(node): pp = Sdf.Path(node.get_prim_path()) if pp not in __expr_cache__: return None return __expr_cache__[pp] @staticmethod def clear(prim): if prim in __expr_cache__: # print("clear cache",prim) c = __expr_cache__[prim] c._stage_subscription = None # noqa: PLW0212 del __expr_cache__[prim] @staticmethod def init(node): pp = Sdf.Path(node.get_prim_path()) cache = ExprCache(node) __expr_cache__[pp] = cache return cache class OgnExpression: """Implementation of the OmniGraph expression node""" @staticmethod def get_node_type(): return "Expression" @staticmethod def get_upstream_attr_or_self(attr): """Returns the list of attributes upstream from the given one, or itself if there is nothing upstream""" attributes_upstream = attr.get_upstream_connections() return attributes_upstream if attributes_upstream else [attr] @staticmethod def compute(context, node): # if not carb.settings.get_settings().get("/persistent/omnigraph/allowExprNodeExe"): # return True need_init = False _cache = ExprCache.get(node) if not _cache: # print("initCache", Sdf.Path(node.get_prim_path())) _cache = ExprCache.init(node) if node.get_attribute_exists("import"): # print("import", Sdf.Path(node.get_prim_path())) import_list = OgnExpression.get_upstream_attr_or_self(node.get_attribute("import")) import_list = [m.strip() for m in context.get_attr_value(import_list).split(",") if len(m.strip())] for m in import_list: try: as_name, module = do_import(m) _cache.symTable[as_name] = module except (ImportError, KeyError, NameError): carb.log_error("OgnExpression: failed importing " + m) continue need_init = True attr_names = [n.get_name() for n in node.get_attributes()] in_attr_names = [a for a in attr_names if a.startswith("inputs:")] for ia in in_attr_names: attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(ia)) setattr(_cache.symTable["inputs"], ia.split(":")[-1], context.get_attr_value(attr)) out_attrs = Attrs() _cache.symTable["outputs"] = out_attrs # for oa in out_attr_names: # attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(oa)) # setattr(_cache.symTable["outputs"], oa.split(":")[-1], context.get_attr_value(attr)) if need_init and node.get_attribute_exists("initExpr"): init_expr = OgnExpression.get_upstream_attr_or_self(node.get_attribute("initExpr")) init_expr = context.get_attr_value(init_expr) _cache.eval(init_expr) # exec(init_expr) expr = OgnExpression.get_upstream_attr_or_self(node.get_attribute("updateExpr")) expr = context.get_attr_value(expr) _cache.eval(expr) # exec(expr) # lazy update of output values cach_out_attrs_dict = out_attrs.__dict__ out_attr_names = [a for a in attr_names if a.startswith("outputs:")] for out_attr_name in out_attr_names: attr_short_name = out_attr_name[8:] # without "outputs:" prefix if attr_short_name in cach_out_attrs_dict: cache_out_attr_val = cach_out_attrs_dict[attr_short_name] attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(out_attr_name)) # print("!", out_attr_name, len(cache_out_attr_val), cache_out_attr_val[0]) context.set_attr_value(cache_out_attr_val, attr) return True @staticmethod def on_shutdown(): global __stage_subscription__ __stage_subscription__ = None @staticmethod def on_detach(): global __expr_cache__, __stage_subscription__ __expr_cache__ = {} __stage_subscription__ = None @staticmethod def on_removed(prim): ExprCache.clear(prim) cg.register_node_type(OgnExpression, 1)
6,066
Python
33.276836
115
0.587867
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.expression as oge from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphExpressionApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "nodes", "tests"] async def test_api(self): _check_module_api_consistency(oge, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(oge.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(oge, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212 _check_public_api_contents(oge.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
939
Python
48.473682
107
0.654952
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/tests/__init__.py
"""There is no public API to this module.""" __all__ = [] scan_for_test_modules = True """The presence of this object causes the test runner to automatically scan the directory for unit test cases"""
201
Python
32.666661
112
0.716418
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/PACKAGE-LICENSES/omni.kit.widget.searchable_combobox-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.4" #Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Searchable ComboBox" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "ui", "combobox", "search"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" category = "developer" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" description = "Searchable ComboBox Widget" readme = "docs/README.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} # Main module of the python interface [[python.module]] name = "omni.kit.widget.searchable_combobox" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.ui_test", "omni.kit.renderer.core", "omni.kit.renderer.capture", "omni.kit.mainwindow", ]
1,260
TOML
23.25
90
0.707937
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/combo_model.py
import omni.ui as ui import omni.kit.app class ComboBoxListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) # True when the item is visible self.filtered = True def prefilter(self, filter_name_text: str): if not filter_name_text: self.filtered = True else: self.filtered = filter_name_text in self.name_model.as_string.lower() def __repr__(self): return f'"{self.name_model.as_string}"' class ComboBoxListModel(ui.AbstractItemModel): _instance = None def __init__(self, item_list): super().__init__() self._children = [ComboBoxListItem(item) for item in item_list] global _instance _instance = self def clean(self): global _instance _instance = None def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: return [] return [c for c in self._children if c.filtered] def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_drag_mime_data(self, item): """Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere""" # As we don't do Drag and Drop to the operating system, we return the string. return item.name_model.as_string def get_item_value_model(self, item, column_id): return item.name_model def filter_by_text(self, filter_name_text: str): """Specify the filter string that is used to reduce the model""" for c in self._children: c.prefilter(filter_name_text.lower()) self._item_changed(None) def get_index_for_item(self, item_text: str): for index, item in enumerate(self._children): if item.name_model.get_value_as_string() == item_text: return index return -1 class ComboBoxListDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def __init__(self, flat=False): super().__init__() def clean(self): pass def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" pass def build_widget(self, model, item, column_id, level, expanded): ui.Label( model.get_item_value_model(item, column_id).as_string, skip_draw_when_clipped=True, elided_text=True, height=18, )
2,759
Python
29
111
0.608191
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/search_widget.py
import asyncio import omni.kit.app import omni.ui as ui from enum import IntFlag class SearchModel(ui.AbstractValueModel): def __init__(self, modified_fn): super().__init__() self._modified_fn = modified_fn self.__str = "" def is_in_string(self, string: str): if self.__str == "": return True return self.__str.upper() in string.upper() def set_value(self, value): self.__str = str(value) self._value_changed() if self._modified_fn: self._modified_fn(self.__str) def get_value_as_string(self): return self.__str class SearchWidget: def __init__(self, theme: str, icon_path: str, modified_fn: callable = None): self._search_model = SearchModel(modified_fn=modified_fn) if not icon_path: icon_path = ( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) if theme == "NvidiaDark": SEARCH_BODY_COLOR = 0xFF2D2D2D SEARCH_PLACEHOLDER = 0xFF666666 BUTTON_BACKGROUND_COLOR = 0xFF323434 COMBO_BACKGROUND_COLOR = 0xFF92929 GENERAL_BACKGROUND_COLOR = 0xFF24211F else: SEARCH_BODY_COLOR = 0xFF2D2D2D SEARCH_PLACEHOLDER = 0xFF666666 BUTTON_BACKGROUND_COLOR = 0xFF545454 COMBO_BACKGROUND_COLOR = 0xFF545454 GENERAL_BACKGROUND_COLOR = 0xFF545454 self._style = { # search_button "Button.Image::search_button": { "image_url": f"{icon_path}/search.svg", "background_color": SEARCH_BODY_COLOR, "margin": 0, }, "Button::search_button": {"margin": 0}, "Field::search_button": {"background_color": SEARCH_BODY_COLOR}, "Field::search_button:hovered": {"background_color": SEARCH_BODY_COLOR}, # search placeholder "Label::search_placeholder": {"color": SEARCH_PLACEHOLDER}, # remove button "Button.Image::remove": {"image_url": f"{icon_path}/remove.svg"}, "Button.Image::remove:hovered": {"image_url": f"{icon_path}/remove-hovered.svg"}, "Button::remove": {"background_color": SEARCH_BODY_COLOR, "margin": 0}, "Button::remove:hovered": {"background_color": SEARCH_BODY_COLOR, "margin": 0}, # remove button popup (different colors) "Button::remove_popup": {"background_color": GENERAL_BACKGROUND_COLOR, "margin": 0}, "Button::remove_popup:hovered": {"background_color": GENERAL_BACKGROUND_COLOR, "margin": 0}, "Button.Image::remove_popup": {"image_url": f"{icon_path}/remove.svg"}, "Button.Image::remove_popup:hovered": {"image_url": f"{icon_path}/remove-hovered.svg"}, # find button "Button::find": {"background_color": BUTTON_BACKGROUND_COLOR}, "Button.Image::find": {"image_url": f"{icon_path}/find.svg"}, # listbox button "Button.Image::listbox": {"image_url": f"{icon_path}/listbox.svg"}, "Button::listbox": {"background_color": COMBO_BACKGROUND_COLOR, "padding": 6, "margin": 0}, } def clean(self): self._field = None self._search_field = None self._search_clear = None self._update_fn = None def destroy(self): self._field = None self._search_field = None self._search_clear = None self._update_fn = None del self._search_model def update(self, string): self._placeholder.visible = bool(string == "") self._search_clear.enabled = not self._placeholder.visible def focus(self): async def focus(field): await omni.kit.app.get_app().next_update_async() field.focus_keyboard() asyncio.ensure_future(focus(self._field)) def build_ui(self, width, search_size): def clear_name(field): field.model.set_value("") field.focus_keyboard() with ui.HStack(width=0, height=0, style=self._style): ui.Button("", width=search_size, height=search_size, enabled=False, name="search_button") with ui.ZStack(width=0, height=0): with ui.HStack(width=0, height=0): field = ui.StringField( model=self._search_model, width=width - 46, height=search_size, name="search_button" ) self._search_clear = ui.Button( "", width=search_size, height=search_size, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, enabled=False, clicked_fn=lambda f=field: clear_name(f), name="remove", ) self._placeholder = ui.Label(" Search....", height=search_size, name="search_placeholder") self._field = field self.focus() def set_placeholder_text(self, msg: str): self._placeholder.text = f" {msg}...." enabled = bool(msg == "Search") self._field.enabled = enabled self._field.focus_keyboard(enabled) def set_text(self, new_text: str): changed = bool(self._search_field.model.get_value_as_string() != new_text) self._search_field.model.set_value(new_text) if changed and self._update_fn: self._update_fn(self._search_field.model) def get_text(self): return self._search_field.model.get_value_as_string() def build_ui_popup(self, search_size: float, default_value: str, popup_text: str, index: int, update_fn: callable): def clear_name(name_field): name_field.model.set_value(default_value) if update_fn: update_fn(name_field.model) self._update_fn = update_fn open_button = None name_field = None with omni.ui.VStack(height=0, spacing=0, style={"margin_width": 0}): with ui.HStack(style=self._style): name_field = ui.StringField(height=search_size, enabled=False) name_field.model.set_value(popup_text) ui.Button( "", width=20, height=20, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, clicked_fn=lambda f=name_field: clear_name(f), name="remove_popup", ) open_button = ui.Button("", width=20, height=20, image_width=8, name="listbox") self._search_field = name_field return name_field, open_button
6,818
Python
38.877193
119
0.552655
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/__init__.py
from .search_widget import SearchModel, SearchWidget from .combo_model import ComboBoxListItem, ComboBoxListModel, ComboBoxListDelegate from .combo_widget import ComboListBoxWidget, build_searchable_combo_widget
212
Python
52.249987
82
0.863208
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/combo_widget.py
import asyncio import carb.input import omni.kit.app import omni.appwindow import omni.ui as ui from typing import List from .combo_model import ComboBoxListModel, ComboBoxListDelegate from .search_widget import SearchWidget class ComboListBoxWidget: def __init__( self, search_widget: SearchWidget, item_list: list, theme: str, window_id: str = "SearchableComboBoxWindow", delegate: ui.AbstractItemDelegate = ComboBoxListDelegate(), ): icon_path = ( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) self._height = 32 self._theme = theme self.__parent = None self._window = None self.__frame = None self._placeholder_search_widget = search_widget self._search_widget = SearchWidget(theme=theme, icon_path=icon_path, modified_fn=self._search_updated) self._search_size = 22 self._window_id = window_id self._name_value_model = ComboBoxListModel(item_list) self._name_value_delegate = delegate if theme == "NvidiaDark": BACKGROUND_COLOR = 0xFF3D3B38 FIELD_TEXT_COLOR = 0xFFD5D5D5 FIELD_BORDER_COLOR = 0 FIELD_HOVER_COLOR = 0xFF383838 else: BACKGROUND_COLOR = 0xFF545454 FIELD_TEXT_COLOR = 0xFFD5D5D5 FIELD_BORDER_COLOR = 0 FIELD_HOVER_COLOR = 0xFFACACAF self._window_style = { "Window": { "background_color": BACKGROUND_COLOR, "border_radius": 6, "border_width": 1, "border_color": FIELD_BORDER_COLOR, }, "ScrollingFrame": {"background_color": BACKGROUND_COLOR}, "Field": { "background_color": BACKGROUND_COLOR, "color": FIELD_TEXT_COLOR, "border_color": FIELD_BORDER_COLOR, "border_radius": 1, "border_width": 0.5, "font_size": 16.0, }, "Field:hovered": {"background_color": FIELD_HOVER_COLOR}, "Field:pressed": {"background_color": FIELD_HOVER_COLOR}, "Field::text_field": {"border_width": 0, "font_size": 14.0}, # search "TreeView.Item::search_view": {"margin": 4}, "TreeView:selected": {"background_color": 0xFF333333}, } def set_parent(self, parent): self.__parent = parent def clean(self): if self._name_value_model: self._name_value_model.clean() if self._name_value_delegate: self._name_value_delegate.clean() if self._search_widget: self._search_widget.clean() del self._name_value_model del self._name_value_delegate self._placeholder_search_widget = None self._scrolling_frame = None self._combo_view = None del self._window def _search_updated(self, string): self._search_widget.update(string) self._name_value_model.filter_by_text(string) self._combo_view.scroll_here_y(0.0) def _select_next(self, comboview: ui.TreeView, model: ui.AbstractItemModel, after=True): full_list = model.get_item_children(None) selection = comboview.selection if not selection: comboview.selection = [full_list[0]] else: index = full_list.index(selection[0]) index += 1 if after else -1 if index < 0 or index >= len(full_list): return comboview.selection = [full_list[index]] def _select_index(self, comboview: ui.TreeView, model: ui.AbstractItemModel, index: int): full_list = model.get_item_children(None) selection = comboview.selection if index >= 0 and index < len(full_list): comboview.selection = [full_list[index]] def _get_view_height(self): item_count = len(self._name_value_model.get_item_children(None)) view_height = (min(10, item_count) * self._height + 1.5) + 4 view_height_min = (3 * self._height + 1.5) + 4 try: appwindow = omni.appwindow.get_default_app_window() window_height = appwindow.get_height() window_height = (window_height / ui.Workspace.get_dpi_scale()) - 8 if self._window.position_y + view_height > window_height: adj = ((self._window.position_y + view_height) - window_height) + self._search_size view_height -= adj if view_height < view_height_min: view_height = view_height_min except: pass return view_height def destroy_ui(self, visible): if not visible: self.set_parent(None) self.clean() def build_ui(self): if self._window and self._window.visible: return # Create and show the window self._window = ui.Window( self._window_id, flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE, auto_resize=True, padding_x=0, padding_y=0, ) self._window.frame.set_style(self._window_style) self._window.set_visibility_changed_fn(self.destroy_ui) def view_clicked(view): async def get_selection(): await omni.kit.app.get_app().next_update_async() selection = view.selection model = selection[0].name_model self._placeholder_search_widget.set_text(model.get_value_as_string()) self._window.visible = False asyncio.ensure_future(get_selection()) self._window.position_x = self.__parent.screen_position_x self._window.position_y = self.__parent.screen_position_y + 20 with self._window.frame: with ui.VStack(width=0, height=0): self._search_widget.build_ui(self.__parent.computed_content_width + 40, self._search_size) self._scrolling_frame = ui.ScrollingFrame( height=self._get_view_height(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with self._scrolling_frame: self._combo_view = ui.TreeView( self._name_value_model, delegate=self._name_value_delegate, root_visible=False, header_visible=False, name="search_view", ) self._combo_view.set_mouse_released_fn(lambda x, y, b, c: view_clicked(self._combo_view)) async def scroll_to_item(): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() item_index = self._name_value_model.get_index_for_item(self._placeholder_search_widget.get_text()) self._select_index(self._combo_view, self._name_value_model, item_index) asyncio.ensure_future(scroll_to_item()) def destroy(self): self.__parent = None self.__frame = None self._scrolling_frame = None self._combo_view = None del self._window def build_searchable_combo_widget( combo_list: List[str], combo_index: int, combo_click_fn: callable, widget_height: int, default_value: str, window_id: str = "SearchableComboBoxWindow", delegate: ui.AbstractItemDelegate = ComboBoxListDelegate(), ) -> SearchWidget: theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" def show_combo_popup( search_widget: SearchWidget, name_field: ui.StringField, combo_index: int, combo_click_fn: callable ): window = ui.Workspace.get_window(window_id) if window: window.visible = False return listbox_widget = ComboListBoxWidget( search_widget=search_widget, item_list=combo_list, window_id=window_id, delegate=delegate, theme=theme ) listbox_widget.set_parent(name_field) listbox_widget.build_ui() search_widget = SearchWidget(theme=theme, icon_path=None) name_field, listbox_button = search_widget.build_ui_popup( search_size=widget_height, default_value=default_value, popup_text=combo_list[combo_index] if combo_index >= 0 else default_value, index=combo_index, update_fn=combo_click_fn, ) name_field.set_mouse_pressed_fn( lambda x, y, b, m, s=search_widget, f=name_field: show_combo_popup(s, f, combo_index, combo_click_fn) ) listbox_button.set_mouse_pressed_fn( lambda x, y, b, m, s=search_widget, f=name_field: show_combo_popup(s, f, combo_index, combo_click_fn) ) return search_widget
9,205
Python
36.57551
118
0.576534
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/tests/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .test_search import *
461
Python
40.999996
76
0.802603
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/tests/test_search.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 pathlib import carb import omni.ui as ui from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.widget.searchable_combobox import build_searchable_combo_widget, ComboBoxListDelegate class TestSearchableComboWidget(AsyncTestCase): async def test_searchable_combo_widget(self): delegate_called = False class TestDelegate(ComboBoxListDelegate): def build_widget(self, model, item, column_id, level, expanded): nonlocal delegate_called delegate_called = True ui.Label( model.get_item_value_model(item, column_id).as_string, skip_draw_when_clipped=True, elided_text=True, height=18, ) callback_calls = 0 callback_value = None window = ui.Window("WidgetTest", width=1000, height=700) with window.frame: with ui.VStack(height=0, spacing=8, style={"margin_width": 2}): ui.Spacer() with ui.HStack(): ui.Label("Component", width=140) def on_combo_click_fn(model): nonlocal callback_calls callback_calls += 1 self.assertTrue(model.get_value_as_string() == callback_value) component_list = [ "3d Reconstruction", "AEC Experience", "AI Framework", "AI Toybox", "AR Experience", "ArtTech", "Asset Converter Service", "Asset Management", "Physics Research", "PhysX Third Party Integrations", "Pinocchio", "PLC", "Point Clouds", "Pose Tracker", "QA Builds", "QA Needs Repro", "Repo Tools", "Reshade", "Resolvers", "RTX", "RTX Hydra", "RTX MGPU", "RTX Renderer", "Sample Content", "SDG", "Sequencer", "Server Installer", "Showroom", "Synthetic Data", "USD", "USD Delta Library", "USD Hydra", "Kit", "USDRT", "UX", "UX / UI", "Virtual Production", "XR", ] component_index = -1 component_combo = build_searchable_combo_widget( component_list, component_index, on_combo_click_fn, widget_height=18, default_value="Kit", window_id="SearchableComboBoxWindow##test_searchable_combo_widget", delegate=TestDelegate(), ) # test set_text & get_text await ui_test.human_delay() callback_value = "USD" component_combo.set_text("USD") await ui_test.human_delay() self.assertTrue(component_combo.get_text() == "USD") self.assertTrue(callback_calls == 1) # test clear & default clear_widget = ui_test.find("WidgetTest//Frame/**/Button[*].name=='remove_popup'") callback_value = "Kit" await clear_widget.click() self.assertTrue(component_combo.get_text() == "Kit") self.assertTrue(callback_calls == 2) # test combo open and typing text_field = ui_test.find("WidgetTest//Frame/**/StringField[*]") await text_field.click() # TODO: text_field.input("ArtTech") don't work here as it does a double_click await ui_test.emulate_char_press("ArtTech") await ui_test.human_delay() treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]") callback_value = "ArtTech" # y+8 to make sure mouse pointer is on popup window (combobox item list), so 1st item is selected await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8) ) self.assertTrue(component_combo.get_text() == callback_value) self.assertTrue(callback_calls == 3) # holding onto this varaible prevents ComboListBoxWidget from getting garbage collected. treeview_widget = None # test combo open button and typing open_widget = ui_test.find("WidgetTest//Frame/**/Button[*].name=='listbox'") await open_widget.click() # as this opens popup window, need to wait for that to be created and ready to use await ui_test.human_delay() await ui_test.emulate_char_press("Pinocchio") treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]") callback_value = "Pinocchio" # y+8 to make sure mouse pointer is on popup window (combobox item list), so 1st item is selected await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8) ) self.assertTrue(component_combo.get_text() == callback_value) self.assertTrue(callback_calls == 4) # holding onto this varaible prevents ComboListBoxWidget from getting garbage collected. treeview_widget = None # test search clear await text_field.click() await ui_test.emulate_char_press("this will be cleared...") await ui_test.human_delay() clear_widget = ui_test.find( "SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/Button[*].name=='remove'" ) await clear_widget.click() await ui_test.emulate_char_press("Asset Converter Service") treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]") callback_value = "Asset Converter Service" await ui_test.emulate_mouse_move_and_click( ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8) ) self.assertTrue(component_combo.get_text() == "Asset Converter Service") self.assertTrue(callback_calls == 5) # holding onto this varaible prevents ComboListBoxWidget from getting garbage collected. treeview_widget = None # test delegate was called self.assertTrue(delegate_called)
7,501
Python
43.390532
118
0.54926
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.5] - 2022-05-18 + Moved to kit ## [1.0.4] - 2021-11-26 + Fixed test using input ## [1.0.3] - 2021-11-26 + Updated to use omni.kit.ui_test ## [1.0.2] - 2021-11-09 + ETM Fix ## [1.0.1] - 2021-10-25 + Removed omni.usd dependancy ## [1.0.0] - 2021-10-12 + Created
527
Markdown
19.307692
87
0.660342
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/docs/README.md
# Searchable ComboBox widget To use: ``` from omni.kit.widget.searchable_combobox import build_searchable_combo_widget def on_combo_click_fn(model): component = model.get_value_as_string() print(f"{component} selected") component_list = ['3d Reconstruction', 'AEC Experience', 'AI Framework', 'AI Toybox', 'AR Experience', 'ArtTech', 'Asset Converter Service', 'Asset Management', 'Physics Research', 'PhysX Third Party Integrations', 'Pinocchio', 'PLC', 'Point Clouds', 'Pose Tracker', 'QA Builds', 'QA Needs Repro', 'Repo Tools', 'Reshade', 'Resolvers', 'RTX', 'RTX Hydra', 'RTX MGPU', 'RTX Renderer', 'Sample Content', 'SDG', 'Sequencer', 'Server Installer', 'Showroom', 'Synthetic Data', 'USD', 'USD Delta Library', 'USD Hydra', 'Kit', 'USDRT', 'UX', 'UX / UI', 'Virtual Production', 'XR'] component_index = -1 self._component_combo = build_searchable_combo_widget(component_list, component_index, on_combo_click_fn, widget_height=18, default_value="Kit") ``` Get combo widget value: ``` component_name = self._component_combo.get_text() ``` Set combo widget value: ``` self._component_combo.set_text("Showroom") ``` Cleanup: ``` self._component_combo.destroy() self._component_combo = None ```
1,217
Markdown
33.799999
573
0.697617
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/docs/index.rst
omni.kit.widget.searchable_combobox ################################### Extension provides combobox widget with search functionality. .. toctree:: :maxdepth: 1 CHANGELOG.md
184
reStructuredText
17.499998
61
0.608696
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_widget_delegate_manager.py
from .abstract_camera_widget_delegate import AbstractCameraButtonDelegate, AbstractCameraMenuItemDelegate from pxr import Sdf class CameraWidgetDelegateManager: def destroy(self): for delegate in AbstractCameraButtonDelegate.get_instances(): delegate.destroy() for delegate in AbstractCameraMenuItemDelegate.get_instances(): delegate.destroy() def __get_all_delegates(self, camera_button_or_menu_item: bool): all_widget_delegates = [] if camera_button_or_menu_item: for delegate in AbstractCameraButtonDelegate.get_instances(): all_widget_delegates.append(delegate) else: for delegate in AbstractCameraMenuItemDelegate.get_instances(): all_widget_delegates.append(delegate) # Sort list in ascending order. all_widget_delegates.sort(key=lambda item: item.order) return all_widget_delegates def build_widgets( self, parent_id, viewport_api, camera_path: Sdf.Path, camera_button_or_menu_item: bool ): """Build all camera widgets for specific camera path with sort based on their orders.""" all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.build_widget(parent_id, viewport_api, camera_path) def on_parent_destroyed(self, parent_id, camera_button_or_menu_item: bool) -> None: # Clean up when parent widget destroyed all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_parent_destroyed(parent_id) def on_camera_path_changed(self, parent_id, camera_path, camera_button_or_menu_item: bool): """The camera tracked has changed.""" all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_camera_path_changed(parent_id, camera_path)
2,035
Python
40.55102
105
0.682555
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_list_delegate.py
__all__ = ["CameraListDelegate"] import carb import omni.usd import omni.ui as ui from typing import Optional from omni.kit.viewport.menubar.core import IconMenuDelegate, USDAttributeModel from pxr import Sdf from .camera_widget_delegate_manager import CameraWidgetDelegateManager class CameraListDelegate(IconMenuDelegate): def __init__(self, viewport_api, widget_delegate_manager: CameraWidgetDelegateManager): self.__model: Optional[USDAttributeModel] = None self.__sub = None self.__viewport_api = viewport_api self.__selected_camera_path = Sdf.Path.emptyPath self.__widget_delegate_manager = widget_delegate_manager super().__init__("UnlockedCamera", text=True, build_custom_widgets=self.__build_custom_widgets) def destroy(self): self.__sub = None if self.__widget_delegate_manager: self.__widget_delegate_manager.on_parent_destroyed(id(self), True) self.__widget_delegate_manager = None super().destroy() def __build_custom_widgets(self, item: ui.MenuItem): if not self.__widget_delegate_manager: return try: self.__widget_delegate_manager.build_widgets( id(self), self.__viewport_api, self.__selected_camera_path, True ) except Exception as e: carb.log_error(f"Failed to build widget: {str(e)}") def _build_icon(self): # with vstack to not trigger menu if click on icon if self._text: with ui.VStack(content_clipping=True, width=0): icon = super()._build_icon() icon.set_mouse_pressed_fn(lambda x, y, b, a: self.__toggle_lock()) else: icon = super()._build_icon() icon.name = self.__get_icon_name() return icon @property def camera_path(self) -> Sdf.Path: return self.__selected_camera_path @camera_path.setter def camera_path(self, path): self.__selected_camera_path = path if self.__widget_delegate_manager: self.__widget_delegate_manager.on_camera_path_changed(id(self), path, True) @property def model(self) -> USDAttributeModel: return self.__model @model.setter def model(self, new_model: USDAttributeModel) -> None: self.__model = new_model icon_name = self.__get_icon_name() if hasattr(self, "icon"): self.icon.name = icon_name else: self._name = icon_name if self.__sub: self.__sub = None if self.__model: self.__sub = self.__model.subscribe_value_changed_fn(self._on_lock_changed) def __get_icon_name(self): if not self.__model: return "UnlockedCameraWithoutHovered" hov_text = "" if bool(self._text) else "WithoutHovered" lock_text = "LockedCamera" if self.__model.as_bool else "UnlockedCamera" return f"{lock_text}{hov_text}" def _on_lock_changed(self, model: ui.AbstractValueModel) -> None: icon_name = self.__get_icon_name() if hasattr(self, "icon"): self.icon.name = icon_name else: self._name = icon_name def __toggle_lock(self): if self.__model: self.__model.set_value(not self.__model.as_bool)
3,346
Python
33.505154
103
0.604603
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/style.py
from omni.ui import color as cl import carb.tokens from pathlib import Path ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.camera}")).joinpath("data").joinpath("icons").absolute() ICON_CORE_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.core}")).joinpath("data").joinpath("icons").absolute() UI_STYLE = { "Menu.Item.Icon::UnlockedCamera": {"image_url": f"{ICON_PATH}/camera_viewport.svg"}, "Menu.Item.Icon::UnlockedCameraWithoutHovered": {"image_url": f"{ICON_PATH}/camera_viewport.svg"}, "Menu.Item.Icon::UnlockedCamera:hovered": {"image_url": f"{ICON_PATH}/lock_dark.svg"}, "Menu.Item.Icon::LockedCamera": {"image_url": f"{ICON_PATH}/viewport_cameras_locked.svg"}, "Menu.Item.Icon::LockedCameraWithoutHovered": {"image_url": f"{ICON_PATH}/viewport_cameras_locked.svg"}, "Menu.Item.Icon::LockedCamera:hovered": {"image_url": f"{ICON_PATH}/unlock_dark.svg"}, "Menu.Item.Icon::Expand": {"image_url": f"{ICON_PATH}/expand.svg", "color": cl.viewport_menubar_background}, "Menu.Item.Icon::Expand:checked": {"image_url": f"{ICON_PATH}/contract.svg"}, "Menu.Item.Icon::Lock": {"image_url": f"{ICON_PATH}/unlock_dark.svg", "color": cl.viewport_menubar_background}, "Menu.Item.Icon::Lock:checked": {"image_url": f"{ICON_PATH}/lock_dark.svg"}, "Menu.Item.Icon::Sample": {"image_url": f"{ICON_PATH}/focalSample_viewport.svg"}, "Menu.Item.Icon::Sample:disabled": {"color": cl.viewport_menubar_medium}, "Menu.Item.Icon::Add": {"image_url": f"{ICON_PATH}/add.svg", "color": cl.viewport_menubar_selection_border}, "Menu.Item.Icon::Lens": {"image_url": f"{ICON_PATH}/lens.svg"}, "Menu.Item.Icon::FocalDistance": {"image_url": f"{ICON_PATH}/focal_distance.svg"}, "Menu.Item.Icon::FStop": {"image_url": f"{ICON_PATH}/Fstop.svg"}, "Menu.Item.Button": { "background_color": 0, "margin": 0, "padding": 0, }, "Menu.Item.Button.Image::OptionBox": {"image_url": f"{ICON_CORE_PATH}/settings_submenu.svg"}, "Menu.Item.Button.Image::CameraLocked": {"image_url": f"{ICON_PATH}/lock_dark.svg"}, "Menu.Item.Button.Image::CameraUnlocked": {"image_url": f"{ICON_PATH}/unlock_dark.svg"}, "MenuBar.Item::transparent": { # "color": 0, }, }
2,311
Python
61.486485
148
0.663349
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/commands.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.commands import omni.usd from pxr import Gf, Sdf, Usd, UsdGeom from typing import Union import carb CAMERA_LOCK_NAME = "omni:kit:cameraLock" class DuplicateCameraCommand(omni.kit.commands.Command): """ Duplicates a camera at a specific time Args: camera_path (str): name of the camera to duplicate. time (float): Time at which to duplicate, or None to use active time usd_context_name (str): The name of a valid omni.UsdContext to target new_camera_path (str): Path to create the new camera at (None for automatic path) """ def __init__(self, camera_path: str = "", time: float = None, usd_context_name: str = '', new_camera_path: str = None): self.__camera_path = camera_path self.__usd_context_name = usd_context_name self.__time = time if time is not None else omni.timeline.get_timeline_interface().get_current_time() self.__new_camera_path = new_camera_path def do(self): if not self.__camera_path: return usd_context = omni.usd.get_context(self.__usd_context_name) if not usd_context: raise RuntimeError(f'UsdContext "{self.self.__usd_context_name}" could not be found') stage = usd_context.get_stage() if not stage: raise RuntimeError(f'UsdContext "{self.self.__usd_context_name}" has no stage') old_prim = stage.GetPrimAtPath(self.__camera_path) if not old_prim: raise RuntimeError(f'Could not find camera prim at "{self.__camera_path}"') if self.__new_camera_path is None: target_path = omni.usd.get_stage_next_free_path(stage, "/Camera", True) else: target_path, self.__new_camera_path = self.__new_camera_path, None omni.kit.commands.execute("CreatePrimWithDefaultXformCommand", prim_path=target_path, prim_type="Camera", create_default_xform=False, stage=stage) new_prim = stage.GetPrimAtPath(target_path) if not new_prim: raise RuntimeError(f'Could not find duplicated prim at "{target_path}"') # Save the created camera path now so any failure below won't kill our undo self.__new_camera_path = target_path timecode = self.__time * stage.GetTimeCodesPerSecond() for attr in old_prim.GetAttributes(): attr_name = attr.GetName() # Skip over any xformOp property (they are not duplicated but created below) if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(attr_name): continue # Skip over the locked property if attr_name == CAMERA_LOCK_NAME: continue value = attr.Get(timecode) if value is not None: new_prim.CreateAttribute(attr.GetName(), attr.GetTypeName()).Set(value) # Now create the transform, taking the original world-space of the source camera and putting it into # the new camera's parent's space. We do this always so that TransformPrim can create the correct # rotation ordering now. parent_xformable = UsdGeom.Xformable(new_prim.GetParent()) if parent_xformable: parent_world_xform = omni.usd.get_world_transform_matrix(parent_xformable.GetPrim(), timecode) else: parent_world_xform = Gf.Matrix4d(1) old_camera_prim_world_mtx = omni.usd.get_world_transform_matrix(old_prim, timecode) new_camera_prim_local_mtx = old_camera_prim_world_mtx * parent_world_xform.GetInverse() omni.kit.commands.execute( "TransformPrim", path=new_prim.GetPath(), new_transform_matrix=new_camera_prim_local_mtx, usd_context_name=self.__usd_context_name ) # These won't be undone, but that's ok..undo will delete the prim omni.usd.editor.set_no_delete(new_prim, False) omni.usd.editor.set_hide_in_stage_window(new_prim, False) def undo(self): pass class SetViewportCameraCommand(omni.kit.commands.Command): """ Sets a Viewport's actively bound camera to camera at given path Args: camera_path (Union[str, Sdf.Path): New camera path to bind to viewport. viewport_api: the viewport to target. """ def __init__(self, camera_path: Union[str, Sdf.Path], viewport_api, *args, **kwargs): super().__init__(*args, **kwargs) self.__viewport_api = viewport_api self.__prev_camera = viewport_api.camera_path self.__target_camera = camera_path self.__look_target = None self.__coi_value = None @staticmethod def read_camera_path(viewport_api) -> Sdf.Path: stage = viewport_api.stage if stage: # TODO: 104 Put in proper namespace and per viewport # camera_path = stage.GetMetadataByDictKey("customLayerData", f"cameraSettings:{viewport_api.id}:boundCamera") or # Fallback to < 103.1 boundCamera camera_path = stage.GetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera") if camera_path: prim = stage.GetPrimAtPath(camera_path) if prim and UsdGeom.Camera(prim): return prim.GetPath() return None def __save_to_file(self, camera_path: str): viewport_api = self.__viewport_api stage = viewport_api.stage # Allow (but warn) the case if no Usd.Stage if not stage: carb.log_warn("No Usd.Stage to set boundCamera to") return # Error if not root-layer layer = stage.GetRootLayer() if not layer: carb.log_error("No Usd.Layer to set boundCamera to") return # Move the EditTarget to the root-layer and set meta-data there with Usd.EditContext(stage, Usd.EditTarget(layer)): # TODO: 104 Put in proper namespace and per viewport # stage.SetMetadataByDictKey("customLayerData", f"cameraSettings:{viewport_api.id}boundCamera", camera_path) # Save the legacy version for opening in versions < 103.1 stage.SetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera", camera_path) def do(self): self.__viewport_api.camera_path = self.__target_camera self.__save_to_file(str(self.__target_camera)) def undo(self, look_through=None): # Set the viewport to use the previous camera self.__viewport_api.camera_path = self.__prev_camera self.__save_to_file(str(self.__prev_camera)) class DuplicateViewportCameraCommand(omni.kit.commands.Command): """ Duplicates a Viewport's actively bound camera and bind active camera to the duplicated one. Args: viewport_api: The viewport to target """ def __init__(self, viewport_api, *args, **kwargs): super().__init__(*args, **kwargs) self.__viewport_api = viewport_api def do(self): viewport_api = self.__viewport_api new_camera_path = omni.usd.get_stage_next_free_path(viewport_api.stage, "/Camera", True) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=viewport_api.camera_path, usd_context_name=viewport_api.usd_context_name, new_camera_path=new_camera_path) omni.kit.commands.execute("SetViewportCameraCommand", camera_path=new_camera_path, viewport_api=viewport_api) def undo(self): pass def register_commands(): return omni.kit.commands.register_all_commands_in_module(__name__) def unregister_commands(cmds): omni.kit.commands.unregister_module_commands(cmds)
8,066
Python
41.457895
178
0.651128
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/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__ = ["ViewportCameraMenuBarExtension", "get_instance", "SingleCameraMenuItemBase", "SingleCameraMenuItem"] from typing import Callable from .camera_menu_container import CameraMenuContainer from .commands import register_commands, unregister_commands import omni.ext import omni.ui as ui from .menu_item.single_camera_menu_item import SingleCameraMenuItemBase, SingleCameraMenuItem _extension_instance = None def get_instance(): global _extension_instance return _extension_instance class ViewportCameraMenuBarExtension(omni.ext.IExt): """The Entry Point for the Display Settings in Viewport Menu Bar""" def on_startup(self, ext_id): self._camera_menu = CameraMenuContainer() self._cmds = register_commands() global _extension_instance _extension_instance = self def on_shutdown(self): if self._camera_menu: self._camera_menu.destroy() self._camera_menu = None cmds, self._cmds = self._cmds, None unregister_commands(cmds) global _extension_instance _extension_instance = None def register_menu_item_type(self, menu_item_type: Callable[..., "SingleCameraMenuItemBase"]): """ Register a custom menu type for the default created camera Args: menu_item_type: callable that will create the menu item """ if self._camera_menu: self._camera_menu.set_menu_item_type(menu_item_type) def register_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None], order: int = 0): """ Register a custom menu item. Args: create_menu_item_fn (Callable): Callback function to create custom menu item. Kwargs: order (int): Position to put cusom menu item in popup menu window. """ if self._camera_menu: self._camera_menu.register_menu_item(create_menu_item_fn, order=order) def deregister_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None]): """ Deregister a custom menu item. Args: create_menu_item_fn (Callable): Callback function to create custom menu item. """ if self._camera_menu: self._camera_menu.deregister_menu_item(create_menu_item_fn)
2,773
Python
35.5
117
0.681212
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/__init__.py
from .extension import * from .abstract_camera_widget_delegate import *
71
Python
34.999983
46
0.802817
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/utils.py
import omni.usd from pxr import Sdf, Usd from typing import Optional SESSION_CAMERAS = { "/OmniverseKit_Persp": "Perspective", "/OmniverseKit_Top": "Top", "/OmniverseKit_Front": "Front", "/OmniverseKit_Right": "Right", } def get_camera_display(path: Sdf.Path, stage: Optional[Usd.Stage] = None): name = SESSION_CAMERAS.get(path.pathString, None) if name: return name if stage: camera_prim = stage.GetPrimAtPath(path) if camera_prim: display_name = omni.usd.editor.get_display_name(camera_prim) if display_name: return display_name return path.name
650
Python
23.11111
74
0.635385
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/abstract_camera_widget_delegate.py
__all__ = ["AbstractCameraButtonDelegate", "AbstractCameraMenuItemDelegate"] import abc import weakref import omni.ui as ui from enum import IntEnum from pxr import Sdf from typing import Optional class AbstractWidgetDelegate(abc.ABC): """ The base class for camera widget delegate. This delegate works for providing the additional camera widget for items of camera list. """ @abc.abstractmethod def build_widget(self, parent_id, viewport_api, camera_path: Sdf.Path) -> Optional[ui.Widget]: """ Builds widget. This must be overrided to provide the layout. parent_id: It's unique id of the camera item, with which you can use to manage the camera widget. viewport_api: Viewport interface. camera_path (Sdf.Path): The camera path to build widget for. """ pass @abc.abstractmethod def on_parent_destroyed(self, parent_id) -> None: """ Called before the destroy of the parent widget. This function can be overrided to release the bound resources specific to the parent. """ pass @abc.abstractmethod def on_camera_path_changed(self, parent_id, camera_path): """The camera tracked has changed.""" pass def destroy(self): """Place to release resources.""" pass @property def order(self) -> int: """ The order of the widget relative to the right of camera label. The lower the order number, the closer the widget to the camera label. """ return 0 class AbstractCameraButtonDelegate(AbstractWidgetDelegate): # Use a list to track all instances __g_registered = [] @classmethod def get_instances(cls): remove = [] # Return a copy to avoid remove in the middle of iterating. all_instances = AbstractCameraButtonDelegate.__g_registered.copy() for wref in all_instances: obj = wref() if obj: yield obj else: remove.append(wref) for wref in remove: AbstractCameraButtonDelegate.__g_registered.remove(wref) def __init__(self): super().__init__() self.__g_registered.append( weakref.ref(self, lambda r: AbstractCameraButtonDelegate.__g_registered.remove(r)) ) def __del__(self): self.destroy() def destroy(self): """Place for releasing resources.""" for wref in AbstractCameraButtonDelegate.__g_registered: if wref() == self: AbstractCameraButtonDelegate.__g_registered.remove(wref) break super().destroy() class AbstractCameraMenuItemDelegate(AbstractWidgetDelegate): # Use a list to track all instances __g_registered = [] @classmethod def get_instances(cls): remove = [] # Return a copy to avoid remove in the middle of iterating. all_instances = AbstractCameraMenuItemDelegate.__g_registered.copy() for wref in all_instances: obj = wref() if obj: yield obj else: remove.append(wref) for wref in remove: AbstractCameraMenuItemDelegate.__g_registered.remove(wref) def __init__(self): super().__init__() self.__g_registered.append( weakref.ref(self, lambda r: AbstractCameraMenuItemDelegate.__g_registered.remove(r)) ) def __del__(self): self.destroy() def destroy(self): """Place for releasing resources.""" for wref in AbstractCameraMenuItemDelegate.__g_registered: if wref() == self: AbstractCameraMenuItemDelegate.__g_registered.remove(wref) break super().destroy() class CameraWidgetDelegateManager: def destroy(self): for delegate in AbstractCameraButtonDelegate.get_instances(): delegate.destroy() for delegate in AbstractCameraMenuItemDelegate.get_instances(): delegate.destroy() def __get_all_delegates(self, camera_button_or_menu_item: bool): all_widget_delegates = [] if camera_button_or_menu_item: for delegate in AbstractCameraButtonDelegate.get_instances(): all_widget_delegates.append(delegate) else: for delegate in AbstractCameraMenuItemDelegate.get_instances(): all_widget_delegates.append(delegate) # Sort list in ascending order. all_widget_delegates.sort(key=lambda item: item.order) def build_widgets( self, parent_id, viewport_api, camera_path: Sdf.Path, camera_button_or_menu_item: bool ): """Build all camera widgets for specific camera path with sort based on their orders.""" all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.build_widget(parent_id, viewport_api, camera_path) def on_parent_destroyed(self, parent_id, camera_button_or_menu_item: bool) -> None: all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_parent_destroyed(parent_id) def on_camera_path_changed(self, parent_id, camera_path, camera_button_or_menu_item: bool): all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item) for delegate in all_widget_delegates: delegate.on_camera_path_changed(parent_id, camera_path)
5,626
Python
30.261111
98
0.626911
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_menu_container.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__ = ["CameraMenuContainer"] from omni.kit.async_engine import run_coroutine from omni.kit.viewport.menubar.core import ( ViewportMenuDelegate, SeparatorDelegate, ViewportMenuContainer, USDAttributeModel, USDFloatAttributeModel, menu_is_tearable, MenuDisplayStatus ) from .menu_item.lens import CameraLens from .menu_item.focal_distance import CameraFocalDistance from .menu_item.fstop import CameraFStop from .menu_item.auto_exposure import CameraAutoExposure from .menu_item.single_camera_menu_item import SingleCameraMenuItem, NoCameraMenuItem from .menu_item.expand_menu_item import ExpandMenuItem from .commands import SetViewportCameraCommand from .camera_list_delegate import CameraListDelegate from .style import UI_STYLE from .utils import SESSION_CAMERAS, get_camera_display from functools import partial from pxr import Sdf, Tf, Trace, Usd, UsdGeom from typing import Callable, Dict, List, Optional, Set, TYPE_CHECKING, Tuple, Union from .camera_widget_delegate_manager import CameraWidgetDelegateManager import asyncio from dataclasses import dataclass, fields, field import carb import functools import omni.ui as ui import omni.usd import omni.kit.commands import omni.timeline import traceback import weakref import concurrent.futures if TYPE_CHECKING: from .menu_item.single_camera_menu_item import SingleCameraMenuItemBase CAMERA_LOCK_NAME = "omni:kit:cameraLock" def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except Exception as e: carb.log_error(f"Exception when async '{func}'") carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") return wrapper def _show_camera_in_menu(prim: Usd.Prim): return prim and prim.IsA(UsdGeom.Camera) and not omni.usd.editor.is_hide_in_ui(prim) class _CameraList: """The object that watches USD for the list of cameras""" def __init__(self, stage, callback): self.__stage: Usd.Stage = stage self.__callback: Callable[[], None] = callback self.__cameras: Set[Sdf.Path] = set() self.__listener = None self.__dirty = True self.__camera_filters = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/filters") or [] self.__usdrt_stage = self.__get_usd_rt_stage(stage) self.__listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__on_usd_changed, stage) if stage else None self.__dirty_prim_paths: Set[Sdf.Path] = set() self.__prim_changed_task: Optional[concurrent.futures.Future] = None def __del__(self): self.destroy() def destroy(self): if self.__listener: self.__listener.Revoke() self.__listener = None @property def is_dirty(self): return self.__dirty @property def camera_list(self) -> List[Sdf.Path]: # If it's called the first time, we just iterate the whole USD stage for cameras # Note the cast to bool is important in case self.__stage is not None, but also an invalid stage was_dirty, self.__dirty = self.__dirty, False has_stage = bool(self.__stage) if was_dirty and has_stage: self.__cameras: Set[Sdf.Path] = set() if self.__usdrt_stage: for prim_path in self.__usdrt_stage.GetPrimsWithTypeName("Camera"): usd_prim = self.__stage.GetPrimAtPath(prim_path.GetString()) if _show_camera_in_menu(usd_prim) and self.__filter(usd_prim): self.__cameras.add(usd_prim.GetPath()) else: # If it's called the first time, we just iterate the whole USD stage for cameras # Note the cast to bool is important in case self.__stage is not None, but also an invalid stage predicate = Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded) for usd_prim in self.__stage.Traverse(predicate): if _show_camera_in_menu(usd_prim) and self.__filter(usd_prim): self.__cameras.add(usd_prim.GetPath()) return self.__cameras def __filter(self, camera_prim: Usd.Prim) -> bool: path = camera_prim.GetPath().pathString for filter in self.__camera_filters: if path.startswith(filter): return False return True @staticmethod def __get_usd_rt_stage(stage: Usd.Stage): if carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/primQuery/useUsdRt"): try: from pxr import UsdUtils from usdrt import Usd as UsdRtUsd stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt() fabric_active_for_stage = UsdRtUsd.Stage.StageWithHistoryExists(stage_id) if fabric_active_for_stage: return UsdRtUsd.Stage.Attach(stage_id) except (ImportError, ModuleNotFoundError): pass return None @Trace.TraceFunction def __on_usd_changed(self, notice: Tf.Notice, stage: Usd.Stage): """Called by Usd.Notice.ObjectsChanged""" if not bool(self.__stage) or stage != self.__stage: return dirty_prims_paths: List[Sdf.Path] = [] for p in notice.GetResyncedPaths(): if p.IsAbsoluteRootOrPrimPath(): dirty_prims_paths.append(p) if not dirty_prims_paths: return self.__dirty_prim_paths.update(dirty_prims_paths) # Update in the next frame. We need it because we want to accumulate the affected prims if self.__prim_changed_task is None or self.__prim_changed_task.done(): self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed()) @handle_exception @Trace.TraceFunction async def __delayed_prim_changed(self): """ Create/remove dirty items that was collected from TfNotice. Can be called any time to pump changes. """ if not bool(self.__stage): return # Swap the dirty list to a local and reset the instance state dirty = False dirty_prim_paths, self.__dirty_prim_paths = self.__dirty_prim_paths, set() removed_camera, added_camera = None, None for path in dirty_prim_paths: prim = self.__stage.GetPrimAtPath(path) if _show_camera_in_menu(prim): # Changed or created self.__cameras.add(path) added_camera = path dirty = True else: # Removed or changed type try: self.__cameras.remove(path) removed_camera = path except KeyError: pass dirty = True # For the case with one event that represents and removal and addition of a camera, pass it along as -hint-. # There could be fals-positives (a layer event where only one camera is gone and one added), but even in # that case hinting to the Viewport what to do (leave camera if removed camera was active) isn't horrible. if len(dirty_prim_paths) != 2 or (removed_camera is None) or (added_camera is None): removed_camera, added_camera = None, None if dirty: self.__dirty = True self.__callback(removed_camera, added_camera) self.__prim_changed_task = None @dataclass class MenuContext: root_menu: ui.Menu = None delegate: ui.MenuDelegate = None settings_menu: ui.Menu = None settings_container: ui.ZStack = None settings_width: int = 0 expand_container: ui.ZStack = None expand_item: ExpandMenuItem = None expand_width: int = 0 expand_model: ui.SimpleBoolModel = None saved_expand = False camera_collection: ui.MenuItemCollection = None camera_path: str = None selected_camera_item: ui.MenuItem = None camera_list: Optional[_CameraList] = None stage_sub: carb.Subscription = None expanded_sub: carb.Subscription = None render_settings_changed_sub: carb.Subscription = None lock_menu_sub: carb.Subscription = None settings_items: List[ui.MenuItem] = field(default_factory=list) camera_to_menu: Dict[Sdf.Path, Tuple[SingleCameraMenuItem, bool]] = field(default_factory=dict) def __init__(self, **kwargs): names = set([f.name for f in fields(self)]) for k, v in kwargs.items(): if k in names: setattr(self, k, v) if not hasattr(self, "settings_items"): self.settings_items = [] if not hasattr(self, "camera_to_menu"): self.camera_to_menu = {} class CameraMenuContainer(ViewportMenuContainer): """The menu with the list of cameras""" def __init__(self): super().__init__( name="Camera", delegate=None, visible_setting_path="/exts/omni.kit.viewport.menubar.camera/visible", order_setting_path="/exts/omni.kit.viewport.menubar.camera/order", expand_setting_path="/exts/omni.kit.viewport.menubar.camera/expand", style=UI_STYLE ) self.__menu_item_type = SingleCameraMenuItem self.__lock_models: Dict[Sdf.Path, USDAttributeModel] = {} self.__menu_context: Dict[int, MenuContext] = {} self._create_menu_item_fns: List[List[Callable[["viewport_context", ui.Menu], None]], int] = [] self.register_menu_item(self._build_camera_collections, -100) self.register_menu_item(self._build_create_camera, -90) self.__custom_camera_widget_delegate_manager = CameraWidgetDelegateManager() def set_menu_item_type(self, menu_item_type: Callable[..., "SingleCameraMenuItemBase"]): """ Set the menu type for the default created camera Args: menu_item_type: callable that will create the menu item """ if not menu_item_type: menu_item_type = SingleCameraMenuItem if self.__menu_item_type != menu_item_type: self.__menu_item_type = menu_item_type self.__full_invalidate() def __del__(self): self.destroy() def destroy(self): self.__lock_models = {} for context in self.__menu_context.values(): context.expanded_sub = None context.lock_menu_sub = None if context.render_settings_changed_sub: context.render_settings_changed_sub.destroy() context.render_settings_changed_sub = None self.__custom_camera_widget_delegate_manager.destroy() super().destroy() def __full_invalidate(self): for context in self.__menu_context.values(): context.root_menu.invalidate() context.settings_menu.invalidate() def get_display_status(self, factory_args: Dict) -> MenuDisplayStatus: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] if context.expand_container.visible: return MenuDisplayStatus.EXPAND elif context.delegate.text_visible: return MenuDisplayStatus.LABEL else: return MenuDisplayStatus.MIN def get_require_size(self, factory_args: Dict, expand: bool=False) -> float: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] display_status = self.get_display_status(factory_args) if expand: if display_status == MenuDisplayStatus.EXPAND: return 0 elif display_status == MenuDisplayStatus.LABEL: return context.settings_width + context.expand_width else: return context.delegate.text_size else: if display_status == MenuDisplayStatus.EXPAND: if context.expand_model.as_bool: return 0 else: return context.settings_width elif display_status == MenuDisplayStatus.LABEL: return 0 else: return context.delegate.text_size def expand(self, factory_args: Dict) -> None: viewport_api_id = factory_args['viewport_api'].id context = self.__menu_context[viewport_api_id] if context.expand_container.visible: return elif context.delegate.text_visible: context.expand_model.set_value(context.saved_expand) context.expand_container.visible = True else: context.delegate.text_visible = True if context.root_menu: context.root_menu.invalidate() def can_contract(self, factory_args: Dict) -> bool: display_status = self.get_display_status(factory_args) return display_status == MenuDisplayStatus.LABEL or display_status == MenuDisplayStatus.EXPAND def contract(self, factory_args: Dict) -> bool: viewport_api_id = factory_args['viewport_api'].id if viewport_api_id not in self.__menu_context: return False context = self.__menu_context[viewport_api_id] display_status = self.get_display_status(factory_args) if display_status == MenuDisplayStatus.EXPAND: context.saved_expand = context.expand_model.as_bool context.expand_model.set_value(False) context.expand_container.visible = False return True elif display_status == MenuDisplayStatus.LABEL: context.delegate.text_visible = False if context.root_menu: context.root_menu.invalidate() return True return False def register_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None], order: int = 0): self._create_menu_item_fns.append((create_menu_item_fn, order)) self.__full_invalidate() def deregister_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None]): found = [item for item in self._create_menu_item_fns if item[0] == create_menu_item_fn] if found: for item in found: self._create_menu_item_fns.remove(item) self.__full_invalidate() def build_fn(self, viewport_context: Dict): """Entry point for the menu bar""" viewport_api = viewport_context.get('viewport_api') viewport_api_id = viewport_api.id # Empty out any existing menu objects self.__menu_context[viewport_api_id] = MenuContext( delegate=CameraListDelegate(viewport_api, self.__custom_camera_widget_delegate_manager) ) # Get a local reference to the new mapped value _menu_context = self.__menu_context[viewport_api_id] _menu_context.root_menu = ui.Menu(menu_compatibility=False, delegate=_menu_context.delegate, style=self._style) _menu_context.root_menu.set_on_build_fn(lambda *args, **kwargs: self._build_menu(viewport_context)) # The Camera property widgets selection menu _menu_context.settings_container = ui.ZStack(width=0) with _menu_context.settings_container: ui.Rectangle(style_type_name_override="Menu.Item.Background") with ui.HStack(width=0): ui.Spacer(width=5) _menu_context.settings_menu = ui.Menu(menu_compatibility=False, direction=ui.Direction.LEFT_TO_RIGHT, style=self._style) _menu_context.settings_menu.set_on_build_fn(lambda *args, **kwargs: self._build_expand(viewport_context)) ui.Spacer(width=5) def __on_settings_changed(id): menu_context = self.__menu_context[viewport_api_id] menu_context.settings_width = max(menu_context.settings_width, menu_context.settings_container.computed_content_width) _menu_context.settings_container.set_computed_content_size_changed_fn(partial(__on_settings_changed, viewport_api_id)) # Delay a frame to hide camera settings if required to get settings width for contract/expand when startup _menu_context.expand_model = ui.SimpleBoolModel(self.expand_model.as_bool) async def __hide_camera_settings_async(menu_context): await omni.kit.app.get_app().next_update_async() menu_context.settings_container.visible = menu_context.expand_model.as_bool if not self.expand_model.as_bool: self.__hide_camera_settings_task_or_future = run_coroutine(__hide_camera_settings_async(_menu_context)) # Menu to expand/contract camera properties _menu_context.expand_container = ui.ZStack(width=0, height=0, style={"padding": 0, "margin": 0}) with _menu_context.expand_container: with ui.Menu(menu_compatibility=False, direction=ui.Direction.LEFT_TO_RIGHT, style=self._style): _menu_context.expand_item = ExpandMenuItem(_menu_context.expand_model) def __on_expand_changed(*args, **kwargs): menu_context = self.__menu_context[viewport_api_id] menu_context.expand_width = max(menu_context.expand_width, menu_context.expand_container.computed_content_width) _menu_context.expand_container.set_computed_content_size_changed_fn(__on_expand_changed) def __on_toggle_expand(*args, **kwargs): menu_context = self.__menu_context[viewport_api_id] menu_context.settings_container.visible = menu_context.expand_model.as_bool menu_context.expand_item.checked = menu_context.expand_model.as_bool # Reset global expand status # Once at least one expanded, set global expanded # Otherwise, set global callpased self.__unsub_global_expand() if menu_context.expand_model.as_bool: self.expand_model.set_value(True) else: expand = False for menu_context in self.__menu_context.values(): if menu_context.expand_model.as_bool: expand = True break self.expand_model.set_value(expand) self.__sub_global_expand() _menu_context.expanded_sub = _menu_context.expand_model.subscribe_value_changed_fn(__on_toggle_expand) self.__sub_global_expand() # When stage opened, rebuild the root menu def on_usd_context_event(event: omni.usd.StageEventType): if event.type == int(omni.usd.StageEventType.OPENED): camera_path = self.__ensure_valid_camera(viewport_api, viewport_api.camera_path) if camera_path: viewport_api.camera_path = camera_path menu_context = self.__menu_context.get(viewport_api_id) if menu_context: menu_context.root_menu.invalidate() menu_context.settings_menu.invalidate() _menu_context.stage_sub = viewport_api.usd_context.get_stage_event_stream().create_subscription_to_pop( on_usd_context_event, name="Viewport MenuBar CameraMenuContainer" ) # Clear out this reference to validate its not being held or used by any callback _menu_context = None def __render_settings_changed(self, camera_path: Sdf.Path, resolution: Tuple[int, int], viewport_api): # The Viewport may have switched to a new camera before out camera list was dirtied context = self.__menu_context[viewport_api.id] if context.camera_to_menu.get(camera_path) is None: # Rebuild but don't check camera validity; the Viewport is sending us the path it is rendering with self.__rebuild_cameras(viewport_api, False) self.__camera_changed(camera_path, viewport_api) def __camera_clicked(self, camera_path: Sdf.Path, viewport_api): context = self.__menu_context[viewport_api.id] if context.camera_path != camera_path: SetViewportCameraCommand(camera_path, viewport_api).do() return # Force the check state back on as it's being toggled off async def force_check(id): selected_cam_item = self.__menu_context[id].selected_camera_item if selected_cam_item and not selected_cam_item.checked: selected_cam_item.checked = True self.__force_check_task_or_future = run_coroutine(force_check(viewport_api.id)) def __camera_changed(self, camera_path: Sdf.Path, viewport_api): context = self.__menu_context[viewport_api.id] if context.camera_path == camera_path: cam_item = context.camera_to_menu.get(camera_path) if cam_item and not cam_item.checked: cam_item.checked = True return # Save the current state now context.camera_path = camera_path # Uncheck anything that is currently selected selected_cam_item = context.selected_camera_item if selected_cam_item: selected_cam_item.checked = False selected_cam_item = None # There is also chance the Camera was changed to an item that doesn't exist cam_item = context.camera_to_menu.get(camera_path) if cam_item: context.selected_camera_item = cam_item # And reset the check state on the new selection cam_item.checked = True # Update the root menu item if context.delegate: context.delegate.text = get_camera_display(camera_path, viewport_api.stage) # Toggle the cam collection marker accordingly if context.camera_collection: context.camera_collection.checked = str(camera_path) not in SESSION_CAMERAS # Need to update the lock item to new camera self.__build_lock_item(viewport_api, camera_path) # Update the active Camera's property widgets by rebuilding them if context: context.settings_menu.invalidate() def __build_lock_item(self, viewport_api, camera_path: Sdf.Path): stage = viewport_api.stage # Lock menu sub is always destroyed context = self.__menu_context.get(viewport_api.id, None) context.lock_menu_sub = None # Possibly no path, so clear any state if not camera_path: self.__lock_models = {} if context and context.delegate: context.delegate.model = None context.delegate.camera_path = None return context.delegate.camera_path = camera_path lock_model = self.__get_lock_model(stage, camera_path) if context and context.delegate: context.delegate.model = lock_model if lock_model: context.lock_menu_sub = lock_model.subscribe_value_changed_fn(lambda m, api=viewport_api: self._on_lock_changed(m, api)) def __get_lock_model(self, stage: Usd.Stage, camera_path: Sdf.Path): if camera_path not in self.__lock_models: if camera_path.pathString in ("/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"): return None # Lock - Should probably use meta-data, but that needs to be added into allowed-metadata schema # self.__lock_models[camera_path] = USDMetadataModel(stage, camera_path, CAMERA_LOCK_NAME) self.__lock_models[camera_path] = USDAttributeModel(stage, camera_path, CAMERA_LOCK_NAME) return self.__lock_models.get(camera_path) def __get_session_camera_paths(self, stage: Usd.Stage): session_camera_paths = [Sdf.Path(path_str) for path_str in SESSION_CAMERAS] if stage: session_camera_paths = [path for path in session_camera_paths if stage.GetPrimAtPath(path)] return session_camera_paths def _build_cameras(self, viewport_api, session_cameras: bool, ui_shown: bool = False, force_build: bool = False): """Build the menu with the list of the cameras""" context = self.__menu_context.get(viewport_api.id, None) if (not session_cameras) and (not force_build): camera_collection = context.camera_collection if camera_collection and not camera_collection.shown and not camera_collection.teared: return if session_cameras: camera_list = self.__get_session_camera_paths(viewport_api.stage) elif not context.camera_list.is_dirty: # If nothing changed, menu should be up-to-date return else: def sorting_key(sdf_path: Sdf.Path): # Sort based on parentPath/displayName which may lead to an invalid Sdf.Path durring AppendChild display_name = get_camera_display(sdf_path, viewport_api.stage) return f"{sdf_path.GetParentPath().pathString}/{display_name}".lower() camera_list = context.camera_list.camera_list camera_list = sorted(camera_list, key=sorting_key) camera_list = [path for path in camera_list if path.pathString not in SESSION_CAMERAS] if context.camera_collection: context.camera_collection.clear() stage = viewport_api.stage # Check that the current camera path is valid current_camera = viewport_api.camera_path valid_camera_path = self.__ensure_valid_camera(viewport_api, current_camera) if valid_camera_path and (valid_camera_path != current_camera): current_camera = valid_camera_path viewport_api.camera_path = current_camera # Clear any selected selected_cam_item now, its going to be an invalid item soon if context and context.selected_camera_item: context.selected_camera_item.checked = False context.selected_camera_item = None class MenuParentContext: def __enter__(self, *args, **kwargs): return context.camera_collection.__enter__(*args, **kwargs) if not session_cameras else None def __exit__(self, *args, **kwargs): return context.camera_collection.__exit__(*args, **kwargs) if not session_cameras else None with MenuParentContext(): if session_cameras or camera_list: for camera_path in camera_list: checked = current_camera == camera_path menu_item = self.__menu_item_type( camera_path, viewport_api, self.__get_lock_model(stage, camera_path), context.root_menu, lambda camera_path=camera_path: self.__camera_clicked(camera_path, viewport_api), self.__custom_camera_widget_delegate_manager ) context.camera_to_menu[camera_path] = menu_item if checked: context.selected_camera_item = menu_item else: NoCameraMenuItem() # Call camera_changed for the case the camera menu has been invalidated context.camera_path = None self.__camera_changed(current_camera, viewport_api) def __rebuild_cameras(self, viewport_api, check_validity: bool = False, removed_camera: Sdf.Path = None, added_camera: Sdf.Path = None): context = self.__menu_context.get(viewport_api.id, None) camera_collection = context.camera_collection if camera_collection and (camera_collection.shown or camera_collection.teared): # Force a rebuild of the stage cameras now camera_collection.invalidate() camera_collection.clear() self._build_cameras(viewport_api, False, True, True) if not check_validity: return camera_path = viewport_api.camera_path # If there was a single re-synch event where this camera was removed, and a new one added, go to added valid_camera_path = self.__ensure_valid_camera(viewport_api, added_camera if removed_camera == camera_path else camera_path) if valid_camera_path and (valid_camera_path != camera_path): viewport_api.camera_path = valid_camera_path def __ensure_valid_camera(self, viewport_api, camera_path: Sdf.Path): stage = viewport_api.stage if not stage: return camera_path def validate_camera(camera_path): if camera_path: prim = stage.GetPrimAtPath(camera_path) # OM-59033: It does not need the followed camera to be shown in the camera list by checking # _show_camera_in_menu(prim) as follow user mode in live session needs this to switch # camera binding dynamically without adding the camera into camera list. if prim: return Sdf.Path(camera_path) return None # Check if the camera_path is actually a valid camera_path camera_path = validate_camera(camera_path) if camera_path: return camera_path # Check if the info is held in the stage metadata. try: # Wrap in a try-catch so failure reading metadata does not cascade to caller. camera_path = validate_camera(stage.GetMetadataByDictKey('customLayerData', 'cameraSettings:boundCamera')) if camera_path: return camera_path except Tf.ErrorException as e: carb.log_error(f"Error reading Usd.Stage's boundCamera metadata {e}") # Fallback to implicit Perspective if possible (it is deterministic) camera_path = validate_camera('/OmniverseKit_Persp') if camera_path: return camera_path # Finally, try an pass the first valid camera in the list context = self.__menu_context[viewport_api.id] if context and context.camera_list: for known_camera in context.camera_list.camera_list: camera_path = validate_camera(known_camera) if camera_path: return camera_path return None def _build_camera_collections(self, viewport_context, root: ui.Menu): viewport_api = viewport_context.get("viewport_api") context = self.__menu_context.get(viewport_api.id, None) if context.camera_list: context.camera_list.destroy() context.camera_list = _CameraList(viewport_api.stage, partial(self.__rebuild_cameras, viewport_api, True)) # Clear out the Camera-path to MenuItem mapping context.camera_to_menu = {} # Verify current camera exists, changing it if it does not camera_path = viewport_api.camera_path valid_camera_path = self.__ensure_valid_camera(viewport_api, camera_path) if valid_camera_path and (valid_camera_path != camera_path): camera_path = valid_camera_path viewport_api.camera_path = camera_path # Order views session_cameras = self.__get_session_camera_paths(viewport_api.stage) show_stage_cameras = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showStageCameras") if show_stage_cameras: tearable = menu_is_tearable("omni.kit.viewport.menubar.camera.Cameras") context.camera_collection = ui.MenuItemCollection( "Cameras", checkable=True, checked=camera_path not in session_cameras, delegate=ViewportMenuDelegate(), shown_changed_fn=partial(self._build_cameras, viewport_api, False), tearable=tearable, hide_on_click=False ) def reset_checked(): context.camera_collection.checked = str(viewport_api.camera_path) in SESSION_CAMERAS context.camera_collection.set_triggered_fn(reset_checked) # XXX: This isn't sticking from the usage in constructor context.camera_collection.tearable = tearable self._build_cameras(viewport_api, True) ui.Separator() def _build_create_camera(self, viewport_context, root: ui.Menu): viewport_api = viewport_context.get("viewport_api") ui.MenuItem( "Create from View", delegate=ViewportMenuDelegate(icon_name="Add"), triggered_fn=lambda *args, **kwargs: self._create_from_view(viewport_api), hide_on_click=False ) def _build_menu(self, viewport_context): """Build the first level menu""" # Create a weak-reference to the active Camera menu; this will be passed to registered build functions viewport_api = viewport_context.get("viewport_api") context = self.__menu_context.get(viewport_api.id, None) cam_menu = weakref.proxy(context.root_menu) context.camera_path = viewport_api.camera_path # Need to watch for external changes to Viewport's camera, this is delivered in a render-settings change. if context.render_settings_changed_sub: context.render_settings_changed_sub.destroy() context.render_settings_changed_sub = None context.render_settings_changed_sub = viewport_api.subscribe_to_render_settings_change(self.__render_settings_changed) if context and context.delegate: context.delegate.model = None context.delegate.camera_path = None self.__lock_models = {} self.__build_lock_item(viewport_api, context.camera_path) # Active camera if context.camera_path: text = get_camera_display(context.camera_path, viewport_api.stage) else: text = self.name context.root_menu.text = text # Menu items self._create_menu_item_fns.sort(key=lambda item: item[1]) for (create_fn, order) in self._create_menu_item_fns: create_fn(viewport_context, cam_menu) # The rest of the menu on the case someone wants to put custom stuff if self._children: for child in self._children: child.build_fn(viewport_context) def _build_expand(self, viewport_context) -> None: # This menu has the number of widgets on the right side. # Check if the widgets are expanded viewport_api = viewport_context.get("viewport_api") context = self.__menu_context[viewport_api.id] stage = viewport_api.stage camera_path = viewport_api.camera_path context.settings_items = [] if camera_path: locked = self.__lock_models[camera_path].as_bool if camera_path in self.__lock_models and self.__lock_models[camera_path] else False enabled = not locked show_manual_exposure = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showManualExposure") if show_manual_exposure: context.settings_items.append( CameraLens( USDFloatAttributeModel(stage, camera_path, "focalLength", draggable=True), enabled=enabled, ) ) ui.MenuItem("", delegate=SeparatorDelegate()) context.settings_items.append( CameraFocalDistance( USDFloatAttributeModel(stage, camera_path, "focusDistance"), viewport_context, enabled=enabled, ) ) ui.MenuItem("", delegate=SeparatorDelegate()) context.settings_items.append( CameraFStop( USDFloatAttributeModel(stage, camera_path, "fStop"), enabled=enabled, ) ) show_auto_exposure = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showAutoExposure") if show_auto_exposure: if show_manual_exposure: ui.MenuItem("", delegate=SeparatorDelegate()) context.settings_items.append(CameraAutoExposure(None, enabled=enabled)) if camera_path in self.__lock_models and self.__lock_models[camera_path]: self._on_lock_changed(self.__lock_models[camera_path], viewport_api) def _create_from_view(self, viewport_api): omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) def _on_lock_changed(self, model: ui.AbstractValueModel, viewport_api) -> None: is_locked = model.as_bool settings_items = self.__menu_context[viewport_api.id].settings_items for setting in settings_items: setting.enabled = not is_locked def _on_menu_collection_triggered(self, menu: ui.MenuItemCollection, checked: bool): # Revert status here to keep checked status no changing when clicked menu.checked = not checked def __sub_global_expand(self): # Watch for the carb setting, for now treat it as global state and apply to all Viewports def __on_toggle_global_expand(*args, **kwargs): expanded = self.expand_model.as_bool for menu_context in self.__menu_context.values(): menu_context.expand_model.set_value(expanded) self.__expanded_sub = self.expand_model.subscribe_value_changed_fn(__on_toggle_global_expand) def __unsub_global_expand(self): self.__expanded_sub = None
38,301
Python
43.641026
144
0.626119
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/single_camera_menu_item.py
import abc from typing import Optional, Callable import carb import omni.ui as ui from typing import Optional, Callable from pxr import Sdf from omni.kit.viewport.menubar.core import ViewportMenuDelegate, LabelMenuDelegate from ..camera_widget_delegate_manager import CameraWidgetDelegateManager from ..utils import get_camera_display class SingleCameraMenuItemBase(ui.MenuItem): """ A single menu item represent a single camera in the camera list """ def __init__( self, camera_path: Sdf.Path, viewport_api, lock_model, root: ui.Menu, triggered_fn: Callable, widget_delegate_manager: CameraWidgetDelegateManager ): self._lock_model = lock_model self.__root = root self.__camera_path = camera_path self.__viewport_api = viewport_api self.__lock_button: Optional[ui.Button] = None self.__lock_model_sub = None self.__options_button = None self.__widget_delegate_manager = widget_delegate_manager super().__init__( get_camera_display(camera_path, viewport_api.stage), checkable=True, checked=viewport_api.camera_path == camera_path, hide_on_click=False, triggered_fn=triggered_fn, delegate=ViewportMenuDelegate( force_checked=False, build_custom_widgets=lambda delegate, item: self._build_menuitem_widgets() ), ) @property def camera_path(self): return self.__camera_path @property def viewport_api(self): return self.__viewport_api def destroy(self): if self.__widget_delegate_manager: self.__widget_delegate_manager.on_parent_destroyed(id(self), False) self.__widget_delegate_manager = None self.__options_button = None super().destroy() self.__lock_model_sub = None def __build_custom_widgets(self): if not self.__widget_delegate_manager: return try: self.__widget_delegate_manager.build_widgets( id(self), self.__viewport_api, self.__camera_path, False ) except Exception as e: carb.log_error(f"Failed to build widget: {str(e)}") def _build_menuitem_widgets(self): """Build additional buttons in the camera menu item""" ui.Spacer(width=10) with ui.VStack(content_clipping=1, width=0): # Button to select camera self.__options_button = ui.Button( style_type_name_override="Menu.Item.Button", name="OptionBox", width=16, height=16, image_width=16, image_height=16, visible=self.checked, clicked_fn=self._option_clicked, ) if self._lock_model: # Button to toggle lock status with ui.VStack(content_clipping=1, width=0): self.__lock_button = ui.Button( style_type_name_override="Menu.Item.Button", name=self.__get_lock_button_name(), width=16, height=16, image_width=16, image_height=16, clicked_fn=self.__toggle_camera_lock, ) self.__lock_model_sub = self._lock_model.subscribe_value_changed_fn(self._on_lock_changed) self.__build_custom_widgets() @abc.abstractmethod def _option_clicked(self): """Function to implement when the option is clicked. Used by RTX Remix""" pass def __toggle_camera_lock(self): self._lock_model.set_value(not self._lock_model.as_bool) self.__lock_button.name = self.__get_lock_button_name() def _on_lock_changed(self, model: ui.AbstractValueModel) -> None: self.__lock_button.name = self.__get_lock_button_name() def __get_lock_button_name(self): return "CameraLocked" if self._lock_model.as_bool else "CameraUnlocked" def set_checked(self, checked: bool) -> None: self.checked = checked self.delegate.checked = checked # Only show options button when it is current camera self.__options_button.visible = checked class SingleCameraMenuItem(SingleCameraMenuItemBase): """ A single menu item represent a single camera in the camera list """ def _option_clicked(self): self.viewport_api.usd_context.get_selection().set_selected_prim_paths([self.camera_path.pathString], True) class NoCameraMenuItem(ui.MenuItem): """ A single menu item represent a no camera in the camera list """ def __init__(self): super().__init__( "No camera", hide_on_click=False, delegate=LabelMenuDelegate(enabled=False, width=120, alignment=ui.Alignment.CENTER), )
4,901
Python
33.041666
114
0.599878
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/lens.py
import asyncio from typing import Tuple, List from pxr import Usd, Sdf import omni.kit.app import omni.ui as ui from omni.ui import constant as fl from .camera_setting import AbstractCameraSetting from omni.kit.viewport.menubar.core import ( SeparatorDelegate, SliderMenuDelegate, ComboBoxMenuDelegate, USDAttributeModel, USDFloatAttributeModel, ComboBoxItem, ComboBoxModel, ) DEFAULT_LENS = [8, 15, 24, 28, 35, 50, 85, 105, 135, 200, (17, 35), (35, 70), (70, 200), (0, 300)] class _CameraLensModel(ComboBoxModel): """The camera lens model has all the lens""" def __init__(self, lens_model: USDFloatAttributeModel): self._values = DEFAULT_LENS self._lens_model = lens_model self.range: Tuple(float, float) = () texts = [] for value in self._values: if isinstance(value, int): texts.append(f"{value} mm") else: texts.append(f"{value[0]} - {value[1]} mm") self._lens_model.add_value_changed_fn(self.__on_lens_changed) super().__init__(texts, self._values, self.display) def destroy(self): super().destroy() self._lens_model.remove_value_changed_fn(self.__on_lens_changed) @property def display(self): lens = self._lens_model.as_float for value in self._values: if isinstance(value, int): if lens == float(value): self.range = (value, value) return value else: min = value[0] max = value[1] if lens <= max and lens >= min: self.range = (min, max) return value default = self._values[-1] return default def _on_current_item_changed(self, item: ComboBoxItem) -> None: if isinstance(item.value, int): self.range = (item.value, item.value) self._lens_model.set_value(float(item.value)) else: # Don't allow 0 for focalLength self.range = (max(0.00001, item.value[0]), item.value[1]) value = self._lens_model.as_float if value > self.range[1] or value < self.range[0]: self._lens_model.set_value(float(self.range[0])) def __on_lens_changed(self, model: ui.AbstractValueModel): # If current value still in current lens range, keep range no change value = self._values[self.current_index.as_int] if isinstance(value, int): if model.as_float == float(value): return elif float(value[0]) <= model.as_float and float(value[1]) >= model.as_float: return self.current_index.set_value(self._get_current_index_by_value(self.display)) class CameraLens(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, enabled: bool = True): self._lens_model = _CameraLensModel(model) self._sub = self._lens_model.subscribe_item_changed_fn(self._on_lens_changed) super().__init__(model, enabled=enabled) def destroy(self): self._lens_model.destroy() self._sub = None def _build_ui(self) -> List[ui.MenuDelegate]: self._lens_delegate = ComboBoxMenuDelegate( model=self._lens_model, height=26, icon_height=26, enabled=self._enabled, text=False, icon_name="Lens", tooltip="Camera Lens", use_in_menubar=True, ) ui.MenuItem("Lens", delegate=self._lens_delegate, identifier="viewport.camera.lens") self._separator = ui.MenuItem("", delegate=SeparatorDelegate()) self._zoom_delegate = SliderMenuDelegate(model=self._property_model, width=0, enabled=self._enabled, tooltip="Camera Zoom") self._zoom_menu = ui.MenuItem("Zoom", delegate=self._zoom_delegate, enabled=self._enabled, identifier="viewport.camera.zoom") async def __delay_init(): await omni.kit.app.get_app().next_update_async() self._on_lens_changed(self._lens_model, None) asyncio.ensure_future(__delay_init()) return [self._lens_delegate, self._zoom_delegate] def _on_lens_changed(self, model: _CameraLensModel, item: ComboBoxItem): range = self._lens_model.range if range[0] == range[1]: self._zoom_delegate.visible = False self._separator.visible = False else: self._zoom_delegate.visible = True self._separator.visible = True self._zoom_delegate.set_range(range[0], range[1])
4,640
Python
34.7
133
0.591379
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/fstop.py
from pxr import Usd, Sdf from typing import List import omni.ui as ui from omni.ui import constant as fl from .camera_setting import AbstractCameraSetting from omni.kit.viewport.menubar.core import SpinnerMenuDelegate, USDAttributeModel __all__ = ["CameraFStop"] class CameraFStop(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, enabled: bool = True): super().__init__(model, enabled=enabled) def destroy(self): pass def _build_ui(self) -> List[ui.MenuDelegate]: self._fstop_delegate = SpinnerMenuDelegate( model=self._property_model, min=0.0, max=22.0, step=0.1, height=26, enabled=self._enabled, text=False, icon_name="FStop", tooltip="Camera F Stop", icon_height=26, use_in_menubar=True, ) ui.MenuItem("F Stop", delegate=self._fstop_delegate, identifier="viewport.camera.f_stop") return [self._fstop_delegate]
1,032
Python
28.514285
97
0.617248
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/auto_exposure.py
from pxr import Usd, Sdf from typing import List import omni.ui as ui from omni.ui import constant as fl from .camera_setting import AbstractCameraSetting from omni.kit.viewport.menubar.core import ( CheckboxMenuDelegate, SpinnerMenuDelegate, SliderMenuDelegate, USDAttributeModel, SettingModel, ) SETTING_AUTO_EXPOSURE = "/rtx/post/histogram/enabled" SETTING_ISO = "/rtx/post/tonemap/filmIso" SETTING_WHITE_SCALE = "/rtx/post/histogram/whiteScale" __all__ = ["CameraAutoExposure", "SETTING_AUTOEXPOSURE", "SETTING_ISO", "SETTING_WHITE_SCALE"] class CameraAutoExposure(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, enabled: bool = True): self._auto_exposure_model = SettingModel(SETTING_AUTO_EXPOSURE) self._white_scale_model = SettingModel(SETTING_WHITE_SCALE) self._iso_model = SettingModel(SETTING_ISO) self._sub = self._auto_exposure_model.subscribe_value_changed_fn(self._on_auto_exposure_changed) super().__init__(model, enabled=enabled) def destroy(self): self._sub = None def _build_ui(self) -> List[ui.MenuDelegate]: self._auto_exposure_delegate = CheckboxMenuDelegate( model=self._auto_exposure_model, width=0, height=26, enabled=self._enabled, use_in_menubar=True ) ui.MenuItem("AE", delegate=self._auto_exposure_delegate, identifier="viewport.camera.auto_exposure") self._white_scale_item = ui.MenuItem( "", delegate=SliderMenuDelegate(model=self._white_scale_model, min=00, max=20, width=0), visible=self._auto_exposure_model.as_bool, ) self._iso_item = ui.MenuItem( "ISO", delegate=SpinnerMenuDelegate( model=self._iso_model, min=50, max=1600, height=26, use_in_menubar=True, ), visible=not self._auto_exposure_model.as_bool, identifier="viewport.camera.iso", ) return [self._auto_exposure_delegate, self._white_scale_item.delegate, self._iso_item.delegate] def _on_auto_exposure_changed(self, model: ui.AbstractValueModel) -> None: self._white_scale_item.visible = model.as_bool self._iso_item.visible = not model.as_bool
2,258
Python
37.948275
108
0.670062
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/camera_setting.py
import abc from pxr import Usd, Sdf from typing import List import omni.ui as ui from omni.kit.viewport.menubar.core import USDAttributeModel __all__ = ["AbstractCameraSetting"] class AbstractCameraSetting: def __init__(self, model: USDAttributeModel, enabled: bool = True): self._property_model = model self._enabled = enabled self._delegates = self._build_ui() @property def enabled(self) -> bool: return self._enabled @enabled.setter def enabled(self, value: bool) -> None: self._enabled = value for delegate in self._delegates: delegate.enabled = value @abc.abstractclassmethod def _build_ui(self) -> List[ui.MenuDelegate]: return []
740
Python
24.551723
71
0.654054
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/focal_distance.py
from .camera_setting import AbstractCameraSetting import omni.usd import omni.ui as ui from omni.ui import scene as sc from omni.ui import constant as fl import omni.kit.undo import omni.kit.app import omni.kit.commands from omni.kit.viewport.menubar.core import SpinnerMenuDelegate, IconMenuDelegate, USDAttributeModel import carb from pxr import Usd, Sdf, Gf import asyncio import weakref import math from typing import List __all__ = ["CamFocalData", "FocusClickGesture", "FocusDragGesture", "PreventOthers", "ViewportClickManipulator", "FocalPickerScene", "CameraFocalDistance"] class CamFocalData: def __init__(self, cam_focal: "CameraFocalDistance", viewport_api): self.__main_cursor = None self.__cam_focal = cam_focal self.viewport_api = viewport_api self.__undo = False self.__auto_destruct = False try: import omni.kit.window.cursor self.__main_cursor = omni.kit.window.cursor.get_main_window_cursor() if self.__main_cursor: self.__main_cursor.override_cursor_shape(carb.windowing.CursorStandardShape.CROSSHAIR) except ImportError: pass def __del__(self): self.destroy() def destroy(self): if self.__undo: self.__undo = False omni.kit.undo.end_group() if self.__main_cursor: self.__main_cursor.clear_overridden_cursor_shape() self.__main_cursor = None if self.__cam_focal: self.__cam_focal._destroy_scene() self.__cam_focal = False self.viewport_api = None def focus_query_completed(self, prim_path: str, world_space_pos, *args): try: viewport_api = self.viewport_api if prim_path and world_space_pos and viewport_api: cam_path = viewport_api.camera_path cam_prim = viewport_api.stage.GetPrimAtPath(cam_path) if not cam_prim: carb.log_error(f'Could not get camera prim at "{cam_path}"') return # Compute world-space camera position to get distance world_space_camera = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0)) distance = (Gf.Vec3d(*world_space_pos) - world_space_camera).GetLength() if math.isfinite(distance): # Set to the focusDistance attribute on the Camera focus_attr = cam_prim.GetAttribute('focusDistance') # Start an undo-group in case of a drag if not self.__undo: self.__undo = True omni.kit.undo.begin_group() omni.kit.commands.execute('ChangeProperty', prop_path=focus_attr.GetPath(), value=distance, prev=focus_attr.Get() if focus_attr else None) # XXX: Setting to change center of interest TOO ? except Exception: pass finally: if self.__auto_destruct: self.__auto_destruct = None self.destroy() def set_focus_position(self, ndc_mouse, auto_destruct: bool = True): mouse, viewport_api = self.viewport_api.map_ndc_to_texture_pixel(ndc_mouse) if mouse and viewport_api: self.__auto_destruct = auto_destruct viewport_api.request_query(mouse, self.focus_query_completed, query_name='omni.kit.viewport.menubar.camera.FocusQuery') elif auto_destruct: self.destroy() class FocusClickGesture(sc.ClickGesture): def __init__(self, cam_focal_data: CamFocalData, *args, **kwargs): super().__init__(*args, **kwargs) self.__cam_focal_data = cam_focal_data def on_ended(self, *args, **kwargs): if self.state != sc.GestureState.CANCELED: self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse) class FocusDragGesture(sc.DragGesture): def __init__(self, cam_focal_data: CamFocalData, *args, **kwargs): super().__init__(*args, **kwargs) self.__cam_focal_data = cam_focal_data def on_changed(self, *args, **kwargs): self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse, False) def on_ended(self, *args, **kwargs): if self.state != sc.GestureState.CANCELED: self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse) class PreventOthers(sc.GestureManager): '''Class to prevent any gestures (like selection) from interfering with the focus pick''' def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if isinstance(gesture, FocusDragGesture): return False if isinstance(gesture, FocusClickGesture): return False return True class ViewportClickManipulator(sc.Manipulator): def __init__(self, cam_focal_data: CamFocalData, mouse_button: int = 0, *args, **kwargs): super().__init__(*args, **kwargs) self.__gestures = [FocusDragGesture(cam_focal_data, mouse_button=mouse_button, manager=PreventOthers()), FocusClickGesture(cam_focal_data, mouse_button=mouse_button, manager=PreventOthers())] self.__transform = None def __del__(self): self.destroy() def on_build(self): # Need to hold a reference to this or the sc.Screen would be destroyed when out of scope self.__transform = sc.Transform() with self.__transform: self.__screen = sc.Screen(gestures=self.__gestures) def destroy(self): self.__gestures = None self.__screen = None if self.__transform: self.__transform.clear() self.__transform = None class FocalPickerScene: def __init__(self, cam_focal_data: CamFocalData, ui_frame): self.__ui_frame = ui_frame self.__manip = None self.__scene = None with ui_frame: # Need to insert a stack to get content_clipping and block events from going below us self.__container = ui.VStack(content_clipping=True) with self.__container: self.__scene = sc.SceneView() with self.__scene.scene: self.__manip = ViewportClickManipulator(cam_focal_data) def __del__(self): self.destroy() def destroy(self): manip, self.__manip = self.__manip, None if manip: manip.destroy() scene, self.__scene = self.__scene, None if scene: scene.destroy() container, self.__container = self.__container, None if container: container.clear() container.destroy() # Clear ui.Frame, but kep it alive for next click ui_frame, self.__ui_frame = self.__ui_frame, None if ui_frame: ui_frame.clear() class CameraFocalDistance(AbstractCameraSetting): def __init__(self, model: USDAttributeModel, viewport_context, enabled: bool = True): self.__registered_scene = None self.__viewport_api = viewport_context.get("viewport_api") self.__ui_get_frame = viewport_context.get("layer_provider") super().__init__(model, enabled=enabled) def destroy(self): self.__viewport_api = None self.__ui_get_frame = None self._destroy_scene() def _build_ui(self) -> List[ui.MenuDelegate]: self._focal_delegate = SpinnerMenuDelegate( model=self._property_model, height=26, enabled=self._enabled, text=False, icon_name="FocalDistance", tooltip="Camera Focal Distance", icon_height=26, use_in_menubar=True, ) ui.MenuItem("Focal Distance", delegate=self._focal_delegate, identifier="viewport.camera.focal_distance") self._sample_delegate = IconMenuDelegate(name="Sample", height=26, has_triangle=False, enabled=self._enabled, tooltip="Sample Focal Distance") ui.MenuItem("Sample", delegate=self._sample_delegate, triggered_fn=self._sample, enabled=self._enabled, identifier="viewport.camera.sample") return [self._focal_delegate, self._sample_delegate] def _sample(self): if self.__registered_scene: # stop sample self._destroy_scene() elif self._enabled: # start sample asyncio.ensure_future(self.__create_focus_picker_scene()) async def __create_focus_picker_scene(self): await omni.kit.app.get_app().next_update_async() self.__destroy_scene_sync() self.__registered_scene = FocalPickerScene(CamFocalData(weakref.proxy(self), self.__viewport_api), self.__ui_get_frame.get_frame("omni.kit.viewport.menubar.camera.FocalPickerScene")) def __destroy_scene_sync(self): if self.__registered_scene: self.__registered_scene.destroy() self.__registered_scene = None def _destroy_scene(self): # Destroy on next event async def ui_async_destroy(): await omni.kit.app.get_app().next_update_async() self.__destroy_scene_sync() asyncio.ensure_future(ui_async_destroy())
9,444
Python
37.868313
155
0.606417
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/expand_menu_item.py
from typing import Dict, Optional import omni.ui as ui from omni.ui import constant as fl class _ExpandButtonDelegate(ui.MenuDelegate): """Simple button with left arrow""" def __init__(self, expanded: bool, **kwargs): self._expanded = expanded self.__icon: Optional[ui.Widget] = None super().__init__(**kwargs) def build_item(self, item: ui.MenuHelper): icon_type = "Menu.Item.Icon" self.__icon = ui.ImageWithProvider( style_type_name_override=icon_type, name="Expand", checked=self._expanded, width=20, height=30, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, ) @property def checked(self) -> bool: return self._expanded @checked.setter def checked(self, value: bool): self._expanded = value if self.__icon: self.__icon.checked = value class ExpandMenuItem(ui.MenuItem): def __init__(self, expand_model): self.__model = expand_model super().__init__( "Expand", delegate=_ExpandButtonDelegate(self.__model.as_bool), triggered_fn=lambda: self.__model.set_value(not self.__model.as_bool), identifier="viewport.camera.expand", ) @property def checked(self): return self.delegate.checked @checked.setter def checked(self, value: bool): self.delegate.checked = value
1,508
Python
27.471698
86
0.576923
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_api.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__ = ['TestAPI'] import omni.kit.test import functools from omni.kit.test import AsyncTestCase from unittest.mock import patch, call from omni.kit.viewport.menubar.camera import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.camera import SingleCameraMenuItem as _SingleCameraMenuItem from omni.kit.viewport.menubar.camera import SingleCameraMenuItemBase as _SingleCameraMenuItemBase from omni.kit.viewport.menubar.camera.camera_menu_container import CameraMenuContainer as _CameraMenuContainer class TestAPI(AsyncTestCase): async def test_get_instance(self): extension = _get_menubar_extension() self.assertIsNotNone(extension) async def test_register_custom_menu_item_type(self): def _single_camera_menu_item(*args, **kwargs): class SingleCameraMenuItem(_SingleCameraMenuItemBase): pass return SingleCameraMenuItem(*args, **kwargs) extension = _get_menubar_extension() self.assertIsNotNone(extension) try: with patch.object(_CameraMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_camera_menu_item) extension.register_menu_item_type( fn ) self.assertEqual(1, set_menu_item_type_mock.call_count) self.assertEqual(call(fn), set_menu_item_type_mock.call_args) finally: extension.register_menu_item_type(None) async def test_register_regular_menu_item_type(self): def _single_camera_menu_item(*args, **kwargs): return _SingleCameraMenuItem(*args, **kwargs) extension = _get_menubar_extension() self.assertIsNotNone(extension) try: with patch.object(_CameraMenuContainer, "set_menu_item_type") as set_menu_item_type_mock: fn = functools.partial(_single_camera_menu_item) extension.register_menu_item_type( fn ) self.assertEqual(1, set_menu_item_type_mock.call_count) self.assertEqual(call(fn), set_menu_item_type_mock.call_args) finally: extension.register_menu_item_type(None)
2,704
Python
40.615384
110
0.677515
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/__init__.py
from .test_api import * from .test_commands import * from .test_ui import * from .test_focal_distance import *
111
Python
21.399996
34
0.738739
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_ui.py
from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.menubar.camera import get_instance as _get_menubar_extension from omni.kit.viewport.menubar.camera import SingleCameraMenuItemBase from omni.kit.viewport.utility import get_active_viewport, get_active_viewport_window import omni.usd import omni.kit.app import functools import omni.kit.test import omni.appwindow import carb.input from pathlib import Path import omni.ui as ui import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import unittest from pxr import Sdf, Usd, UsdGeom CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 850, 300 class ToggleExpansionState(): def __init__(self): self.__settings = carb.settings.get_settings() self.__key = "/persistent/exts/omni.kit.viewport.menubar.camera/expand" self.__restore_value = self.__settings.get(self.__key) def set(self, value: bool): self.__settings.set(self.__key, value) def __del__(self): self.__settings.set(self.__key, self.__restore_value) class TestCameraMenuWindow(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def test_general(self): await self.finalize_test(golden_img_name="menubar_camera.png") async def test_lock(self): viewport = get_active_viewport() viewport.camera_path = UsdGeom.Camera.Define(viewport.stage, '/NewCamera').GetPath() path = Sdf.Path(viewport.camera_path).AppendProperty("omni:kit:cameraLock") omni.kit.commands.execute('ChangePropertyCommand', prop_path=path, value=True, prev=False, timecode=Usd.TimeCode.Default(), type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool) try: await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_name="menubar_camera_locked.png") finally: omni.kit.commands.execute('ChangePropertyCommand', prop_path=path, value=False, prev=False, timecode=Usd.TimeCode.Default(), type_to_create_if_not_exist=Sdf.ValueTypeNames.Bool) async def test_collapsed(self): """Test collapse/expand functionality of additional camera properties""" settings = carb.settings.get_settings() expand_state = ToggleExpansionState() try: expand_state.set(False) await self.finalize_test(golden_img_name="menubar_camera_collpased.png") expand_state.set(True) await self.finalize_test(golden_img_name="menubar_camera_expanded.png") finally: del expand_state await self.wait_n_updates() async def test_resize_4_in_1(self): restore_width = self._viewport_window.width expand_state = ToggleExpansionState() expand_state.set(True) await self.wait_n_updates(2) try: # resize 1: contract settings self._viewport_window.width = 200 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_contract_settings.png") # resize 2: contract text self._viewport_window.width = 60 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_contract_text.png") # resize 3 : expand text self._viewport_window.width = 200 await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_expand_text.png") # resize 4 : expand settings self._viewport_window.width = restore_width await self.wait_n_updates(5) await self.finalize_test(golden_img_name="menubar_camera_resize_expand_settings.png") finally: del expand_state self._viewport_window.width = restore_width await self.wait_n_updates() async def test_user_menu_item(self): def __create_first(viewport_context, root): ui.MenuItem("This is first custom menu item") def __create_second(viewport_context, root): ui.MenuItem("This is second custom menu item") expand_state = ToggleExpansionState() instance = omni.kit.viewport.menubar.camera.get_instance() try: instance.register_menu_item(__create_second, order=20) instance.register_menu_item(__create_first, order=10) expand_state.set(True) await self.__click_root_menu_item() await self.finalize_test(golden_img_name="menubar_camera_custom.png") await ui_test.emulate_mouse_click() expand_state.set(False) await self.__click_root_menu_item() await self.finalize_test(golden_img_name="menubar_camera_custom_collapsed.png") finally: await ui_test.emulate_mouse_click() instance.deregister_menu_item(__create_first) instance.deregister_menu_item(__create_second) del expand_state await self.wait_n_updates() async def __click_root_menu_item(self): # Enable mouse input app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) await ui_test.emulate_mouse_move(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() async def test_camera_menu_with_custom_type(self): menu_option_clicked = 0 def _single_camera_menu_item(*args, **kwargs): class SingleCameraMenuItem(SingleCameraMenuItemBase): def _option_clicked(self): nonlocal menu_option_clicked menu_option_clicked += 1 return SingleCameraMenuItem(*args, **kwargs) await self.__click_root_menu_item() self.assertEqual(0, menu_option_clicked) await ui_test.emulate_mouse_move(Vec2(140, 110)) await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(0, menu_option_clicked) extension = _get_menubar_extension() try: extension.register_menu_item_type( functools.partial(_single_camera_menu_item) ) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(1, menu_option_clicked) finally: extension.register_menu_item_type(None) # Call it again to hide popup menu window await self.__click_root_menu_item() async def test_external_cam_change(self): # Get the Viewport and change the active camera viewport = get_active_viewport() orig_cam_path = viewport.camera_path new_cam_path = Sdf.Path('/OmniverseKit_Top') self.assertNotEqual(orig_cam_path, new_cam_path) try: viewport.camera_path = new_cam_path # Change should be reflected in UI await self.wait_n_updates(10) await self.finalize_test(golden_img_name="menubar_camera_external_cam_change.png") finally: viewport.camera_path = orig_cam_path class TestCameraMenuHideStageCameras(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showStageCameras", False) # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showStageCameras", True) await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def __click_root_menu_item(self): # Enable mouse input app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) await ui_test.emulate_mouse_move(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() async def test_hide_stage_cameras(self): """Test hide functionality of stage cameras properties""" await self.__click_root_menu_item() try: await self.finalize_test(golden_img_name="menubar_hide_stage_cameras.png") finally: await self.wait_n_updates() await self.__click_root_menu_item() class TestCameraMenuHideManualExposure(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() context = omni.usd.get_context() carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showManualExposure", False) # Create a new stage to show camera parameters await context.new_stage_async() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): carb.settings.get_settings().set("/exts/omni.kit.viewport.menubar.camera/showManualExposure", True) await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def test_hide_manual_exposure(self): """Test hiding of manual exposure camera properties""" try: await self.finalize_test(golden_img_name="menubar_hide_manual_exposure.png") finally: await self.wait_n_updates()
11,466
Python
36.230519
113
0.643293
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_focal_distance.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 carb.input from omni.ui.tests.test_base import OmniUiTest import omni.usd from pxr import Gf, UsdGeom import omni.kit.ui_test as ui_test from omni.kit.viewport.utility import get_active_viewport_window from omni.kit.ui_test import Vec2 TEST_WIDTH, TEST_HEIGHT = 850, 300 class TestFocalDistance(OmniUiTest): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, '/World').GetPrim()) await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) await self.wait_n_updates() self._viewport_window = get_active_viewport_window() self._viewport_window.position_x = 0 self._viewport_window.position_y = 0 async def tearDown(self): self.usd_context = None self.stage = None async def test_cam_sample_focal_distance(self): # create a test camera cam_path = '/World/TestCamera' cam_prim = UsdGeom.Camera.Define(self.stage, cam_path).GetPrim() omni.kit.commands.execute("TransformPrimSRTCommand", path=cam_path, new_translation=Gf.Vec3d(0, 0, 15)) focus_dist_attr = cam_prim.GetAttribute('focusDistance') focus_dist_attr.Set(400) # create a cube as the sample sample_path = '/World/Cube' UsdGeom.Cube.Define(self.stage, sample_path) await self.wait_n_updates(300) # set the test cam to be the viewport cam app_window = omni.appwindow.get_default_app_window() app_window.set_input_blocking_state(carb.input.DeviceType.MOUSE, None) # open camera list await ui_test.emulate_mouse_move(Vec2(40, 40)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # cameras await ui_test.emulate_mouse_move(Vec2(40, 75)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # choose test camera await ui_test.emulate_mouse_move(Vec2(200, 75)) await ui_test.emulate_mouse_click() await self.wait_n_updates() # decrease the focal distance by 3 await ui_test.emulate_mouse_move(Vec2(340, 50)) for _ in range(3): await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() self.assertEqual(focus_dist_attr.Get(), 397) # click focal sample button to enable sample picker await ui_test.emulate_mouse_move(Vec2(370, 40)) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates() # click the sample object (cube) to reset the focal distance await ui_test.emulate_mouse_move(Vec2(420, 150)) await self.wait_n_updates() await ui_test.emulate_mouse_click() await self.wait_n_updates(10) self.assertAlmostEqual(focus_dist_attr.Get(), 14, places=2)
3,524
Python
37.315217
111
0.667423
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/tests/test_commands.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__ = ['TestCommands'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.usd from pxr import Gf, Sdf, UsdGeom import omni.kit.undo import carb # Test that the Viewport-level commands reach the proper methods class TestViewportAPI: def __init__(self, usd_context_name, cam_path: str = None): self.usd_context_name = usd_context_name self.usd_context = omni.usd.get_context() self.stage = self.usd_context.get_stage() self.__camera_path = cam_path @property def camera_path(self): return self.__camera_path @camera_path.setter def camera_path(self, cam_path): self.__camera_path = cam_path class TestCommands(AsyncTestCase): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, '/World').GetPrim()) async def tearDown(self): self.usd_context = None self.stage = None async def test_duplicate_camera(self): def get_num_xform_ops(cam: UsdGeom.Camera): xform_ops = cam.GetOrderedXformOps() return len(xform_ops) if xform_ops else 0 cam_path = '/World/TestCamera' new_camera = UsdGeom.Camera.Define(self.stage, '/World/TestCamera') # This camera has no xformOps self.assertEqual(0, get_num_xform_ops(new_camera)) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path) # Should have duplicated to '/World/Camera' dup_camera_path = '/World/Camera' dup_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(dup_camera_path)) # Validate the new camera self.assertIsNotNone(dup_camera) self.assertTrue(bool(dup_camera)) # Should have 3 xformOps, in order to honor the defaut camera roation order self.assertEqual(3, get_num_xform_ops(dup_camera)) # Test duplication of implicit camera omni.kit.commands.execute("DuplicateCameraCommand", camera_path='/OmniverseKit_Persp') # Test both of these meta-data entries are true for an implicit Camera self.assertTrue(omni.usd.editor.is_hide_in_stage_window(self.stage.GetPrimAtPath('/OmniverseKit_Persp'))) self.assertTrue(omni.usd.editor.is_no_delete(self.stage.GetPrimAtPath('/OmniverseKit_Persp'))) num_xfops_1 = get_num_xform_ops(new_camera) # Should have duplicated to '/World/Camera_1' dup_camera_path = '/World/Camera_01' dup_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(cam_path)) # Validate the new camera self.assertIsNotNone(dup_camera) self.assertTrue(bool(dup_camera)) # Should have same number of xformOps now self.assertEqual(num_xfops_1, get_num_xform_ops(dup_camera)) # Test both of these meta-data entries are false after duplicating an implicit Camera self.assertFalse(omni.usd.editor.is_hide_in_stage_window(dup_camera.GetPrim())) self.assertFalse(omni.usd.editor.is_no_delete(dup_camera.GetPrim())) async def test_duplicate_camera_unlocked(self): cam_path = '/World/TestCamera' cam_lock = 'omni:kit:cameraLock' usd_camera = UsdGeom.Camera.Define(self.stage, '/World/TestCamera') prop = usd_camera.GetPrim().CreateAttribute(cam_lock, Sdf.ValueTypeNames.Bool, True) prop.Set(True) # Make sure the lock attribute is present and set to true self.assertTrue(usd_camera.GetPrim().GetAttribute(cam_lock).Get()) omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path) cam_path = '/World/Camera' # Should have duplicated to '/World/Camera' new_camera = UsdGeom.Camera(self.stage.GetPrimAtPath(cam_path)) # Validate the new camera self.assertIsNotNone(new_camera) self.assertTrue(bool(new_camera)) # Make sure the lock attribute wasn't copied over self.assertFalse(new_camera.GetPrim().GetAttribute(cam_lock).IsValid()) # Nothing should have affected the original self.assertTrue(usd_camera.GetPrim().GetAttribute(cam_lock).Get()) async def test_duplicate_camera_with_name(self): cam_path = '/World/TestCamera' UsdGeom.Camera.Define(self.stage, '/World/TestCamera') new_cam_path = '/World/TestDuplicatedCamera' omni.kit.commands.execute("DuplicateCameraCommand", camera_path=cam_path, new_camera_path=new_cam_path) # Should have duplicated to '/World/TestDuplicatedCamera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) # Undo the command omni.kit.undo.undo() # Camera should no longer be valid (its been deleted) self.assertFalse(bool(camera)) async def test_duplicate_viewport_camera(self): cam_path = '/World/TestCamera' UsdGeom.Camera.Define(self.stage, cam_path) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) # Should have duplicated to '/World/Camera' new_cam_path = '/World/Camera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) self.assertEqual(viewport_api.camera_path, new_cam_path) # Undo the command omni.kit.undo.undo() # Viewport should have been reset self.assertEqual(viewport_api.camera_path, cam_path) # Camera should no longer be valid (its been deleted) self.assertFalse(bool(camera)) async def __test_duplicate_viewport_camera_hierarchy(self, rot_order: str = None): settings = carb.settings.get_settings() try: default_prim = self.stage.GetDefaultPrim() root_path = default_prim.GetPath().pathString if default_prim else '' parent_paths = (f'{root_path}/Xform0', f'{root_path}/Xform0/Xform1') cam_path = f'{parent_paths[1]}/TestCamera' UsdGeom.Xform.Define(self.stage, parent_paths[0]) omni.kit.commands.execute("TransformPrimSRTCommand", path=parent_paths[0], new_translation=Gf.Vec3d(10, 10, 10)) UsdGeom.Xform.Define(self.stage, parent_paths[1]) omni.kit.commands.execute("TransformPrimSRTCommand", path=parent_paths[1], new_translation=Gf.Vec3d(10, 10, 10), new_rotation_euler=Gf.Vec3d(90, 0, 0)) UsdGeom.Camera.Define(self.stage, cam_path) omni.kit.commands.execute("TransformPrimSRTCommand", path=cam_path, new_translation=Gf.Vec3d(10, 10, 10), new_rotation_euler=Gf.Vec3d(90, 0, 0)) # Set the rotation order now to test that moving from an existing order to a new one works if rot_order: settings.set('/persistent/app/primCreation/DefaultCameraRotationOrder', rot_order) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api) # Should have duplicated to '/World/Camera' new_cam_path = f'{root_path}/Camera' camera = UsdGeom.Camera(self.stage.GetPrimAtPath(new_cam_path)) # Validate the new camera self.assertIsNotNone(camera) self.assertTrue(bool(camera)) self.assertEqual(viewport_api.camera_path, new_cam_path) src_xform = omni.usd.get_world_transform_matrix(self.stage.GetPrimAtPath(cam_path)) dst_xform = omni.usd.get_world_transform_matrix(self.stage.GetPrimAtPath(new_cam_path)) self.assertTrue(Gf.IsClose(src_xform, dst_xform, 1.0e-5)) if rot_order: self.assertTrue(f'xformOp:rotate{rot_order}' in camera.GetXformOpOrderAttr().Get()) finally: if rot_order: settings.destroy_item('/persistent/app/primCreation/DefaultCameraRotationOrder') async def test_duplicate_viewport_camera_hierarchy(self): await self.__test_duplicate_viewport_camera_hierarchy() async def test_duplicate_viewport_camera_hierarchy_with_order(self): '''Test duplictaing a camera that is nested in a transformed honors default camera rotation order''' await self.__test_duplicate_viewport_camera_hierarchy('XYZ') # Test again with a different order and also without a default prim await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() await self.__test_duplicate_viewport_camera_hierarchy('ZYX') async def test_set_viewport_camera(self): cam_path = '/World/TestCamera' cam_path2 = '/World/TestCamera2' UsdGeom.Camera.Define(self.stage, cam_path) UsdGeom.Camera.Define(self.stage, cam_path) viewport_api = TestViewportAPI(self.usd_context_name, cam_path) omni.kit.commands.execute("SetViewportCameraCommand", camera_path=cam_path2, viewport_api=viewport_api) # Should now be set to cam_path2 self.assertEqual(viewport_api.camera_path, cam_path2) # Undo the command omni.kit.undo.undo() # Should now be set to cam_path self.assertEqual(viewport_api.camera_path, cam_path)
10,059
Python
42.930131
163
0.672134
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/docs/index.rst
omni.kit.viewport.menubar.camera ################################# Camera Setting in Viewport MenuBar .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule:: omni.kit.viewport.menubar.camera :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members:
333
reStructuredText
15.699999
48
0.618619
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/PACKAGE-LICENSES/omni.kit.viewport.legacy_gizmos-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806