file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/tests/mock_utils.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import List import omni.kit.usd.layers as layers import omni.timeline import omni.ui import omni.usd from ..session_state import SessionState from ..sync_strategy import SyncStrategyDescriptor, SyncStrategyType, TimelineSyncStrategyExecutor from ..timeline_session import TimelineSession from ..timeline_session_role import TimelineSessionRoleType from ..ui_user_window import UserWindow def print_widget_tree(widget: omni.ui.Widget, level: int = 0): # Prints the widget tree to the console print(" " * level + str(widget.__class__.__name__)) for child in omni.ui.Inspector.get_children(widget): print_widget_tree(child, level + 1) # making sure context and timeline are unique _cnt = 0 # need to re-write this once we have mock live session joiner # for now, it hacks timeline to simulate joiner class MockTimelineSession(TimelineSession): def __init__( self, usd_context_name: str, session_user: layers.LiveSessionUser, session_state, role: TimelineSessionRoleType, hijack_timeline_fn, ): self._hijack_timeline_fn = hijack_timeline_fn super().__init__(usd_context_name, session_user, session_state, role) # hijack _do_change_role role inorder to hijack director timeline def _do_change_role(self, role_type: TimelineSessionRoleType): super()._do_change_role(role_type) self._hijack_timeline_fn(self) class MockJoiner: def __init__( self, main_timeline: omni.timeline.Timeline, user: layers.LiveSessionUser, sync_strategy_type: SyncStrategyType = SyncStrategyType.DIFFERENCE_LIMITED, ): # hijack director timeline for making sure `mock_timeline_session` the timeline could achieve the same state as the main timeline self.joiner = user self.mock_timeline_usd_context = omni.usd.create_context(f"test_another_timeline_contex_{self.joiner.user_id}") self.mock_timeline_usd_context.set_timeline(f"mock timeline {self.joiner.user_id}") self.mock_timeline = self.mock_timeline_usd_context.get_timeline() self.mock_director_timeline_name = f"mock director timeline: {user.user_id}" self.mock_director_timeline = omni.timeline.get_timeline_interface(self.mock_director_timeline_name) self.has_copied_from_main_timeline = False def hijack_timeline_fn(mock_timeline_session: MockTimelineSession): if mock_timeline_session.role_type != TimelineSessionRoleType.LISTENER: return self._copy_from_main_timeline(self.mock_timeline, main_timeline) mock_timeline_session.role._director_timeline = None mock_timeline_session.role._timeline_sync_executor._timeline = None omni.timeline.destroy_timeline(mock_timeline_session.role._timeline_name) mock_timeline_session.role._timeline_name = self.mock_director_timeline_name mock_timeline_session.role._timeline_sync_executor = TimelineSyncStrategyExecutor( SyncStrategyDescriptor(sync_strategy_type), self.mock_director_timeline ) # mock timeline session self.mock_session_state = SessionState() self.mock_timeline_session = MockTimelineSession( self.mock_timeline_usd_context.get_name(), self.joiner, self.mock_session_state, TimelineSessionRoleType.LISTENER, hijack_timeline_fn, ) self.mock_session_state.timeline_session = self.mock_timeline_session self.mock_session_state.add_users([self.joiner]) # mock window self.window = UserWindow(self.mock_session_state) self.window._window.title = f"Timeline Session Test {user.user_name}" def set_current_time(self, time: float) -> None: self.mock_timeline.set_current_time(time) def get_current_time(self) -> float: return self.mock_timeline.get_current_time() def get_time_codes_per_seconds(self) -> float: return self.mock_timeline.get_time_codes_per_seconds() def is_playing(self) -> bool: return self.mock_timeline.is_playing() def is_stopped(self) -> bool: return self.mock_timeline.is_stopped() def is_looping(self) -> bool: return self.mock_timeline.is_looping() def play(self) -> None: self.mock_timeline.play() def commit_received_update_timeline_events(self) -> None: self.mock_director_timeline.commit() def commit(self) -> None: self.mock_timeline.commit() def get_window_title(self) -> str: return self.window._window.title def destroy(self) -> None: self.window.destroy() self.mock_timeline_session.stop_session() self.mock_timeline.set_director(None) self.mock_timeline.stop() self.mock_timeline.commit() self.mock_timeline = None self.mock_director_timeline = None omni.timeline.destroy_timeline(self.mock_timeline_usd_context.get_timeline_name()) omni.timeline.destroy_timeline(self.mock_director_timeline_name) omni.usd.destroy_context(self.mock_timeline_usd_context.get_name()) self.mock_timeline_usd_context = None # simulate open main timeline from live layer def _copy_from_main_timeline(self, mock_timeline: omni.timeline.Timeline, main_timeline: omni.timeline.Timeline): if self.has_copied_from_main_timeline: return self.has_copied_from_main_timeline = True mock_timeline.set_end_time(main_timeline.get_end_time()) mock_timeline.set_start_time(main_timeline.get_start_time()) mock_timeline.set_time_codes_per_second(main_timeline.get_time_codes_per_seconds()) mock_timeline.commit() return mock_timeline # need to replace this session_watcher once we have mock live session joiner class MockJoinerManager: def __init__(self): self._joiners: List[MockJoiner] = [] def create_joiner( self, main_timeline: omni.timeline.Timeline, user_name: str, user_id: str, owner: layers.LiveSessionUser, sync_strategy_type: SyncStrategyType = SyncStrategyType.DIFFERENCE_LIMITED, ) -> MockJoiner: global _cnt cnt = _cnt _cnt += 1 joiner_id = len(self._joiners) mock_joiner = MockJoiner( main_timeline, layers.LiveSessionUser( f"{user_name}_{joiner_id}", f"{user_id}_{joiner_id}_test_cnt_{cnt}", "timeline live_session test" ), sync_strategy_type, ) # simulate session watcher mock_joiner.mock_session_state.add_users([owner]) for joiner in self._joiners: joiner.mock_session_state.add_users([mock_joiner.joiner]) mock_joiner.mock_session_state.add_users([joiner.joiner]) self._joiners.append(mock_joiner) return mock_joiner def destroy_joiners(self): for mock_joiner in self._joiners: mock_joiner.destroy() self._joiners = []
7,546
Python
37.116161
137
0.672012
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/tests/tests.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import unittest import asyncio from typing import List import carb import omni.kit.collaboration.presence_layer as pl import omni.kit.test import omni.kit.ui_test as ui_test import omni.kit.usd.layers as layers import omni.timeline import omni.timeline.live_session as ls from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi from pxr import Sdf, Usd # for clean up state from ..live_session_extension import _session_watcher as g_session_watcher from ..sync_strategy import SyncStrategyType from ..timeline_serializer import LOOPING_ATTR_NAME, PLAYSTATE_ATTR_NAME, TIME_ATTR_NAME, TIMELINE_PRIM_PATH from ..timeline_session import TimelineSession from ..ui_user_window import UserWindow from .mock_utils import MockJoiner, MockJoinerManager _fake_layer = None class TestTimeline(omni.kit.test.AsyncTestCase): async def setUp(self): self._app = omni.kit.app.get_app() self._usd_context = omni.usd.get_context() self._layers = layers.get_layers(self._usd_context) self._live_syncing = layers.get_live_syncing(self._usd_context) self._timeline = self._usd_context.get_timeline() self._end_time = 94874897 self._simulated_user_name = "test" self._simulated_user_id = "abcde" self._users = None self._presenter = None self._control_request = None self._want_control = False g_session_watcher.start() self._mock_joiner_manager = MockJoinerManager() # need to create new window for every test case self._window = UserWindow(ls.get_session_state()) self._window_title = "Timeline Session Test Owner" self._window._window.title = self._window_title async def tearDown(self): self._window.destroy() self._window = None self._mock_joiner_manager.destroy_joiners() self._mock_joiner_manager = None g_session_watcher.stop() if self._usd_context.get_stage(): await self._usd_context.close_stage_async() self._stage = None self._fake_layer.Clear() await self._reset_timeline() self._live_syncing.stop_all_live_sessions() self._layers.get_event_stream().pump() await self.wait(50) async def wait(self, frames=10): for _ in range(frames): await self._app.next_update_async() async def _reset_timeline(self): self._timeline.stop() self._timeline.clear_zoom() self._timeline.set_current_time(0.0) self._timeline.set_end_time(self._end_time) self._timeline.set_start_time(0.0) self._timeline.set_director(None) self._timeline.commit() async def _create_session(self): self._stage_url = "omniverse://__faked_omniverse_server__/test/test.usd" global _fake_layer if _fake_layer is None: _fake_layer = Sdf.Layer.New(Sdf.FileFormat.FindByExtension(".usd"), self._stage_url) self._fake_layer = _fake_layer self._stage = Usd.Stage.Open(self._fake_layer) await self._usd_context.attach_stage_async(self._stage) session = self._live_syncing.find_live_session_by_name(self._stage_url, "test") if not session: session = self._live_syncing.create_live_session("test", self._stage_url) self.assertTrue(session, "Failed to create live session.") await self._reset_timeline() self.assertTrue(self._live_syncing.join_live_session(session)) await self.wait() self.assertTrue(self._live_syncing.is_in_live_session()) presence_layer = pl.get_presence_layer_interface(self._usd_context) self.assertIsNotNone(presence_layer) self._presence_stage: Usd.Stage = presence_layer.get_shared_data_stage() self.assertIsNotNone(self._presence_stage) async def _simulate_user_join(self, user_name, user_id) -> layers.LiveSessionUser: user = layers.LiveSessionUser(user_name, user_id, "Create") await self._simulate_user_join_with_user_object(user) return user async def _simulate_user_join_with_user_object(self, user: layers.LiveSessionUser): # Access private variable to simulate user login. current_session = self._live_syncing.get_current_live_session() session_channel = current_session._session_channel() session_channel._peer_users[user.user_id] = user session_channel._send_layer_event( layers.LayerEventType.LIVE_SESSION_USER_JOINED, {"user_name": user.user_name, "user_id": user.user_id} ) await self.wait() @MockLiveSyncingApi async def test_state(self): state = ls.get_session_state() # Initial state, no live session session = ls.get_timeline_session() self.assertIsNone(session) self.assertIsNotNone(state) self.assertEqual(len(state.users), 0) # Create live session, test TimelineSession state.add_users_changed_fn(self._on_users_changed) await self._create_session() session = ls.get_timeline_session() self.assertTrue(session.is_running()) self.assertIsNotNone(session.live_session_user) self.assertIsNotNone(session.owner) self.assertIsNotNone(session.presenter) self.assertTrue(session.am_i_owner()) self.assertTrue(session.am_i_presenter()) self.assertEqual(session.owner_id, session.live_session_user.user_id) self.assertTrue(session.is_logged_user(session.live_session_user)) self.assertTrue(session.is_owner(session.live_session_user)) self.assertTrue(session.is_presenter(session.live_session_user)) self.assertEqual(len(session.get_request_controls()), 0) self.assertEqual(len(session.get_request_control_ids()), 0) self.assertTrue(session.is_sync_enabled()) self.assertIsNotNone(session.role) self.assertEqual(session.role_type, ls.TimelineSessionRoleType.PRESENTER) self.assertEqual(len(state.users), 1) self.assertEqual(state.users[0], session.live_session_user) self._assert_users_and_clear(1, session.live_session_user) # Join a new user new_user = await self._simulate_user_join(self._simulated_user_name, self._simulated_user_id) users_with_new_id = [user for user in state.users if user.user_id == self._simulated_user_id] self.assertEqual(len(users_with_new_id), 1) new_user_from_session = users_with_new_id[0] self._assert_users_and_clear(1, new_user_from_session) self.assertTrue(session.am_i_owner()) self.assertTrue(session.am_i_presenter()) self.assertFalse(session.is_owner(new_user_from_session)) self.assertFalse(session.is_presenter(new_user_from_session)) self.assertEqual(len(session.get_request_controls()), 0) # Timeline state is sent properly await self._test_timeline_send(session, state) # Make the new user a presenter session.add_presenter_changed_fn(self._on_presenter_changed) session.presenter = new_user_from_session await self.wait() # for timeline changes to become active self.assertEqual(self._presenter, new_user_from_session) # callback self.assertTrue(session.am_i_owner()) self.assertFalse(session.am_i_presenter()) self.assertFalse(session.is_owner(new_user_from_session)) self.assertTrue(session.is_presenter(new_user_from_session)) self.assertEqual(session.role_type, ls.TimelineSessionRoleType.LISTENER) # We are listeners, cannot change the timeline self.assertTrue(self._timeline.is_stopped()) # make sure synchronization does not interfere with the test self._timeline.set_current_time(50) self._timeline.play() self._timeline.commit() self.assertAlmostEqual(self._timeline.get_current_time(), 0) self.assertTrue(self._timeline.is_stopped()) # Control request session.add_control_request_changed_fn(self._on_control_request) session.request_control(True) await self.wait() self.assertEqual(self._control_request, session.live_session_user) # callback self.assertEqual(self._want_control, True) # callback self.assertEqual(len(session.get_request_controls()), 1) self.assertEqual(len(session.get_request_control_ids()), 1) self.assertTrue(session.live_session_user in session.get_request_controls()) self.assertTrue(session.live_session_user.user_id in session.get_request_control_ids()) session.request_control(True) # send another control request, test that it is not duplicated await self.wait() self.assertEqual(len(session.get_request_controls()), 1) self.assertEqual(len(session.get_request_control_ids()), 1) session.request_control(False) await self.wait() self.assertEqual(self._control_request, session.live_session_user) # callback self.assertEqual(self._want_control, False) # callback self.assertEqual(len(session.get_request_controls()), 0) self.assertEqual(len(session.get_request_control_ids()), 0) self._control_request = None session.request_control(False) # test that we don't crash when we remove the request twice await self.wait() self.assertIsNone(self._control_request) self.assertEqual(len(session.get_request_controls()), 0) self.assertEqual(len(session.get_request_control_ids()), 0) # Timeline state is read properly await self._test_timeline_receive(session, state) # Stop session session.stop_session() self.assertFalse(session.is_running()) state.remove_users_changed_fn(self._on_users_changed) session.remove_presenter_changed_fn(self._on_presenter_changed) session.remove_control_request_changed_fn(self._on_control_request) # This is implementation specific, used in the function below. def _get_timeline_playstate(self) -> int: if self._timeline.is_playing(): return 0 if self._timeline.is_stopped(): return 2 return 1 # As we don't have two clients, we test that the serializer changes the synchronization prim # when the timeline is changed. # This needs to be rewritten when the transmission protocol is changed. async def _test_timeline_send(self, session, state): timeline_prim: Usd.Prim = self._presence_stage.GetPrimAtPath(TIMELINE_PRIM_PATH) self.assertTrue(timeline_prim.IsValid(), "Timeline prim needs to be created") time = self._timeline.get_current_time() looping = self._timeline.is_looping() playstate = self._get_timeline_playstate() time_attr = timeline_prim.GetAttribute(TIME_ATTR_NAME) looping_attr = timeline_prim.GetAttribute(LOOPING_ATTR_NAME) playstate_attr = timeline_prim.GetAttribute(PLAYSTATE_ATTR_NAME) self.assertTrue(time_attr.IsValid()) self.assertTrue(looping_attr.IsValid()) self.assertTrue(playstate_attr.IsValid()) self.assertEqual(time_attr.Get(), time) self.assertEqual(looping_attr.Get(), looping) self.assertEqual(playstate_attr.Get(), playstate) # change timeline values time = time + 1 looping = not looping self._timeline.set_current_time(time) self._timeline.set_looping(looping) self.assertFalse(self._timeline.is_playing()) # make sure time is not changed automatically await self.wait() self.assertEqual(time_attr.Get(), time) self.assertEqual(looping_attr.Get(), looping) self._timeline.play() await self.wait() self.assertEqual(playstate_attr.Get(), self._get_timeline_playstate()) # restore self._timeline.stop() self._timeline.set_current_time(0) self._timeline.commit() # As we don't have two clients, we test that the serializer reads the result # when the synchronization prim is changed and applies it to the timeline. # This needs to be rewritten when the transmission protocol is changed. async def _test_timeline_receive(self, sesssion, state): timeline_prim: Usd.Prim = self._presence_stage.GetPrimAtPath(TIMELINE_PRIM_PATH) self.assertTrue(timeline_prim.IsValid(), "Timeline prim needs to be created") time = self._timeline.get_current_time() looping = self._timeline.is_looping() self.assertFalse(self._timeline.is_playing()) playstate = self._get_timeline_playstate() time_attr = timeline_prim.GetAttribute(TIME_ATTR_NAME) looping_attr = timeline_prim.GetAttribute(LOOPING_ATTR_NAME) playstate_attr = timeline_prim.GetAttribute(PLAYSTATE_ATTR_NAME) self.assertTrue(time_attr.IsValid()) self.assertTrue(looping_attr.IsValid()) self.assertTrue(playstate_attr.IsValid()) self.assertEqual(time_attr.Get(), time) self.assertEqual(looping_attr.Get(), looping) self.assertEqual(playstate_attr.Get(), playstate) # change prim values time = time + 1 looping = not looping time_attr.Set(time) looping_attr.Set(looping) await self.wait() self.assertEqual(self._timeline.get_current_time(), time) self.assertEqual(self._timeline.is_looping(), looping) playstate_attr.Set(0) await self.wait() self.assertFalse(self._timeline.is_stopped()) # sync strategies may set to paused but not stopped # restore self._timeline.stop() self._timeline.set_current_time(0) self._timeline.commit() def _on_users_changed(self, user_list): self._users = user_list def _assert_users_and_clear(self, expected_size, must_have_user): self.assertIsNotNone(self._users) self.assertEqual(len(self._users), expected_size) if must_have_user is not None: self.assertTrue(must_have_user in self._users) self._users = None def _on_presenter_changed(self, user): self._presenter = user def _on_control_request(self, user, want_control): self._control_request = user self._want_control = want_control async def _mock_join_session( self, sync_strategy_type: SyncStrategyType = SyncStrategyType.DIFFERENCE_LIMITED ) -> MockJoiner: mock_joiner = self._mock_joiner_manager.create_joiner( self._timeline, self._simulated_user_name, self._simulated_user_id, ls.get_timeline_session().live_session_user, sync_strategy_type, ) mock_joiner.mock_timeline_session.start_session() await self._simulate_user_join_with_user_object(mock_joiner.joiner) return mock_joiner async def _sync_received_update_events_from_presenter( self, mock_joiners: List[MockJoiner], wait_frame: int = 10 ) -> None: await self.wait(wait_frame) for mock_joiner in mock_joiners: mock_joiner.commit_received_update_timeline_events() # The following tests are written based on # this doc: https://docs.google.com/document/d/1vx2OBSDVKa1GgKwswSY7qmqgpQq46Qnha8L92GCPQNs/edit?pli=1#heading=h.5tno0u5x49br ## 1. User (owner) creates a new session and joins it ### a. Expected: User becomes timeline presenter immediately @MockLiveSyncingApi async def test_create_and_join_session(self): await self._create_session() session = ls.get_timeline_session() self.assertTrue(session.is_running()) self.assertIsNotNone(session.live_session_user) self.assertIsNotNone(session.presenter) self.assertTrue(session.am_i_presenter()) self.assertTrue(session.is_presenter(session.live_session_user)) ## 2. Set state (e.g. time) to non-default for the presenter. Other users join. ### a Expected: #### i. joining users become listeners, owner stays presenter #### ii. joining users should pick up the synced state immediately #### (test that this is also happening when the timeline is not playing!) async def _test_change_state_before_other_joining(self, playing: bool): await self._create_session() # update timeline modified_time = self._timeline.get_current_time() + 10 self._timeline.set_current_time(modified_time) if playing: # enable playing self._timeline.play() self._timeline.commit() mock_joiner = await self._mock_join_session() await self._sync_received_update_events_from_presenter([mock_joiner]) # make sure presenter does not change origin_session = ls.get_timeline_session() self.assertTrue(origin_session.is_presenter(origin_session.live_session_user)) self.assertEqual(len(ls.get_session_state().users), 2) self.assertFalse( mock_joiner.mock_timeline_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user) ) self.assertTrue(mock_joiner.mock_timeline_session.is_presenter(origin_session.live_session_user)) ## joining users should pick up the synced state immediately self.assertEqual(mock_joiner.get_time_codes_per_seconds(), self._timeline.get_time_codes_per_seconds()) self.assertEqual(mock_joiner.is_looping(), self._timeline.is_looping()) self.assertEqual(mock_joiner.is_playing(), self._timeline.is_playing()) self.assertEqual(mock_joiner.is_playing(), playing) if not playing: self.assertEqual(mock_joiner.get_current_time(), modified_time) self.assertEqual(mock_joiner.get_current_time(), self._timeline.get_current_time()) else: # By default, listeners employ interpolation to synchronize with the presenter's state. # Therefore, we must introduce a delay to ensure smooth synchronization. self.assertLessEqual(mock_joiner.get_current_time(), modified_time) await self._sync_received_update_events_from_presenter([mock_joiner], 100) self.assertGreaterEqual(mock_joiner.get_current_time(), modified_time) self.assertAlmostEqual(mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1) @MockLiveSyncingApi async def test_change_state_before_other_joining_in_play_mode(self): await self._test_change_state_before_other_joining(True) @MockLiveSyncingApi async def test_change_state_before_other_joining_in_stop_mode(self): await self._test_change_state_before_other_joining(False) ## 3. Change time for the presenter ## 4. Same with playing, pause, stop ### i Expected: time should change for all listeners accordingly async def _test_change_time_and_timeline_state( self, presenter_timeline: omni.timeline.Timeline, listener_timelines: [omni.timeline.Timeline] ): # change time modified_time = presenter_timeline.get_current_time() + 10 presenter_timeline.set_current_time(modified_time) presenter_timeline.commit() self.assertEqual(presenter_timeline.get_current_time(), modified_time) await self.wait() for timeline in listener_timelines: timeline.commit() self.assertEqual(timeline.get_current_time(), modified_time) self.assertEqual(timeline.get_current_time(), presenter_timeline.get_current_time()) # play presenter_timeline.play() presenter_timeline.commit() self.assertTrue(presenter_timeline.is_playing()) await self.wait() for timeline in listener_timelines: timeline.commit() self.assertAlmostEqual(timeline.get_current_time(), self._timeline.get_current_time(), delta=1) self.assertEqual(timeline.is_playing(), self._timeline.is_playing()) self.assertEqual(timeline.is_playing(), True) # pause presenter_timeline.pause() presenter_timeline.commit() self.assertFalse(presenter_timeline.is_playing()) self.assertFalse(presenter_timeline.is_stopped()) await self.wait() for timeline in listener_timelines: timeline.commit() self.assertAlmostEqual(timeline.get_current_time(), presenter_timeline.get_current_time(), delta=1) self.assertEqual(timeline.is_playing(), presenter_timeline.is_playing()) self.assertEqual(timeline.is_playing(), False) self.assertEqual(timeline.is_stopped(), presenter_timeline.is_stopped()) self.assertEqual(timeline.is_stopped(), False) # stop presenter_timeline.stop() presenter_timeline.commit() self.assertFalse(presenter_timeline.is_playing()) self.assertTrue(presenter_timeline.is_stopped()) await self.wait() for timeline in listener_timelines: timeline.commit() self.assertEqual(timeline.get_current_time(), presenter_timeline.get_current_time()) self.assertEqual(timeline.is_playing(), presenter_timeline.is_playing()) self.assertEqual(timeline.is_playing(), False) self.assertEqual(timeline.is_stopped(), presenter_timeline.is_stopped()) self.assertEqual(timeline.is_stopped(), True) @MockLiveSyncingApi async def test_change_time_and_timeline_state_for_presenter(self): await self._create_session() mock_joiner = await self._mock_join_session() for _ in range(3): await self._test_change_time_and_timeline_state(self._timeline, [mock_joiner.mock_timeline]) # 5. Turn timeline sync off for presenter, start changing time, playing, etc. ## a. Expected: ### i. time is unchanged for all listeners ### ii. UI that shows sync state at the presenter's Kit instance should show sync is off (`is_sync_enabled()` should be false) ### iii. UI at listeners shows they are still receiving updates (`is_sync_enabled()` should be true) ### and they still cannot control their own timeline (in fact we might change this design) # 6. Turn back timeline sync for presenter. ## a. Expected: changes that are made for the presenter are synced at listeners; ## presenter's UI shows sync is on again (`is_sync_enabled()` should be true) @MockLiveSyncingApi async def test_presenter_turn_sync_off(self): await self._create_session() mock_joiner = await self._mock_join_session() # sync up state await self._sync_received_update_events_from_presenter([mock_joiner]) old_time = mock_joiner.get_current_time() playing = mock_joiner.is_playing() # turn off sync def expect_false(enabled: bool) -> None: return self.assertFalse(enabled) ls.get_timeline_session().add_enable_sync_changed_fn(expect_false) ls.get_timeline_session().enable_sync(False) self.assertFalse(ls.get_timeline_session().is_sync_enabled()) # change time modified_time = self._timeline.get_current_time() + 10 self._timeline.set_current_time(modified_time) self._timeline.commit() await self._sync_received_update_events_from_presenter([mock_joiner]) # listener is still in sync mode self.assertTrue(mock_joiner.mock_timeline_session.is_sync_enabled()) self.assertEqual(mock_joiner.get_current_time(), old_time) self.assertNotEqual(mock_joiner.get_current_time(), modified_time) # play self._timeline.play() self._timeline.commit() # play for a while await self._sync_received_update_events_from_presenter([mock_joiner], 50) self.assertEqual(mock_joiner.get_current_time(), old_time) self.assertNotAlmostEqual(mock_joiner.get_current_time(), self._timeline.get_current_time()) self.assertNotEqual(mock_joiner.is_playing(), self._timeline.is_playing()) self.assertEqual(mock_joiner.is_playing(), playing) # listenr try to modify timeline but fail mock_joiner.set_current_time(modified_time) mock_joiner.commit() self.assertNotEqual(mock_joiner.get_current_time(), modified_time) self.assertEqual(mock_joiner.get_current_time(), old_time) mock_joiner.play() await self._sync_received_update_events_from_presenter([mock_joiner]) self.assertEqual(mock_joiner.is_playing(), playing) # make sure this callback is removed ls.get_timeline_session().remove_enable_sync_changed_fn(expect_false) ls.get_timeline_session().enable_sync(True) self.assertTrue(ls.get_timeline_session().is_sync_enabled()) # listener should pick up the state from the presenter await self._sync_received_update_events_from_presenter([mock_joiner]) self.assertEqual(mock_joiner.is_playing(), self._timeline.is_playing()) # By default, listeners employ interpolation to synchronize with the presenter's state. # Therefore, we must introduce a delay to ensure smooth synchronization. self.assertLessEqual(mock_joiner.get_current_time(), self._timeline.get_current_time()) await self._sync_received_update_events_from_presenter([mock_joiner], 100) self.assertAlmostEqual(mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1) # 7. Similar to the previous one, # but testing allowed time difference: turn on and off timeline sync during playback. ## a. Expected: ### i. when sync is turned off during playback, ### listeners should pause after a while ### (which is determined by the allowed time difference setting, ### 0 = immediately, 1 sec = listeners should be 1 sec ahead when they pause). ### Test this carefully with looping, playing/pausing/stopping several times. ### ii. when sync is turned off and then on very rapidly, ### there should be minimal lag at listeners (which depends on the allowed time difference setting) @MockLiveSyncingApi async def test_presenter_turn_sync_on_and_off_during_playback(self): # rounding to 1e-5 STRICT_MODE_EPS = 1e-5 await self._create_session() default_mode_mock_joiner = await self._mock_join_session() strict_mode_mock_joiner = await self._mock_join_session(SyncStrategyType.STRICT) loose_mode_mock_joiner = await self._mock_join_session(SyncStrategyType.LOOSE) async def play() -> None: self._timeline.play() self._timeline.commit() await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner] ) self.assertTrue(default_mode_mock_joiner.is_playing()) # In strict mode, the system adheres strictly to the presenter's timeline. # Thus, we validate that the mock joiner isn't playing in this mode. self.assertFalse(strict_mode_mock_joiner.is_playing()) self.assertTrue(loose_mode_mock_joiner.is_playing()) async def disable_sync_during_playing_and_wait_for_a_while(): ls.get_timeline_session().enable_sync(False) self.assertFalse(ls.get_timeline_session().is_sync_enabled()) last_seen_time_from_presenter = self._timeline.get_current_time() # wait for a while await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner], 300 ) self.assertTrue(default_mode_mock_joiner.mock_timeline_session.is_sync_enabled()) self.assertTrue(strict_mode_mock_joiner.mock_timeline_session.is_sync_enabled()) self.assertTrue(loose_mode_mock_joiner.mock_timeline_session.is_sync_enabled()) self.assertFalse(default_mode_mock_joiner.is_playing()) self.assertFalse(strict_mode_mock_joiner.is_playing()) self.assertTrue(loose_mode_mock_joiner.is_playing()) # only follow the presenter self.assertAlmostEqual( last_seen_time_from_presenter, strict_mode_mock_joiner.get_current_time(), delta=STRICT_MODE_EPS ) self.assertLess(last_seen_time_from_presenter, default_mode_mock_joiner.get_current_time()) # stop after listener's time is 1 + some eps ahead the last seen presenter time self.assertAlmostEqual( last_seen_time_from_presenter, default_mode_mock_joiner.get_current_time(), delta=1.5 ) # keep playing self.assertLess(last_seen_time_from_presenter, loose_mode_mock_joiner.get_current_time()) async def enable_sync_during_playing() -> None: # sync back ls.get_timeline_session().enable_sync(True) self.assertTrue(ls.get_timeline_session().is_sync_enabled()) await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner] ) self.assertTrue(default_mode_mock_joiner.is_playing()) self.assertFalse(strict_mode_mock_joiner.is_playing()) self.assertTrue(loose_mode_mock_joiner.is_playing()) # in default mode, listeners employ interpolation to synchronize with the presenter's state. # So it will not catch up immediately self.assertLessEqual(default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time()) # in strict mode, time should be synced with the presenter immediately self.assertAlmostEqual( strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1 ) # in default mode, listeners employ interpolation to synchronize with the presenter's state. # Therefore, we must introduce a delay to ensure smooth synchronization. await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner], 100 ) self.assertAlmostEqual( default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1 ) self.assertAlmostEqual( strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1 ) async def pause() -> None: self._timeline.pause() self._timeline.commit() await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner] ) self.assertFalse(default_mode_mock_joiner.is_playing()) self.assertFalse(strict_mode_mock_joiner.is_playing()) self.assertFalse(loose_mode_mock_joiner.is_playing()) self.assertAlmostEqual( default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1 ) self.assertAlmostEqual( strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=STRICT_MODE_EPS ) async def trigger_loop() -> None: # trigger loop self._timeline.set_current_time(self._end_time - 1) self._timeline.commit() await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner] ) self.assertEqual(default_mode_mock_joiner.get_current_time(), self._timeline.get_current_time()) self.assertEqual(strict_mode_mock_joiner.get_current_time(), self._timeline.get_current_time()) self.assertEqual(loose_mode_mock_joiner.get_current_time(), self._timeline.get_current_time()) # play for a while to start from the begining self._timeline.play() self._timeline.commit() await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner], 100 ) self.assertTrue(default_mode_mock_joiner.is_playing()) self.assertFalse(strict_mode_mock_joiner.is_playing()) self.assertTrue(loose_mode_mock_joiner.is_playing()) self.assertGreaterEqual(default_mode_mock_joiner.get_current_time(), 0) self.assertGreaterEqual(strict_mode_mock_joiner.get_current_time(), 0) self.assertGreaterEqual(loose_mode_mock_joiner.get_current_time(), 0) async def stop() -> None: self._timeline.stop() self._timeline.commit() await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner] ) self.assertFalse(default_mode_mock_joiner.is_playing()) self.assertFalse(strict_mode_mock_joiner.is_playing()) self.assertFalse(loose_mode_mock_joiner.is_playing()) self.assertEqual(default_mode_mock_joiner.get_current_time(), 0) self.assertEqual(strict_mode_mock_joiner.get_current_time(), 0) self.assertEqual(loose_mode_mock_joiner.get_current_time(), 0) # for joiners to sync up await self._sync_received_update_events_from_presenter( [default_mode_mock_joiner, strict_mode_mock_joiner, loose_mode_mock_joiner] ) for _ in range(3): for _ in range(2): await play() await disable_sync_during_playing_and_wait_for_a_while() await enable_sync_during_playing() # pause await pause() await play() await disable_sync_during_playing_and_wait_for_a_while() await enable_sync_during_playing() await pause() # loop await trigger_loop() await disable_sync_during_playing_and_wait_for_a_while() await enable_sync_during_playing() # stop await stop() await play() await disable_sync_during_playing_and_wait_for_a_while() await enable_sync_during_playing() await stop() # turn on and off very rapidly await play() # making sure default_mode_listener never pause for _ in range(50): ls.get_timeline_session().enable_sync(False) ls.get_timeline_session().enable_sync(True) self.assertTrue(default_mode_mock_joiner.is_playing()) await self.wait(1) # 8. Leave timeline sync on for presenter, turn it off for some of the listeners ## a. Expected: these listeners can control their own timeline ## and receive nothing from the synced state; corresponding UI shows sync is off (`is_sync_enabled()` is the state of the UI) # 9. Turn sync back for listeners ## a. Expected: ### i. If the synced (the presenter's) timeline is playing, it should start playing for the listeners again ### ii. If the synced (the presenter's) timeline is not playing, ### the time at the listeners should jump to the synced time. ### This is a bit different than the previous case, ### as we want to make sure that listeners pick up the synced state ### even if it has not changed since they re-enabled timeline sync. (In the previous case, if the timeline is playing they keep getting new time updates) @MockLiveSyncingApi async def test_listeners_turn_sync_off_and_on(self): await self._create_session() disable_sync_mock_joiner = await self._mock_join_session() enable_sync_mock_joiner = await self._mock_join_session() disable_sync_mock_joiner.mock_timeline_session.enable_sync(False) self.assertFalse(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled()) old_time = disable_sync_mock_joiner.get_current_time() # change time modified_time = self._timeline.get_current_time() + 10 self._timeline.set_current_time(modified_time) self._timeline.commit() await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner, enable_sync_mock_joiner]) self.assertEqual(disable_sync_mock_joiner.get_current_time(), old_time) self.assertNotEqual(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time()) self.assertEqual(enable_sync_mock_joiner.get_current_time(), modified_time) self.assertEqual(enable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time()) # manipluate time new_time = old_time + 3 disable_sync_mock_joiner.set_current_time(new_time) disable_sync_mock_joiner.commit() self.assertEqual(disable_sync_mock_joiner.get_current_time(), new_time) self.assertNotEqual(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time()) # should pick up state after enable_sync disable_sync_mock_joiner.mock_timeline_session.enable_sync(True) self.assertTrue(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled()) await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner]) self.assertEqual(disable_sync_mock_joiner.get_current_time(), modified_time) self.assertEqual(disable_sync_mock_joiner.is_playing(), self._timeline.is_playing()) # disbale again and make presenter playing disable_sync_mock_joiner.mock_timeline_session.enable_sync(False) self.assertFalse(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled()) old_time = disable_sync_mock_joiner.get_current_time() self._timeline.play() self._timeline.commit() # play for a while await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner, enable_sync_mock_joiner], 50) self.assertNotEqual(disable_sync_mock_joiner.is_playing(), self._timeline.is_playing()) self.assertEqual(enable_sync_mock_joiner.is_playing(), self._timeline.is_playing()) self.assertFalse(disable_sync_mock_joiner.is_playing()) self.assertTrue(enable_sync_mock_joiner.is_playing()) self.assertAlmostEqual(enable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1) self.assertLess(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time()) # should pick up state after enable_sync disable_sync_mock_joiner.mock_timeline_session.enable_sync(True) self.assertTrue(disable_sync_mock_joiner.mock_timeline_session.is_sync_enabled()) await self._sync_received_update_events_from_presenter([disable_sync_mock_joiner, enable_sync_mock_joiner]) self.assertEqual(disable_sync_mock_joiner.is_playing(), self._timeline.is_playing()) self.assertEqual(enable_sync_mock_joiner.is_playing(), self._timeline.is_playing()) self.assertTrue(disable_sync_mock_joiner.is_playing()) self.assertTrue(enable_sync_mock_joiner.is_playing()) self.assertGreater(disable_sync_mock_joiner.get_current_time(), modified_time) self.assertAlmostEqual(disable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1) self.assertAlmostEqual(enable_sync_mock_joiner.get_current_time(), self._timeline.get_current_time(), delta=1) # 10. Owner passes the presenter role (timeline control) to another user. # The new presenter changes its (and thus the synced) timeline, set time, play/pause/stop etc. ## a. Expected: ### i. Owner (previous presenter) is no longer able to control its own timeline ### ii. Everything that the new presenter is doing is synced to all listeners (including the previous presenter!) ### iii. Owner is not allowed to pass the presenter role to the same user again (UI: "give control"-like messages turn to "withdraw control" or something similar) ### iv. All UI that somehow marks/shows who the presenter is should show the new presenter (user icons, timeline window etc.) # 11. Owner passes the presenter role to a new user. # Essentially the same as the previous case, # except that presenter role passed from a non-owner user to another non-owner. # Repeat this several times for several (or all) users. # 12. Owner returns the presenter role to him/herself (edge case). # Everything should be the same as in the cases above. async def _set_as_presenter(self, new_presenter_timeline_session: TimelineSession) -> None: owner_session = ls.get_timeline_session() owner_session.presenter = new_presenter_timeline_session.live_session_user await self.wait() async def _validate_presenter_state( self, old_presenter_timeline: omni.timeline.Timeline, new_presenter_timeline: omni.timeline.Timeline, new_presenter_timeline_session: TimelineSession, new_presenter_window: UserWindow, non_presenter_mock_joiners: List[MockJoiner], pass_to_owner: bool, ) -> None: owner_session = ls.get_timeline_session() # i. previous presenter could not change timeline old_time = old_presenter_timeline.get_current_time() new_time = old_time + self._end_time / 10 old_presenter_timeline.set_current_time(new_time) old_presenter_timeline.commit() self.assertEqual(old_presenter_timeline.get_current_time(), old_time) self.assertNotEqual(old_presenter_timeline.get_current_time(), new_time) old_presenter_timeline.play() old_presenter_timeline.commit() self.assertFalse(old_presenter_timeline.is_playing()) # ii. new presenter manipulate listener_timelines: List[omni.timeline.Timeline] = [old_presenter_timeline] for mock_joiner in non_presenter_mock_joiners: listener_timelines.append(mock_joiner.mock_timeline) for _ in range(3): await self._test_change_time_and_timeline_state(new_presenter_timeline, listener_timelines) # iv. new presenter self.assertEqual( new_presenter_timeline_session.is_presenter(owner_session.live_session_user), pass_to_owner, "" ) self.assertEqual(owner_session.is_presenter(owner_session.live_session_user), pass_to_owner, "") self.assertEqual(owner_session.am_i_presenter(), pass_to_owner, "") self.assertTrue(owner_session.is_presenter(new_presenter_timeline_session.live_session_user)) self.assertTrue(new_presenter_timeline_session.is_presenter(new_presenter_timeline_session.live_session_user)) self.assertTrue(new_presenter_timeline_session.am_i_presenter()) for mock_joiner in non_presenter_mock_joiners: self.assertEqual( mock_joiner.mock_timeline_session.is_presenter(owner_session.live_session_user), pass_to_owner ) self.assertFalse(new_presenter_timeline_session.is_presenter(mock_joiner.joiner)) self.assertFalse( new_presenter_timeline_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user) ) self.assertFalse(owner_session.is_presenter(mock_joiner.joiner)) self.assertFalse(owner_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user)) self.assertFalse(mock_joiner.mock_timeline_session.is_presenter(mock_joiner.joiner)) self.assertFalse( mock_joiner.mock_timeline_session.is_presenter(mock_joiner.mock_timeline_session.live_session_user) ) self.assertTrue( mock_joiner.mock_timeline_session.is_presenter(new_presenter_timeline_session.live_session_user) ) self.assertFalse(mock_joiner.mock_timeline_session.am_i_presenter()) # iii and iv. UI owner_window = ui_test.find(self._window_title) new_presenter_window_ref = ui_test.find(new_presenter_window._window.title) self._window.show() new_presenter_window.show() await self.wait() new_presenter = new_presenter_timeline_session.live_session_user search_text = f'**/ScrollingFrame[0]/VStack[0]/Label[*].text == "{new_presenter.user_name} ({new_presenter.from_app}) [Presenter]"' if pass_to_owner: new_presenter_in_owner_window = owner_window.find( f'**/ScrollingFrame[0]/VStack[0]/Label[*].text == "{new_presenter.user_name} ({new_presenter.from_app}) [Owner][Presenter][Current user]"' ) else: new_presenter_in_owner_window = owner_window.find(search_text) self.assertIsNotNone(new_presenter_window_ref.find(f'{search_text[:-1]}[Current user]"')) self.assertIsNotNone(new_presenter_in_owner_window) await new_presenter_in_owner_window.click() btn = owner_window.find('**/Button[*].text == "Set as Timeline Presenter"') self.assertIsNotNone(btn) self.assertFalse(btn.widget.visible) for mock_joiner in non_presenter_mock_joiners: mock_joiner_window = ui_test.find(mock_joiner.get_window_title()) mock_joiner.window.show() await self.wait() self.assertIsNotNone(mock_joiner_window.find(search_text)) non_presenter = mock_joiner.mock_timeline_session.live_session_user non_presenter_text = f'**/ScrollingFrame[0]/VStack[0]/Label[*].text == "{non_presenter.user_name} ({non_presenter.from_app}) "' non_presenter_in_owner_window = owner_window.find(non_presenter_text) self.assertIsNotNone(non_presenter_in_owner_window) await non_presenter_in_owner_window.click() btn = owner_window.find('**/Button[*].text == "Set as Timeline Presenter"') self.assertIsNotNone(btn) self.assertTrue(btn.widget.visible) @MockLiveSyncingApi async def test_pass_presenter(self): await self._create_session() mock_joiners: List[MockJoiner] = [] for _ in range(2): mock_joiners.append(await self._mock_join_session()) for _ in range(2): # 10, 11 previous_presenter_timeline = self._timeline for _ in range(2): for mock_joiner in mock_joiners: non_presenters = filter( lambda other: other.joiner.user_id != mock_joiner.joiner.user_id, mock_joiners ) await self._set_as_presenter(mock_joiner.mock_timeline_session) await self._validate_presenter_state( previous_presenter_timeline, mock_joiner.mock_timeline, mock_joiner.mock_timeline_session, mock_joiner.window, list(non_presenters), False, ) previous_presenter_timeline = mock_joiner.mock_timeline # 12 await self._set_as_presenter(ls.get_timeline_session()) await self._validate_presenter_state( previous_presenter_timeline, self._timeline, ls.get_timeline_session(), self._window, mock_joiners, True, ) # 13. A listener sends a request to become presenter. # Potentially do this with multiple listeners at the same time. ## a. Expected: The UI for the listener changes and he can no longer send a request, ## instead, he can withdraw it # 14. The owner receives a notification about the request and the user(s) that sent the request appear(s) on the "requests" list. # The owner is able to select it and has the option to pass the presenter role. # 15. A listener revokes its request ## a. Expected: the owner no longer sees this user among the requests. # 16. Pass presenter role to a user that requested it. 1) listener sends a request, 2) owner gives timeline control ## a. Expected, once timeline control is passed: ### i. the requester should disappear from the request list at the owner ### ii. everything else should be the same (and tested similarly) as when the owner passes the presenter role to another user async def _list_check(self, control_requesters: List[MockJoiner]) -> None: self.assertEqual(len(ls.get_timeline_session().get_request_control_ids()), len(control_requesters)) owner_window = ui_test.find(self._window_title) for mock_joiner in control_requesters: user = mock_joiner.joiner control_req_in_owner_window = owner_window.find( f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{user.user_name} ({user.from_app}) "' ) self.assertIsNotNone(control_req_in_owner_window) await control_req_in_owner_window.click() self.assertTrue(control_req_in_owner_window.widget.selected) self.assertIsNotNone(owner_window.find('**/Button[*].text == "Set as Timeline Presenter"')) mock_joiner_window_ref = ui_test.find(mock_joiner.get_window_title()) self.assertIsNone(mock_joiner_window_ref.find('**/Button[*].text == "Request Timeline Control"')) self.assertIsNotNone(mock_joiner_window_ref.find('**/Button[*].text == "Revoke Request"')) self.assertTrue( any( user_id == mock_joiner.joiner.user_id for user_id in ls.get_timeline_session().get_request_control_ids() ) ) for other in filter(lambda other: other.joiner.user_id != mock_joiner.joiner.user_id, control_requesters): other_user = other.joiner self.assertIsNotNone( mock_joiner_window_ref.find( f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{other_user.user_name} ({other_user.from_app}) "' ) ) async def _remove_user_from_control_list( self, set_as_presenter: bool, control_requesters: List[MockJoiner], mock_joiners: List[MockJoiner] ) -> None: owner_window = ui_test.find(self._window_title) chosen_user = control_requesters.pop() if set_as_presenter: user = chosen_user.joiner control_req_in_owner_window = owner_window.find( f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{user.user_name} ({user.from_app}) "' ) self.assertIsNotNone(control_req_in_owner_window) await control_req_in_owner_window.click() self.assertTrue(control_req_in_owner_window.widget.selected) set_presenter_btn = owner_window.find('**/Button[*].text == "Set as Timeline Presenter"') self.assertIsNotNone(set_presenter_btn) await set_presenter_btn.click() else: # revoke chosen_user_window_ref = ui_test.find(chosen_user.get_window_title()) revoke_btn = chosen_user_window_ref.find('**/Button[*].text == "Revoke Request"') self.assertIsNotNone(revoke_btn) await revoke_btn.click() chosen_user.window.show() for mock_joiner in mock_joiners: mock_joiner.window.show() self._window.show() await self.wait() self.assertIsNone( owner_window.find( f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{chosen_user.joiner.user_name} ({chosen_user.joiner.from_app}) "' ) ) await self._list_check(control_requesters) for mock_joiner in mock_joiners: self.assertIsNone( owner_window.find( f'**/ScrollingFrame[1]/VStack[0]/Label[*].text == "{chosen_user.joiner.user_name} ({chosen_user.joiner.from_app}) "' ) ) if not set_as_presenter: return await self._validate_presenter_state( self._timeline, chosen_user.mock_timeline, chosen_user.mock_timeline_session, chosen_user.window, list(filter(lambda other: other.joiner.user_id != chosen_user.joiner.user_id, mock_joiners)), False, ) @MockLiveSyncingApi async def test_request_control(self): await self._create_session() mock_joiners: List[MockJoiner] = [] for _ in range(5): mock_joiners.append(await self._mock_join_session()) control_req_list = list(mock_joiners) # 13 self.assertEqual(len(ls.get_timeline_session().get_request_control_ids()), 0) for mock_joiner in mock_joiners: mock_joiner_window_ref = ui_test.find(mock_joiner.get_window_title()) self.assertIsNotNone(mock_joiner_window_ref.find('**/Button[*].text == "Request Timeline Control"')) self.assertIsNone(mock_joiner_window_ref.find('**/Button[*].text == "Revoke Request"')) mock_joiner.mock_timeline_session.request_control(True) for mock_joiner in mock_joiners: mock_joiner.window.show() self._window.show() await self.wait() # 14 await self._list_check(control_req_list) # 15 revoke await self._remove_user_from_control_list(False, control_req_list, mock_joiners) # 16 await self._remove_user_from_control_list(True, control_req_list, mock_joiners) # 17. Latency estimate: TBD ## a. So far I have tested that it returns zero for the presenter and something meaningful or everyone else. ## b. Latency for listeners should increase when there's a lag (e.g. artificially introduced sleep) at the presenter ## c. Turning timeline sync off for the presenter should not affect the latency @MockLiveSyncingApi async def test_latency_estimate(self): await self._create_session() self._timeline.play() self._timeline.commit() mock_joiners: List[MockJoiner] = [] for _ in range(3): mock_joiners.append(await self._mock_join_session()) await self._sync_received_update_events_from_presenter(mock_joiners) # latency estimate from presenter is 0 self.assertEqual(ls.get_timeline_session().role.get_latency_estimate(), 0) avg_latency = 0.0 cnt = 50 for _ in range(cnt): await self.wait(1) for mock_joiner in mock_joiners: avg_latency += mock_joiner.mock_timeline_session.role.get_latency_estimate() avg_latency /= cnt # turn off sync does not affect latency ls.get_timeline_session().enable_sync(False) await self._sync_received_update_events_from_presenter(mock_joiners) avg_turn_off_sync_latency = 0.0 cnt = 50 for _ in range(cnt): await self.wait(1) for mock_joiner in mock_joiners: avg_turn_off_sync_latency += mock_joiner.mock_timeline_session.role.get_latency_estimate() avg_turn_off_sync_latency /= cnt self.assertAlmostEqual(avg_latency, avg_turn_off_sync_latency, delta=1) # simulate lag ls.get_timeline_session().stop_session() await asyncio.sleep(1.5) lag_latency = 0.0 for _ in range(cnt): await self.wait(1) for mock_joiner in mock_joiners: lag_latency += mock_joiner.mock_timeline_session.role.get_latency_estimate() lag_latency /= cnt self.assertNotAlmostEqual(avg_latency, lag_latency, delta=1) ls.get_timeline_session().start_session() await self._sync_received_update_events_from_presenter(mock_joiners) # 18. Everyone leaves the session, then owner joins an existing session while there are no other users. # (There was a bug at some point when this didn't work.) ## a. Expected: owner should become the presenter @MockLiveSyncingApi @unittest.skip("Need to fix MockLiveSyncingApi to fully mock live session") async def test_new_owner(self): await self._create_session() mock_joiners: List[MockJoiner] = [] for _ in range(3): mock_joiners.append(await self._mock_join_session()) self._timeline.play() self._timeline.commit() await self._sync_received_update_events_from_presenter(mock_joiners) user_cnt = len(mock_joiners) + 1 for mock_joiner in mock_joiners: user = mock_joiner.joiner current_session = self._live_syncing.get_current_live_session() session_channel = current_session._session_channel() del session_channel._peer_users[user.user_id] session_channel._send_layer_event( layers.LayerEventType.LIVE_SESSION_USER_LEFT, {"user_name": user.user_name, "user_id": user.user_id} ) await self.wait() self.assertIsNone(ls.get_session_state().find_user(user.user_id)) user_cnt -= 1 self.assertEqual(len(ls.get_session_state().users), user_cnt) # leave self._live_syncing.stop_all_live_sessions() await self.wait() self.assertEqual(len(ls.get_session_state().users), 0) # rejoin session = self._live_syncing.find_live_session_by_name(self._stage_url, "test") self.assertTrue(session, "Failed to find live session.") self.assertTrue(self._live_syncing.join_live_session(session)) await self.wait() self.assertTrue(self._live_syncing.is_in_live_session()) # become presenter owner_timeline_session = ls.get_timeline_session() self.assertTrue(owner_timeline_session.am_i_presenter()) self.assertTrue(owner_timeline_session.is_presenter(owner_timeline_session.live_session_user)) self.assertEqual(owner_timeline_session.role_type, ls.TimelineSessionRoleType.PRESENTER)
59,064
Python
45.216745
166
0.651141
omniverse-code/kit/exts/omni.timeline.live_session/omni/timeline/live_session/tests/__init__.py
from .test_ui_window import * from .tests import *
51
Python
16.333328
29
0.72549
omniverse-code/kit/exts/omni.timeline.live_session/docs/examples.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. # # This file shows API usage examples for omni.timeline.live_session import omni.kit.usd.layers as layers import omni.timeline.live_session import omni.usd class Examples: # Example: Watch for connection to live session, then register to presenter changed event and react to it def example_presenter_changed_watcher(self): usd_context_name: str = "" self.usd_context = omni.usd.get_context(usd_context_name) live_syncing = layers.get_live_syncing(self.usd_context) self.layers = layers.get_layers(self.usd_context) self.layers_event_subscription = self.layers.get_event_stream().create_subscription_to_pop( self._on_layers_event, name="my_example_sub" ) # Make sure to set self.layers_event_subscription to None somewhere, omitted from the example # When a live session is joined, register callback for presenter changed events def _on_layers_event(self, event): payload = layers.get_layer_event_payload(event) if not payload: return # Only events from root layer session are handled. if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED: if not payload.is_layer_influenced(self.usd_context.get_stage_url()): return # Get the timeline session and register our own callback for presenter changed self.timeline_session = omni.timeline.live_session.get_timeline_session() if self.timeline_session is not None: self.timeline_session.add_presenter_changed_fn(self._on_presenter_changed) # Make sure to call session.remove_presenter_changed_fn somewhere, this is omitted here # Our callback that is called by the timeline sync extension when the presenter is changed. We get the new user. def _on_presenter_changed(self, user: layers.LiveSessionUser): print(f'The new Timeline Presenter is {user.user_name}') if self.timeline_session.am_i_presenter(): print('I am the Timeline Presenter!') else: print('I am a Timeline Listener.') # Example: Turn the timeline sync on or off. # For Listeners turning off stops receiving updates and gives them back the ability to control their own timeline. # For the Presenter turning off stops sending updates to Listeners. def example_toggle_sync(self): timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None: syncing = timeline_session.is_sync_enabled() if syncing: print('Timeline sync is enabled, turning it off') else: print('Timeline sync is disabled, turning it on') timeline_session.enable_sync(not syncing) # Example: Subscribe to changes in timeline sync (enabled/disabled) def example_enable_sync_changed(self): timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None: timeline_session.add_enable_sync_changed_fn(self._on_enable_sync_changed) # Make sure to call session.remove_enable_sync_changed_fn somewhere, this is omitted here def _on_enable_sync_changed(self, enabled: bool): print(f'Timeline synchronization was {"enabled" if enabled else "disabled"}') # Example: Query the estimated latency from the timeline session def example_query_latency(self): timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None: latency = timeline_session.role.get_latency_estimate() print(f'The estimated latency from the Timeline Presenter is {latency}') # Example: Register to control request received event def example_control_requests(self): timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None: timeline_session.add_control_request_changed_fn(self._on_control_requests_changed) # Make sure to call session.remove_control_request_changed_fn somewhere, this is omitted here # Our callback that is called by the timeline sync extension when a user sends or withdraws control request. def _on_control_requests_changed(self, user: layers.LiveSessionUser, wants_control: bool): if wants_control: print(f'User {user.user_name} requested to control the Timeline') else: print(f'User {user.user_name} withdrew the request to control the Timeline') # Print all users who have requested control timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None: all_users = timeline_session.get_request_controls() if len(all_users) == 0: print('There are no requests to control the Timeline') else: print('List of users requested to control the Timeline:') for request_user in all_users: print(f'\t{request_user.user_name}')
5,559
Python
49.545454
120
0.686095
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext from omni.rtx.window.settings import RendererSettingsFactory from .importers import IndeXImporters from .widgets import IndeXCommonSettingStack, IndeXClusterSettingStack class IndeXSettingsExtension(omni.ext.IExt): """The entry point for IndeX Settings Window""" renderer_name = "Scientific (IndeX)" def on_startup(self): RendererSettingsFactory.register_renderer(self.renderer_name, ["IndeX Cluster", "IndeX Common"]) RendererSettingsFactory.register_stack("IndeX Cluster", IndeXClusterSettingStack) RendererSettingsFactory.register_stack("IndeX Common", IndeXCommonSettingStack) try: import omni.kit.window.property as p except ImportError: # Likely running headless return w = p.get_window() if not w: return from .widgets.colormap_properties_widget import ColormapPropertiesWidget from .widgets.shader_properties_widget import ShaderPropertiesWidget from .widgets.volume_properties_widget import VolumePropertiesWidget self.colormap_widget = ColormapPropertiesWidget() self.shader_widget = ShaderPropertiesWidget() self.volume_widget = VolumePropertiesWidget() IndeXImporters.register_bindings(self) def on_shutdown(self): RendererSettingsFactory.unregister_renderer(self.renderer_name) RendererSettingsFactory.unregister_stack("IndeX Cluster") RendererSettingsFactory.unregister_stack("IndeX Common") RendererSettingsFactory.build_ui() try: import omni.kit.window.property as p except ImportError: # Likely running headless return w = p.get_window() if not w: return w.unregister_widget("prim", "shader") self.colormap_widget.on_shutdown() self.colormap_widget = None self.shader_widget.on_shutdown() self.shader_widget = None self.volume_widget.on_shutdown() self.volume_widget = None IndeXImporters.deregister_bindings(self)
2,544
Python
34.347222
104
0.704796
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/importers/__init__.py
from .importers import IndeXImporters
38
Python
18.499991
37
0.868421
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/importers/importers.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 import omni.usd import omni.kit.commands import omni.kit.window.content_browser as content from omni.kit.window.popup_dialog import FormDialog, MessageDialog import omni.ui as ui from pxr import Sdf, Gf, UsdVol, UsdShade from enum import Enum import os import re from ..presets import ColormapPresets, ShaderPresets class ComboListModel(ui.AbstractItemModel): class ComboListItem(ui.AbstractItem): def __init__(self, item): super().__init__() self.model = ui.SimpleStringModel(item) def __init__(self, item_list, default_index): super().__init__() self._default_index = default_index self._current_index = ui.SimpleIntModel(default_index) self._current_index.add_value_changed_fn(lambda a: self._item_changed(None)) self._item_list = item_list self._items = [] if item_list: for item in item_list: self._items.append(ComboListModel.ComboListItem(item)) def get_item_children(self, item): return self._items def get_item_list(self): return self._item_list def get_item_value_model(self, item=None, column_id=-1): if item is None: return self._current_index return item.model def get_current_index(self): return self._current_index.get_value_as_int() def set_current_index(self, index): self._current_index.set_value(index) def get_current_string(self): return self._items[self._current_index.get_value_as_int()].model.get_value_as_string() def is_default(self): return self.get_current_index() == self._default_index class IndeXAddVolume: class VolumeFormat(Enum): RAW, OPENVDB, PARTICLE_VOLUME = range(3) VOLUME_REPRESENTATIONS = { "NanoVDB": "vdb", "IndeX Sparse": "sparse_volume", } LABEL_ORDER_ROW_MAJOR = "Row-major (C-style)" LABEL_ORDER_COLUMN_MAJOR = "Column-major (Fortran-style)" LABEL_DEFAULT = "Default" LABEL_NONE = "None" def __init__(self, volume_format, ext, asset_file_path): self.volume_format = volume_format self.ext = ext self.asset_file_path = asset_file_path self.non_importer_field_names = [] self.importer_name = None self.extra_importer_settings = {} self.file_format = None def _on_add(self, dlg): importer_settings = self.extra_importer_settings render_settings = {} colormap = None shader = None volume_usd_path = dlg.get_value("volume_usd_path") valid = Sdf.Path.IsValidPathString(volume_usd_path) if not valid: dlg.hide() def on_error_ok(msg_dlg): msg_dlg.hide() # Show the main dialog again after showing the error # message. Having two modal dialogs visible at the same # time doesn't seem to be possible. dlg.show() #FIXME: This pops up at the top-left, not the center MessageDialog( message=f"Invalid USD path: '{volume_usd_path}'\nReason: '{valid[1]}'\nPlease ensure that the specified path is valid.", title="Error", ok_handler=on_error_ok, disable_cancel_button=True ).show() return False # Pass through generic importer arguments directly for key, value in dlg.get_values().items(): if key not in self.non_importer_field_names: if isinstance(value, bool): value = str(value).lower() # convert 'True' to 'true' importer_settings[key] = str(value) if self.volume_format == IndeXAddVolume.VolumeFormat.RAW: dims_model = dlg.get_field("dims").model sub_models = dims_model.get_item_children() dims = ( dims_model.get_item_value_model(sub_models[0]).as_int, dims_model.get_item_value_model(sub_models[1]).as_int, dims_model.get_item_value_model(sub_models[2]).as_int, ) for dim in dims: if dim <= 0: dlg.hide() def on_error_ok(msg_dlg): msg_dlg.hide() # Show the main dialog again after showing the error # message. Having two modal dialogs visible at the same # time doesn't seem to be possible. dlg.show() #FIXME: This pops up at the top-left, not the center MessageDialog( message=f"Invalid volume dimension specified: {dims}\nAll components must be positive.", title="Error", ok_handler=on_error_ok, disable_cancel_button=True ).show() return False importer_settings["size"] = dims importer_settings["voxel_format"] = dlg.get_field("voxel_format").model.get_current_string() importer_settings["convert_zyx_to_xyz"] = (dlg.get_field("data_order").model.get_current_string() == self.LABEL_ORDER_ROW_MAJOR) importer_settings["type"] = "sparse_volume" importer_settings["importer"] = "nv::index::plugin::base_importer.Sparse_volume_importer_raw" elif self.volume_format == IndeXAddVolume.VolumeFormat.OPENVDB: volume_type = dlg.get_field("type").model.get_current_string() if volume_type in IndeXAddVolume.VOLUME_REPRESENTATIONS: importer_settings["type"] = IndeXAddVolume.VOLUME_REPRESENTATIONS[volume_type] elif self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME: importer_settings["importer"] = self.importer_name importer_settings["type"] = "particle_volume" colormap = ColormapPresets.DEFAULT render_settings["renderingMode"] = dlg.get_field("renderingMode").model.get_current_string() fixed_point_width = dlg.get_value("fixedPointWidth") if (fixed_point_width > 0): importer_settings["fixed_radius"] = str(fixed_point_width / 2.0) subdivision_mode = dlg.get_field("subdivisionMode").model.get_current_string() if subdivision_mode != "current": carb.settings.get_settings().set("/rtx/index/overrideSubdivisionMode", subdivision_mode) subdivision_part_count = dlg.get_value("subdivisionPartCount") if subdivision_part_count > 0: carb.settings.get_settings().set("/rtx/index/overrideSubdivisionPartCount", subdivision_part_count) dlg.hide() colormap_field = dlg.get_field("colormap") if colormap_field and not colormap: colormap = colormap_field.model.get_current_string() if not ColormapPresets.has(colormap): colormap = None shader_field = dlg.get_field("shader") if shader_field and not shader: shader = shader_field.model.get_current_string() if not ShaderPresets.has(shader): shader = None omni.kit.commands.execute( "AddVolumeFileToStage", ext=self.ext, volume_path=volume_usd_path, asset_file_path=self.asset_file_path, volume_format=self.volume_format, importer_settings=importer_settings, render_settings=render_settings, colormap=colormap, shader=shader ) return True def show(self): def on_okay(dlg: FormDialog): return self._on_add(dlg) def combo_field(name, label, items, default=0): return FormDialog.FieldDef(name, label, lambda **kwargs: ui.ComboBox(ComboListModel(items, default), **kwargs), 0) fields = [] self.non_importer_field_names = [] file_name = os.path.basename(self.asset_file_path) (file_root, file_ext) = os.path.splitext(file_name) # Replace characters with special meaning in SdfPath by underscores file_root_usd_safe = file_root for ch in ['.', ':', '[', ']', '-', ' ']: file_root_usd_safe = file_root_usd_safe.replace(ch, '_') default_usd_path = f"/World/volume_{file_root_usd_safe}" fields.append(FormDialog.FieldDef("volume_usd_path", "USD Path: ", ui.StringField, default_usd_path)) self.non_importer_field_names.append("volume_usd_path") if self.volume_format == IndeXAddVolume.VolumeFormat.RAW: volume_format_label = 'RAW' default_dims = [0, 0, 0] # Look for dimensions encoded in the filename m = re.match('.*_(\d+)_(\d+)_(\d+)(_.*|$)', file_root) if m: default_dims = [ int(m[1]), int(m[2]), int(m[3]) ] fields.append(FormDialog.FieldDef( "dims", "Dimensions: ", lambda **kwargs: ui.MultiIntField(default_dims[0], default_dims[1], default_dims[2], **kwargs), 0)) self.non_importer_field_names.append("dims") voxel_format_list = [ 'uint8', 'uint16', 'sint16', 'rgba8', 'float16', 'float32', 'float32_4' ] fields.append(combo_field("voxel_format", "Voxel Format: ", voxel_format_list)) self.non_importer_field_names.append("voxel_format") fields.append(combo_field("data_order", "Data Order: ", [ self.LABEL_ORDER_ROW_MAJOR, self.LABEL_ORDER_COLUMN_MAJOR ])) self.non_importer_field_names.append("data_order") elif self.volume_format == IndeXAddVolume.VolumeFormat.OPENVDB: volume_format_label = 'OpenVDB' fields.append(FormDialog.FieldDef("input_file_field", "OpenVDB Data Field (optional): ", ui.StringField, "")) fields.append(combo_field("type", "Volume Representation: ", [ self.LABEL_DEFAULT ] + list(self.VOLUME_REPRESENTATIONS.keys()))) self.non_importer_field_names.append("type") elif self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME: volume_format_label = 'particle' rendering_modes_list = ["rbf", "solid_box", "solid_cone", "solid_cylinder", "solid_sphere", "solid_disc"] fields.append(combo_field("renderingMode", "Rendering Mode: ", rendering_modes_list, rendering_modes_list.index("solid_sphere"))) self.non_importer_field_names.append("renderingMode") fields.append(FormDialog.FieldDef("fixedPointWidth", "Fixed Point Width: ", ui.FloatField, 0.0)) self.non_importer_field_names.append("fixedPointWidth") file_format = file_ext.replace('.', '').lower() self.file_format = file_format if file_format == 'las': self.importer_name = "nv::index::plugin::base_importer.Particle_volume_importer_las" fields.append(FormDialog.FieldDef("offset_point_mode", "Offset Point Mode: ", ui.IntField, 2)) fields.append(FormDialog.FieldDef("radius_min", "Radius Min: ", ui.FloatField, 0.0)) fields.append(FormDialog.FieldDef("radius_max", "Radius Max: ", ui.FloatField, -1.0)) fields.append(FormDialog.FieldDef("radius_scale", "Radius Scale: ", ui.FloatField, 1.0)) fields.append(FormDialog.FieldDef("scale_color", "Color Scale: ", ui.FloatField, 1.0)) fields.append(FormDialog.FieldDef("ignore_las_offset", "Ignore LAS Offset: ", ui.CheckBox, True)) fields.append(FormDialog.FieldDef("ignore_zero_points", "Ignore Zero Points: ", ui.CheckBox, False)) elif file_format == 'pcd': self.importer_name = "nv::index::plugin::base_importer.Particle_volume_importer_point_cloud_data" fields.append(FormDialog.FieldDef("is_little_endian", "Little Endian: ", ui.CheckBox, False)) elif file_format == 'ptx': self.importer_name = "nv::index::plugin::base_importer.Particle_volume_importer_ptx" fields.append(FormDialog.FieldDef("ignore_zero_points", "Ignore Zero Points: ", ui.CheckBox, False)) fields.append(FormDialog.FieldDef("color_type_uint8", "Color Type UInt8: ", ui.CheckBox, True)) elif file_format == 'e57': self.importer_name = "nv::index::plugin::e57_importer.Particle_volume_importer_e57" # Do not bake the transformation into the point data, but provide the transformation matrix self.extra_importer_settings["apply_transform"] = "false" fields.append(FormDialog.FieldDef("__ignore_dataset_transform", "Ignore transformation: ", ui.CheckBox, False)) else: carb.log_error(f"ERROR: Unsupported particle volume format '{file_format} for file '{self.asset_file_path}.") subdivision_modes_list = ["current", "grid", "kd_tree"] fields.append(combo_field("subdivisionMode", "Subdivision Mode: ", subdivision_modes_list, subdivision_modes_list.index("current"))) self.non_importer_field_names.append("subdivisionMode") fields.append(FormDialog.FieldDef("subdivisionPartCount", "Subdivision Part Count: ", ui.IntField, 0)) self.non_importer_field_names.append("subdivisionPartCount") else: return if self.volume_format != IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME: fields.append(combo_field("colormap", "Add Colormap: ", [ self.LABEL_NONE ] + ColormapPresets.get_labels())) self.non_importer_field_names.append("colormap") fields.append(combo_field("shader", "Add XAC Shader: ", [ self.LABEL_NONE ] + ShaderPresets.get_labels())) self.non_importer_field_names.append("shader") dlg = FormDialog( width=600, message=f"Adding {volume_format_label} volume asset '{file_name}' to the stage:", title=f"Add {volume_format_label.capitalize()} Volume Asset", ok_label="Add", ok_handler=on_okay, field_defs=fields, ) dlg.show() def is_openvdb_file(path): return os.path.splitext(path)[1].lower() == ".vdb" def is_raw_file(path): return os.path.splitext(path)[1].lower() == ".raw" def is_particle_volume_file(path): supported_particle_volume_formats = [] file_formats = carb.settings.get_settings().get("/nvindex/state/supportedFileFormats") if file_formats: for f in file_formats: if f in ["las", "pcd", "ptx", "e57"]: supported_particle_volume_formats.append("." + f) return os.path.splitext(path)[1].lower() in supported_particle_volume_formats def is_maybe_raw_file(path): return not (is_openvdb_file(path) or is_particle_volume_file(path)) class IndeXImporters: OPENVDB_FILE_HANDLER_NAME = "IndeX OpenVDB File Open Handler" RAW_FILE_HANDLER_NAME = "IndeX RAW File Open Handler" PARTICLE_VOLUME_FILE_HANDLER_NAME = "IndeX ParticleVolume File Open Handler" CONTEXT_MENU_NAME_ADD_OPENVDB = "Add OpenVDB Volume Asset to Stage" CONTEXT_MENU_NAME_ADD_RAW = "Add RAW Volume Asset to Stage" CONTEXT_MENU_NAME_ADD_PARTICLE_VOLUME = "Add Particle Volume Asset to Stage" def register_bindings(ext): content.get_instance().add_file_open_handler( IndeXImporters.OPENVDB_FILE_HANDLER_NAME, open_fn=lambda path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.OPENVDB, ext, path).show(), file_type=is_openvdb_file ) content.get_instance().add_file_open_handler( IndeXImporters.RAW_FILE_HANDLER_NAME, open_fn=lambda path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.RAW, ext, path).show(), file_type=is_raw_file ) content.get_instance().add_file_open_handler( IndeXImporters.PARTICLE_VOLUME_FILE_HANDLER_NAME, open_fn=lambda path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME, ext, path).show(), file_type=is_particle_volume_file ) content.get_instance().add_context_menu( name=IndeXImporters.CONTEXT_MENU_NAME_ADD_RAW, glyph="menu_add.svg", click_fn=lambda name, path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.RAW, ext, path).show(), show_fn=is_maybe_raw_file ) content.get_instance().add_context_menu( name=IndeXImporters.CONTEXT_MENU_NAME_ADD_OPENVDB, glyph="menu_add.svg", click_fn=lambda name, path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.OPENVDB, ext, path).show(), show_fn=is_openvdb_file ) content.get_instance().add_context_menu( name=IndeXImporters.CONTEXT_MENU_NAME_ADD_PARTICLE_VOLUME, glyph="menu_add.svg", click_fn=lambda name, path: IndeXAddVolume(IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME, ext, path).show(), show_fn=is_particle_volume_file ) def deregister_bindings(ext): content.get_instance().delete_file_open_handler( IndeXImporters.OPENVDB_FILE_HANDLER_NAME) content.get_instance().delete_file_open_handler( IndeXImporters.RAW_FILE_HANDLER_NAME) content.get_instance().delete_file_open_handler( IndeXImporters.PARTICLE_VOLUME_FILE_HANDLER_NAME) content.get_instance().delete_context_menu( IndeXImporters.CONTEXT_MENU_NAME_ADD_OPENVDB) content.get_instance().delete_context_menu( IndeXImporters.CONTEXT_MENU_NAME_ADD_RAW) content.get_instance().delete_context_menu( IndeXImporters.CONTEXT_MENU_NAME_ADD_PARTICLE_VOLUME) class AddVolumeFileToStage(omni.kit.commands.Command): """ Add an volume file to the stage. Args: ext: the calling extension volume_path: USD path of the volume in the stage asset_file_path: the volume assset being loaded volume_format: 'openvdb' or 'raw' importer_settings: dictionary containing setting to pass to IndeX importer render_settings: dictionary containing settings for rendering the volume """ def __init__(self, ext, volume_path, asset_file_path, volume_format, importer_settings, render_settings, colormap, shader) -> None: self.ext = ext self.volume_path = volume_path self.asset_file_path = asset_file_path self.volume_format = volume_format self.importer_settings = importer_settings self.render_settings = render_settings self.colormap = colormap self.shader = shader self.stage = omni.usd.get_context().get_stage() self.volume_prim = None def do(self): if not self.ext: carb.log_error(f"ERROR: Tried to add volume {self.asset_file_path} when extension is already shut down") return False if not self.asset_file_path: carb.log_error(f"ERROR: Volume file {self.asset_file_path} is not defined") return False try: asset_name = "VolumeAsset" asset_path = f"{self.volume_path}/{asset_name}" material_path = f"{self.volume_path}/Material" colormap_path = f"{material_path}/Colormap" shader_path = f"{material_path}/VolumeShader" rel_name = "volume" # Create volume asset if self.volume_format == IndeXAddVolume.VolumeFormat.OPENVDB: volume_asset = UsdVol.OpenVDBAsset.Define(self.stage, asset_path) volume_asset_prim = volume_asset.GetPrim() field_name = self.importer_settings["input_file_field"] if field_name: rel_name = field_name volume_asset.GetFieldNameAttr().Set(field_name) elif self.volume_format == IndeXAddVolume.VolumeFormat.RAW: volume_asset_prim = self.stage.DefinePrim(asset_path, "FieldAsset") volume_asset = UsdVol.FieldAsset(volume_asset_prim) elif self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME: volume_asset_prim = self.stage.DefinePrim(asset_path, "FieldAsset") volume_asset = UsdVol.FieldAsset(volume_asset_prim) volume_asset.CreateFilePathAttr().Set(self.asset_file_path) # Add generic importer settings as customData for key, value in self.importer_settings.items(): # Skip keys that are handled explicitly if key not in ["input_file_field", "size", "type"]: volume_asset_prim.SetCustomDataByKey("nvindex.importerSettings:" + key, value) # Create volume volume = UsdVol.Volume.Define(self.stage, self.volume_path) volume.CreateFieldRelationship(rel_name, volume_asset.GetPath()) self.volume_prim = volume.GetPrim() # Mark the prim as to be handled by IndeX in compositing mode if carb.settings.get_settings().get("/nvindex/compositeRenderingMode"): self.volume_prim.CreateAttribute("nvindex:composite", Sdf.ValueTypeNames.Bool, custom=True).Set(True) self.volume_prim.CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool, custom=True).Set(True) if "size" in self.importer_settings: extent_attr = volume.CreateExtentAttr() extent_attr.Set([[0, 0, 0], self.importer_settings["size"]]) if "type" in self.importer_settings: type_attr = volume.GetPrim().CreateAttribute("nvindex:type", Sdf.ValueTypeNames.Token, True) type_attr.Set(self.importer_settings["type"]) # Add generic render settings as customData for key, value in self.render_settings.items(): self.volume_prim.SetCustomDataByKey("nvindex.renderSettings:" + key, value) if self.colormap or self.shader: # Create and connect material and empty shader material = UsdShade.Material.Define(self.stage, material_path) UsdShade.MaterialBindingAPI(volume.GetPrim()).Bind(material) shader = UsdShade.Shader.Define(self.stage, shader_path) shader_output = shader.CreateOutput("volume", Sdf.ValueTypeNames.Token) material.CreateVolumeOutput("nvindex").ConnectToSource(shader_output) if self.volume_format == IndeXAddVolume.VolumeFormat.PARTICLE_VOLUME: # Create default Phong material for particle volumes shader.SetShaderId("nvindex:phong_gl") shader.CreateImplementationSourceAttr().Set("id") shader.CreateInput("ambient", Sdf.ValueTypeNames.Float3).Set((0.1, 0.1, 0.1)) shader.CreateInput("diffuse", Sdf.ValueTypeNames.Float3).Set((1.0, 1.0, 1.0)) shader.CreateInput("specular", Sdf.ValueTypeNames.Float3).Set((0.4, 0.4, 0.4)) shader.CreateInput("shininess", Sdf.ValueTypeNames.Float).Set(10.0) shader.CreateInput("opacity", Sdf.ValueTypeNames.Float).Set(0.0) # indicates that particle color should be used if self.colormap: # Add colormap colormap = self.stage.DefinePrim(colormap_path, "Colormap") colormap_output = colormap.CreateAttribute("outputs:colormap", Sdf.ValueTypeNames.Token) shader.CreateInput("colormap", Sdf.ValueTypeNames.Token).ConnectToSource(colormap_output.GetPath()) colormapSource = "rgbaPoints" colormap.CreateAttribute("colormapSource", Sdf.ValueTypeNames.Token).Set(colormapSource) (xPoints, rgbaPoints) = ColormapPresets.generate(self.colormap, colormap_source=colormapSource) colormap.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set(xPoints) colormap.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set(rgbaPoints) colormap.CreateAttribute("domain", Sdf.ValueTypeNames.Float2).Set((0.0, 1.0)) if self.shader: # Add shader source code shader.SetSourceCode(ShaderPresets.get(self.shader), "xac") return True except Exception as e: carb.log_warn(f"ERROR: Cannot add volume asset {self.asset_file_path}: {e}") return False def undo(self): if not self.ext: carb.log_error(f"Cannot undo adding volume {self.asset_file_path}. Extension is no longer loaded.") return False current_stage = omni.usd.get_context().get_stage() if current_stage != self.stage or self.volume_prim is None or not self.volume_prim.IsValid(): carb.log_warn(f"Cannot undo adding volume {self.asset_file_path}. Stage is no longer loaded.") return False try: self.stage.RemovePrim(self.volume_prim.GetPath()) self.volume_prim = None return True except Exception as e: carb.log_warn(f"ERROR: Cannot remove volume {self.asset_file_path}: {e}") return False omni.kit.commands.register_all_commands_in_module(__name__)
25,920
Python
46.043557
145
0.618056
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/presets/colormap_presets.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. # class ColormapPresets: DEFAULT = "Grayscale Ramp" GENERATORS = { # Simple color ramp from fully transparent white to semi-transparent gray DEFAULT: lambda size, src : ColormapPresets._generate_ramp(size, src), "Darker Grayscale Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (1, 1, 1, 0), (0, 0, 0, 0.5)), # Same, but with one color "Red Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (1, 0, 0, 0), (0.5, 0.0, 0.0, 0.5)), "Green Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (0, 1, 0, 0), (0.0, 0.0, 0.0, 0.5)), "Blue Ramp": lambda size, src : ColormapPresets._generate_ramp(size, src, (0, 0, 1, 0), (0.0, 0.0, 0.0, 0.5)), # Three colors "White-Yellow-Red": lambda size, src : ColormapPresets._generate_three_colors( size, src, (1.0, 1.0, 1.0), (1.0, 1.0, 0.0), (1.0, 0.0, 0.0), 0.0, 0.5), "Red-Green-Blue": lambda size, src : ColormapPresets._generate_three_colors( size, src, (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), 0.0, 0.5), "Blue-White-Red": lambda size, src : ColormapPresets._generate_three_colors( size, src, (0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0), 0.0, 0.5), "Black-Red-Yellow": lambda size, src : ColormapPresets._generate_three_colors( size, src, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), 0.0, 0.5), "Black-Blue-White": lambda size, src : ColormapPresets._generate_three_colors( size, src, (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (1.0, 1.0, 1.0), 0.0, 0.5), } def _generate_ramp(colormap_size = 256, colormap_source = "", ramp_min = (1.0, 1.0, 1.0, 0.0), ramp_max = (0.5, 0.5, 0.5, 0.5)): if colormap_source == "rgbaPoints": return ( [0, 1], # xPoints [ramp_min, ramp_max] # rgbaPoints ) c = [0, 0, 0, 0] colormap_data = [tuple(c)] * colormap_size for i in range(colormap_size): u = i / (colormap_size - 1) for j in range(4): c[j] = ramp_min[j] * (1.0 - u) + ramp_max[j] * u colormap_data[i] = tuple(c) return colormap_data def _generate_three_colors(colormap_size, colormap_source, color1, color2, color3, opacity_ramp_min = 0.0, opacity_ramp_max = 0.5): if colormap_source == "rgbaPoints": opacity_ramp_mid = (opacity_ramp_min + opacity_ramp_max) / 2 return ( [0, 0.5, 1], # xPoints [color1 + (opacity_ramp_min,), color2 + (opacity_ramp_mid,), color3 + (opacity_ramp_max,)] # rgbaPoints ) c = [0, 0, 0, 0] colormap_data = [tuple(c)] * colormap_size for i in range(colormap_size): u = i / (colormap_size - 1) for j in range(3): if u < 0.5: c[j] = color1[j] * (1.0 - u) + color2[j] * u else: c[j] = color2[j] * (1.0 - u) + color3[j] * u c[3] = opacity_ramp_min * (1.0 - u) + opacity_ramp_max * u colormap_data[i] = tuple(c) return colormap_data def get_labels(): return list(ColormapPresets.GENERATORS.keys()) def generate(label, colormap_size = 256, colormap_source = ""): if label in ColormapPresets.GENERATORS: return ColormapPresets.GENERATORS[label](colormap_size, colormap_source) else: return None def has(label): return (label in ColormapPresets.GENERATORS)
4,152
Python
46.193181
135
0.544316
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/presets/__init__.py
from .colormap_presets import ColormapPresets from .shader_presets import ShaderPresets
88
Python
28.666657
45
0.863636
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/presets/shader_presets.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. # class ShaderPresets: SHADERS = { "Minimal Volume Shader": """\ NV_IDX_XAC_VERSION_1_0 using namespace nv::index::xac; class Volume_sample_program { NV_IDX_VOLUME_SAMPLE_PROGRAM public: NV_IDX_DEVICE_INLINE_MEMBER void initialize() {} NV_IDX_DEVICE_INLINE_MEMBER int execute( const Sample_info_self& sample_info, Sample_output& sample_output) { // get reference to the volume and its colormap const auto& volume = state.self; const Colormap& colormap = state.self.get_colormap(); // generate a volume sampler const auto sampler = volume.generate_sampler<float>(); // get current sample position const float3& sample_position = sample_info.sample_position_object_space; // sample the volume at the current position const float sample_value = sampler.fetch_sample(sample_position); // apply the colormap const float4 sample_color = colormap.lookup(sample_value); // store the output color sample_output.set_color(sample_color); return NV_IDX_PROG_OK; } }; """, "Red Shader": """\ NV_IDX_XAC_VERSION_1_0 using namespace nv::index::xac; class Volume_sample_program { NV_IDX_VOLUME_SAMPLE_PROGRAM public: NV_IDX_DEVICE_INLINE_MEMBER void initialize() {} NV_IDX_DEVICE_INLINE_MEMBER int execute( const Sample_info_self& sample_info, Sample_output& sample_output) { // get reference to the volume and its colormap const auto& volume = state.self; const Colormap& colormap = state.self.get_colormap(); // generate a volume sampler const auto sampler = volume.generate_sampler<float>(); // get current sample position const float3& sample_position = sample_info.sample_position_object_space; // sample the volume at the current position const float sample_value = sampler.fetch_sample(sample_position); // apply the colormap float4 sample_color = colormap.lookup(sample_value); // make it more reddish sample_color.x = 1.f; // store the output color sample_output.set_color(sample_color); return NV_IDX_PROG_OK; } }; """, } def get_labels(): return list(ShaderPresets.SHADERS.keys()) def get(label): if label in ShaderPresets.SHADERS: return ShaderPresets.SHADERS[label] else: return None def has(label): return (label in ShaderPresets.SHADERS)
3,027
Python
26.279279
81
0.65147
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/common_settings.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. # from omni.kit.widget.settings import SettingType import omni.ui as ui import carb import omni.kit.app from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame from omni.rtx.window.settings.rendersettingsdefaults import SettingsDefaultHandler class SceneSettingsFrame(SettingsCollectionFrame): def _build_ui(self): self._add_setting( SettingType.DOUBLE3, "Region of Interest Min", "/rtx/index/regionOfInterestMin", tooltip="Start of region of interest", has_reset=False, ) self._add_setting( SettingType.DOUBLE3, "Region of Interest Max", "/rtx/index/regionOfInterestMax", tooltip="End of region of interest", has_reset=False, ) self._change_cb1 = omni.kit.app.SettingChangeSubscription("/nvindex/dataBboxMin", self._on_change) self._change_cb2 = omni.kit.app.SettingChangeSubscription("/nvindex/dataBboxMax", self._on_change) dataBboxMin = self._settings.get("/nvindex/dataBboxMin") dataBboxMax = self._settings.get("/nvindex/dataBboxMax") def do_reset_to_scene_extent(): self._settings.set("/rtx/index/regionOfInterestMin", dataBboxMin) self._settings.set("/rtx/index/regionOfInterestMax", dataBboxMax) if dataBboxMin and dataBboxMax: dataBboxValid = True for i in range(0, 3): if (dataBboxMin[i] >= dataBboxMax[i]): dataBboxValid = False if dataBboxValid: ui.Button("Reset to Data Extent", tooltip="Resets the region of interest to contain all scene element", clicked_fn=do_reset_to_scene_extent) self._add_setting( SettingType.FLOAT, "Default Point Width", "/rtx/index/defaultPointWidth", tooltip="Default point width for new point clouds loaded from USD. If set to 0, a simple heuristic will be used.", ) if self._settings.get("/nvindex/showAdvancedSettings"): subdivisionModeItems = { "Default": "", "Grid": "grid", "KD-tree": "kd_tree", } self._add_setting_combo( "Override Subdivision Mode", "/rtx/index/overrideSubdivisionMode", subdivisionModeItems, tooltip="Override data subdivision mode, only affects newly added datasets." ) self._add_setting( SettingType.INT, "Override Subdivision Part Count", "/rtx/index/overrideSubdivisionPartCount", 0, 256, tooltip="Override number of parts for kd_tree subdivision, only affects newly added datasets." ) def destroy(self): self._change_cb1 = None self._change_cb2 = None super().destroy() class RenderSettingsFrame(SettingsCollectionFrame): def _build_ui(self): composite_rendering = self._settings.get("/nvindex/compositeRenderingMode") if composite_rendering: self._add_setting( SettingType.FLOAT, "Color Scaling", "/rtx/index/colorScale", 0.0, 100.0, tooltip="Scale factor for color output", ) else: self._add_setting( SettingType.COLOR3, "Background Color", "/rtx/index/backgroundColor", tooltip="Color of scene background", ) if self._settings.get("/nvindex/showAdvancedSettings"): self._add_setting( SettingType.FLOAT, "Background Opacity", "/rtx/index/backgroundOpacity", 0.0, 1.0, tooltip="Opacity of scene background", ) self._add_setting( SettingType.BOOL, "Frame Buffer Blending", "/rtx/index/frameBufferBlending", tooltip="Blend rendering result to frame buffer", ) self._add_setting( SettingType.INT, "Rendering Samples", "/rtx/index/renderingSamples", 1, 32, tooltip="Number of samples per pixel used during rendering", ) class CompositingSettingsFrame(SettingsCollectionFrame): def _build_ui(self): self._add_setting( SettingType.BOOL, "Automatic Span Control", "/rtx/index/automaticSpanControl", tooltip="Automatically optimize the number of spans used for compositing", ) self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/index/automaticSpanControl", self._on_change) if not self._settings.get("/rtx/index/automaticSpanControl"): self._add_setting( SettingType.INT, "Horizontal spans", "/rtx/index/nbSpans", 1, 100, tooltip="Number of spans used for compositing, when automatic span control is not used", ) self._add_setting( SettingType.INT, "Host Span Limit", "/rtx/index/maxSpansPerMachine", 1, 100, tooltip="Maximum number of spans per host", ) def destroy(self): self._change_cb = None super().destroy() class AdvancedSettingsFrame(SettingsCollectionFrame): def _build_ui(self): self._add_setting( SettingType.BOOL, "Monitor Performance Values", "/rtx/index/monitorPerformanceValues", tooltip="Print performance statistics to stdout", ) self._add_setting( SettingType.STRING, "Session Export File (optional)", "/nvindex/exportSessionFilename", tooltip="Absolute path where to write the session export to. If empty, the log will be used.", ) self._change_cb = omni.kit.app.SettingChangeSubscription("/nvindex/exportSessionFilename", self._on_change) def do_export_session(): self._settings.set("/nvindex/exportSession", True) exportTarget = "File" if self._settings.get("/nvindex/exportSessionFilename") else "Log" ui.Button("Export Session to " + exportTarget, tooltip="Export session information", clicked_fn=do_export_session) restart_msg = "changing it requires restarting IndeX" logLevelItems = { "Debug": "debug", "Verbose": "verbose", "Info": "info", "Warning": "warning", "Error": "error", "Fatal": "fatal", } self._add_setting_combo( "Log Level", "/nvindex/logLevel", logLevelItems, tooltip="Log level for IndeX log message, " + restart_msg, ) def do_restart_index(): self._settings.set("/nvindex/restartIndex", True) ui.Button("Restart IndeX", tooltip="Restart the NVIDIA IndeX session, reloading all data", clicked_fn=do_restart_index) def destroy(self): self._change_cb = None super().destroy() class IndeXCommonSettingStack(RTXSettingsStack): def __init__(self) -> None: self._stack = ui.VStack(spacing=10) self._settings = carb.settings.get_settings() with self._stack: SceneSettingsFrame("Scene Settings", parent=self) RenderSettingsFrame("Render Settings", parent=self) if self._settings.get("/nvindex/showAdvancedSettings"): CompositingSettingsFrame("Compositing Settings", parent=self) AdvancedSettingsFrame("Advanced", parent=self) ui.Spacer()
8,550
Python
34.334711
127
0.579181
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/volume_properties_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.settings import omni.kit.app import omni.ui as ui from pxr import Sdf, UsdShade from ..presets import ColormapPresets from .index_properties_base_widget import IndexPropertiesBaseWidget class VolumePropertiesWidget(IndexPropertiesBaseWidget): point_cloud_types = [ "PointCloud", "StreamingSettings"] def __init__(self): self.settings = carb.settings.get_settings() super().__init__("IndeX Volume", ["Volume", "Points"] + VolumePropertiesWidget.point_cloud_types) self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/index/compositeEnabled", self._on_change) def clean(self): self._change_cb = None super().clean() def _on_change(self, *_): self.request_rebuild() def set_volume_type(self, combo_model, item): prim = self.get_prim() volume_type = combo_model.get_current_string() if volume_type == "default": prim.GetAttribute("nvindex:type").Clear() else: prim.CreateAttribute("nvindex:type", Sdf.ValueTypeNames.Token, True, Sdf.VariabilityUniform).Set(volume_type) self.request_rebuild() # update UI to change mode def get_compositing(self): return self.get_prim().GetAttribute("nvindex:composite").Get() == True def set_compositing(self, enable): self.get_prim().CreateAttribute("nvindex:composite", Sdf.ValueTypeNames.Bool, custom=True).Set(enable) if enable: self.set_rtx_skip(True) # don't disable it here self.request_rebuild() # update UI def get_rtx_skip(self): return self.get_prim().GetAttribute("omni:rtx:skip").Get() == True def set_rtx_skip(self, skip): self.get_prim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool, custom=True).Set(skip) def create_material(self): volume_prim = self.get_prim() stage = volume_prim.GetStage() material_path_base = str(volume_prim.GetPath()) + "/Material" material_path = material_path_base # Make material path unique i = 0 while stage.GetPrimAtPath(material_path): i += 1 material_path = material_path_base + str(i) colormap_path = f"{material_path}/Colormap" shader_path = f"{material_path}/VolumeShader" colormap = stage.DefinePrim(colormap_path, "Colormap") colormap_output = colormap.CreateAttribute("outputs:colormap", Sdf.ValueTypeNames.Token) colormap.CreateAttribute("domain", Sdf.ValueTypeNames.Float2).Set((0.0, 1.0)) material = UsdShade.Material.Define(stage, material_path) binding_api = UsdShade.MaterialBindingAPI.Apply(volume_prim) binding_api.Bind(material) shader = UsdShade.Shader.Define(stage, shader_path) shader_output = shader.CreateOutput("volume", Sdf.ValueTypeNames.Token) material.CreateVolumeOutput("nvindex").ConnectToSource(shader_output) shader.CreateInput("colormap", Sdf.ValueTypeNames.Token).ConnectToSource(colormap_output.GetPath()) colormapSource = "rgbaPoints" colormap.CreateAttribute("colormapSource", Sdf.ValueTypeNames.Token).Set(colormapSource) (xPoints, rgbaPoints) = ColormapPresets.generate(ColormapPresets.DEFAULT, colormap_source=colormapSource) colormap.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set(xPoints) colormap.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set(rgbaPoints) def build_properties(self, stage, prim, prim_path): with ui.VStack(spacing=5): # Volume type current_volume_type = prim.GetAttribute("nvindex:type").Get() if not current_volume_type and (prim.GetTypeName() == "Points" or prim.GetTypeName() in VolumePropertiesWidget.point_cloud_types): current_volume_type = "particle_volume" if self._collapsable_frame: self._collapsable_frame.title = "IndeX Points" if self.settings.get("/nvindex/compositeRenderingMode") and prim.GetTypeName() not in VolumePropertiesWidget.point_cloud_types: if not self.settings.get("/rtx/index/compositeEnabled"): self.build_label( "NVIDIA IndeX Compositing is currently not active. " "You can enable it in 'Render Settings / Common / NVIDIA IndeX Compositing'.", full_width=True) ui.Separator() # Enable/disable composite rendering for this prim with ui.HStack(): self.build_label("Use IndeX compositing") widget = ui.CheckBox(name="nvindex_composite") widget.model.set_value(self.get_compositing()) widget.model.add_value_changed_fn(lambda m: self.set_compositing(m.get_value_as_bool())) with ui.HStack(): self.build_label("Skip in RTX renderer") widget = ui.CheckBox(name="rtx_skip") widget.model.set_value(self.get_rtx_skip()) widget.model.add_value_changed_fn(lambda m: self.set_rtx_skip(m.get_value_as_bool())) # Skip rest of UI unless compositing is enabled if not self.get_compositing(): return ui.Separator() with ui.HStack(): self.build_label("Volume Type") volume_types_list = ["vdb", "sparse_volume"] if current_volume_type is None or current_volume_type in volume_types_list: self.volume_type_widget = ui.ComboBox(self.create_combo_list_model(current_volume_type, ["default"] + volume_types_list), name="volume_type") self.volume_type_widget.model.add_item_changed_fn(self.set_volume_type) else: self.build_label(current_volume_type) render_settings = prim.GetCustomDataByKey(self.USD_RENDERSETTINGS) if current_volume_type != "irregular_volume": # Common settings (except for irregular volumes) self.build_render_setting_float( "Sampling Distance", "samplingDistance", -1.0, render_settings) self.build_render_setting_float( "Reference Sampling Distance", "referenceSamplingDistance", -1.0, render_settings) if current_volume_type == "sparse_volume": # self.build_render_setting_int3( # "Voxel Offsets", "voxelOffsets", # [-1.0, -1.0, -1.0], # render_settings) # Filter Mode self.build_render_setting_combo_box( "Filter Mode", "filterMode", ["default", "nearest", "trilinear", "trilinear_pre", "tricubic_catmull", "tricubic_catmull_pre", "tricubic_bspline", "tricubic_bspline_pre"], render_settings) self.build_render_setting_bool( "LOD Rendering", "lodRenderingEnabled", False, render_settings) self.build_render_setting_float( "LOD Pixel Threshold", "lodPixelThreshold", -1.0, render_settings) self.build_render_setting_bool( "Preintegration", "preintegratedVolumeRendering", False, render_settings) elif current_volume_type == "particle_volume": self.build_render_setting_combo_box( "Rendering Mode", "renderingMode", ["default", "rbf", "solid_box", "solid_cone", "solid_cylinder", "solid_sphere", "solid_disc"], render_settings) self.build_render_setting_combo_box( "RBF Falloff Kernel", "rbfFalloffKernel", ["default", "constant", "linear", "hermite", "spline"], render_settings) # Prefer point width as it is used by USD, but also support IndeX point radius if render_settings and "overrideFixedRadius" in render_settings: self.build_render_setting_float( "Override Fixed Radius", "overrideFixedRadius", -1.0, render_settings) else: self.build_render_setting_float( "Override Fixed Width", "overrideFixedWidth", -1.0, render_settings) if prim.GetTypeName() in VolumePropertiesWidget.point_cloud_types: self.build_render_setting_float( "Spacing Point Width Factor", "spacingPointWidthFactor", -1.0, render_settings) elif current_volume_type == "irregular_volume": self.build_render_setting_float( "Halo Size", "haloSize", -1.0, render_settings) self.build_render_setting_int( "Sampling Mode", "samplingMode", -1, render_settings) self.build_render_setting_float( "Sampling Segment Length", "samplingSegmentLength", -1.0, render_settings) self.build_render_setting_float( "Sampling Reference Segment Length", "samplingReferenceSegmentLength", -1.0, render_settings) else: # vdb (default) # Filter Mode self.build_render_setting_combo_box( "Filter Mode", "filterMode", ["default", "nearest", "trilinear"], render_settings) self.build_render_setting_int( "Subset Voxel Border", "subsetVoxelBorder", -1, render_settings) if self.show_advanced_settings: if current_volume_type == "irregular_volume": self.build_render_setting_int( "Diagnostics Mode", "diagnosticsMode", 0, render_settings) self.build_render_setting_int( "Diagnostics Flags", "diagnosticsFlags", 0, render_settings) self.build_render_setting_float( "Wireframe Size", "wireframeSize", 0.001, render_settings) self.build_render_setting_float( "Wireframe Color Mod Begin", "wireframeColorModBegin", 0.0, render_settings) self.build_render_setting_float( "Wireframe Color Mod Factor", "wireframeColorModFactor", 0.0, render_settings) else: self.build_render_setting_int( "Debug Visualization", "debugVisualizationOption", 0, render_settings) # Show timestep only if already defined timestep = prim.GetAttribute("nvindex:timestep") if timestep: with ui.HStack(): self.build_label("Timestep") widget = ui.FloatField(name="timestep") widget.model.set_value(timestep.Get() or 0.0) widget.model.add_value_changed_fn(lambda m: self.store_value("nvindex:timestep", m.get_value_as_float(), 0.0, Sdf.ValueTypeNames.Double)) with ui.HStack(): ui.Button("Create Volume Material", clicked_fn=self.create_material, name="createVolumeMaterial")
12,537
Python
42.839161
161
0.564011
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/cluster_settings.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. # from omni.kit.widget.settings import SettingType import omni.ui as ui import carb import omni.kit.app from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame from omni.rtx.window.settings.rendersettingsdefaults import SettingsDefaultHandler class ClusterCompositingSettingsFrame(SettingsCollectionFrame): def _build_ui(self): compositingModeItems = { "All": "COMPOSITING_ALL", "Local Only": "COMPOSITING_LOCAL_ONLY", "Remote Only": "COMPOSITING_REMOTE_ONLY", "None": "NO_COMPOSITING" } self._add_setting_combo( "Compositing Mode", "/rtx/index/compositingMode", compositingModeItems, tooltip="Control distribution of the compositing workload", ) if not self._settings.get("/nvindex/showAdvancedSettings"): return self._add_setting( SettingType.BOOL, "Transfer Span Alpha Channel", "/rtx/index/spanAlphaChannel", tooltip="Enable transfer of the alpha channel for horizontal span image data", ) self._add_setting( SettingType.BOOL, "Span Image Encoding", "/rtx/index/spanImageEncoding", tooltip="Use special image encoding to improve compression for horizontal span image data", ) self._add_setting( SettingType.BOOL, "Tile Image Encoding", "/rtx/index/tileImageEncoding", tooltip="Use special image encoding to improve compression for intermediate tile image data", ) self._add_setting( SettingType.INT, "Span Compression Level", "/rtx/index/spanCompressionLevel", 0, 9, tooltip="Compression level for transfer of horizontal span image data", ) self._add_setting( SettingType.INT, "Tile Compression Level", "/rtx/index/tileCompressionLevel", 0, 9, tooltip="Compression level for transfer of intermediate tiles image data", ) self._add_setting( SettingType.INT, "Span Compression Mode", "/rtx/index/spanCompressionMode", 0, 9, tooltip="Compression mode for transfer of horizontal span image data", ) self._add_setting( SettingType.INT, "Tile Compression Mode", "/rtx/index/tileCompressionMode", 0, 9, tooltip="Compression mode for transfer of intermediate tiles image data", ) self._add_setting( SettingType.INT, "Span Compression Threads", "/rtx/index/spanCompressionThreads", 0, 64, tooltip="Number of threads to use for compressing horizontal span image data (0=default)", ) self._add_setting( SettingType.INT, "Tile Compression Threads", "/rtx/index/tileCompressionThreads", 0, 64, tooltip="Number of threads to use for compressing intermediate tiles image data (0=default)", ) if self._settings.get("/nvindex/compositeRenderingMode"): self._add_setting( SettingType.INT, "Depth Buffer Compression Level", "/rtx/index/depthBufferCompressionLevel", 0, 9, tooltip="Compression level for transfer of depth buffer data", ) self._add_setting( SettingType.INT, "Depth Buffer Compression Mode", "/rtx/index/depthBufferCompressionMode", 0, 9, tooltip="Compression mode for transfer of depth buffer data", ) self._add_setting( SettingType.INT, "Depth Buffer Compression Threads", "/rtx/index/depthBufferCompressionThreads", 0, 64, tooltip="Number of threads to use for compressing depth buffer data (0=default)", ) class ClusterNetworkSettingsFrame(SettingsCollectionFrame): def _build_ui(self): network_enabled_path = "/nvindex/state/networkEnabled" cluster_message_path = "/nvindex/state/clusterMessage" self._change_cb_network_enabled = omni.kit.app.SettingChangeSubscription(network_enabled_path, self._on_change) self._change_cb_cluster_message = omni.kit.app.SettingChangeSubscription(cluster_message_path, self._on_change) restart_msg = "changing it requires restarting IndeX" networkModeItem = { "UDP": "udp", "TCP": "tcp", "OFF": "off", } self._add_setting_combo( "Network Mode", "/nvindex/networkMode", networkModeItem, tooltip="Mode for IndeX cluster mode, " + restart_msg, ) self._add_setting( SettingType.STRING, "Discovery Address", "/nvindex/discoveryAddress", tooltip="Discovery address for cluster mode, " + restart_msg, ) self._add_setting( SettingType.STRING, "Multicast Address", "/nvindex/multicastAddress", tooltip="Multicast address for cluster mode, " + restart_msg ) self._add_setting( SettingType.STRING, "Cluster Interface Address", "/nvindex/clusterInterfaceAddress", tooltip="Network interface to use cluster mode, " + restart_msg ) self._add_setting( SettingType.INT, "Minimum Cluster Size", "/nvindex/minimumClusterSize", tooltip="Minimum size of the cluster to start rendering" ) serviceModeItems = { "Rendering + Compositing ": "rendering_and_compositing", "Rendering only": "rendering", "Compositing only": "compositing", "None": "none", } self._add_setting_combo( "Service Mode", "/nvindex/clusterServiceMode", serviceModeItems, tooltip="Service mode of the current host, use 'None' render remotely only, " + restart_msg, ) self._add_setting( SettingType.STRING, "Cluster Identifier", "/nvindex/clusterIdentifier", tooltip="Optional identifier, must be the same on all hosts, " + restart_msg, ) def do_restart_index(): self._settings.set("/nvindex/restartIndex", True) ui.Button("Restart IndeX", tooltip="Restart the NVIDIA IndeX session, reloading all data", clicked_fn=do_restart_index) if self._settings.get(network_enabled_path): ui.Label("Cluster State:", alignment=ui.Alignment.CENTER) ui.Label(self._settings.get(cluster_message_path), word_wrap=True) def destroy(self): self._change_cb = None self._change_cb_network_enabled = None self._change_cb_cluster_message = None super().destroy() class IndeXClusterSettingStack(RTXSettingsStack): def __init__(self) -> None: self._stack = ui.VStack(spacing=10) self._settings = carb.settings.get_settings() with self._stack: ClusterCompositingSettingsFrame("Cluster Compositing Settings", parent=self) ClusterNetworkSettingsFrame("Network Settings", parent=self) ui.Spacer()
8,227
Python
33.717299
127
0.587213
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/ramp.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 asyncio import functools from tokenize import Double import numpy as np import omni.kit as ok import omni.ui as ui import omni.usd as ou from pxr import Gf # will be eventually unified with omni.ramp extension class RampValues: def __init__(self, prim_path=None, pos_attr_name=None, val_attr_name=None, old_positions=None, old_values=None, new_positions=None, new_values=None): self.prim_path = prim_path self.pos_attr_name = pos_attr_name self.val_attr_name = val_attr_name self.old_pos = old_positions self.old_val = old_values self.new_pos = new_positions self.new_val = new_values class IndexSetRampValuesCommand(ok.commands.Command): def __init__(self, ramps, **kwargs): self.ramps = ramps def do(self): stage = ou.get_context().get_stage() if not stage: return for ramp in self.ramps: prim = stage.GetPrimAtPath(ramp.prim_path) if not prim: return if ramp.new_pos and ramp.new_val: pos_attr = prim.GetAttribute(ramp.pos_attr_name) val_attr = prim.GetAttribute(ramp.val_attr_name) if pos_attr and val_attr: pos_attr.Set(ramp.new_pos) val_attr.Set(ramp.new_val) def undo(self): stage = ou.get_context().get_stage() if not stage: return for ramp in self.ramps: prim = stage.GetPrimAtPath(ramp.prim_path) if not prim: return if ramp.old_pos and ramp.old_val: pos_attr = prim.GetAttribute(ramp.pos_attr_name) val_attr = prim.GetAttribute(ramp.val_attr_name) if pos_attr and val_attr: pos_attr.Set(ramp.old_pos) val_attr.Set(ramp.old_val) ok.commands.register(IndexSetRampValuesCommand) class RampModel: positions_attr_name = "" values_attr_name = "" default_key_positions = [0] default_key_values = [(0, 0, 0, 0)] ALPHA_INDEX = 3 SCALAR_INDEX = 0 def __init__(self, ramp_type, selected, prim, attr_names, default_keys=None, clamp_values=True): self.ramp_type = ramp_type self.context = ou.get_context() self.prim = prim if prim: self.prim_path = prim.GetPath() else: self.prim_path = None self.clamp_values = clamp_values if type(attr_names) == list: self.positions_attr_name = attr_names[0] self.values_attr_name = attr_names[1] if type(default_keys) == list: self.default_key_positions = default_keys[0] self.default_key_values = default_keys[1] # # # widget models - subscribe to get updates # current selected index self.selected = selected # value on selected index self.value = [] * 4 # position on selected index self.position = None # show only range up to max_display_value self.max_range = None self.min_value = 0 self.max_value = 1 self.max_display_value = 1 self.key_positions_attr = None self.key_values_attr = None self.key_positions = [] self.key_values = [] self.num_keys = 0 self.range = 1 self.stage = self.context.get_stage() if self.stage: if self.prim: self.key_positions_attr = self.prim.GetAttribute(self.positions_attr_name) self.key_values_attr = self.prim.GetAttribute(self.values_attr_name) # public # call this when the ramp has to sync with the usd stage def update(self): #print("update") self.stage = self.context.get_stage() if not self.stage: return -1 self.prim = self.stage.GetPrimAtPath(self.prim_path) if not self.prim: return -1 self.key_positions_attr = self.prim.GetAttribute(self.positions_attr_name) self.key_values_attr = self.prim.GetAttribute(self.values_attr_name) self.initialize_if_empty_ramp() if self.key_positions_attr: self.key_positions = list(self.key_positions_attr.Get()) if self.key_values_attr: self.key_values = list(self.key_values_attr.Get()) self.update_num_keys() if len(self.key_positions) <= self.selected.as_int: return len(self.key_positions) - 1 if len(self.key_values) <= self.selected.as_int: return len(self.key_values) - 1 return -1 def update_position(self): #print("update position") if not self.position: return index = self.selected.as_int position = self.position.as_float self.key_positions = list(self.key_positions_attr.Get()) self.key_values = list(self.key_values_attr.Get()) # update keys data, order them if user dragged one in front, or behind others self.key_positions[index] = position new_index = self.order_keys(index, position) if new_index != index: self.key_values_attr.Set(self.key_values) return new_index def save_and_select_position(self, index): self.key_positions_attr.Set(self.key_positions) self.select_index(index) def update_value(self, is_scalar=False, scalar_index=-1): #print("update value: scalar: "+str(is_scalar)+" index: "+str(scalar_index) + " (clamping: "+str(self.clamp_values)+", ramptype: "+self.ramp_type+")") #print(" - self value: "+str(self.value)) if not self.value: return # get currently selected key index = self.selected.as_int if is_scalar: if scalar_index < 0: value = self.value[RampModel.SCALAR_INDEX].as_float else: value = self.value[scalar_index].as_float # clamp set value if self.clamp_values: value = max(self.min_value, value) if scalar_index < 0: self.key_values[index] = value else: self.key_values[index][scalar_index] = value self.update_limits(scalar_index) else: if self.clamp_values: value_r = max(self.min_value, self.value[0].as_float) value_g = max(self.min_value, self.value[1].as_float) value_b = max(self.min_value, self.value[2].as_float) # get alpha value from RGBA array value_alpha = self.key_values[index][RampModel.ALPHA_INDEX] self.key_values[index] = Gf.Vec4f(value_r, value_g, value_b, value_alpha) else: # get alpha value from RGBA array value_alpha = self.key_values[index][RampModel.ALPHA_INDEX] self.key_values[index] = Gf.Vec4f(self.value[0].as_float, self.value[1].as_float, self.value[2].as_float, value_alpha) # update key value entries self.key_values_attr.Set(self.key_values) def update_limits(self, scalar_index): #print("update limits on "+str(self.ramp_type)+" ["+str(self.min_value)+","+str(self.max_value)+"], scalar index: "+str(scalar_index)) if len(self.key_values) == 0: return if self.max_range and self.max_range.as_bool: self.max_value = 1 self.range = self.max_display_value - self.min_value else: if (scalar_index < 0): # check ramp type if (self.ramp_type == "alpha"): # select max only from alpha entries #self.max_value = max(np.array(self.key_values).T[self.ALPHA_INDEX]) # AK: use fixed max range self.max_value = 1.0 else: # select max from all values #self.max_value = max(self.key_values) # AK: use fixed range self.max_value = 1.0 else: #max(np.array(self.key_values).T[scalar_index]) self.max_value = 1.0 self.range = self.max_value - self.min_value self.range = self.max_value - self.min_value def save_position(self, index, position): # update widgets self.position.set_value(position) def save_value(self, value, is_scalar, scalar_index): self.key_values = list(self.key_values_attr.Get()) index = self.selected.as_int if is_scalar: # AK: update widgets if scalar_index < 0: #print(" * ramp.save_value: set scalar index with negative index: "+ str(scalar_index)) #print(" - retrieving value ("+str(len(self.value))+") at: "+str(RampModel.SCALAR_INDEX)) #print("* - value ("+str(value)+") scalar_index: "+str(scalar_index)+ " (is_scalar: "+str(is_scalar)+")") #print(" - selected index: "+str(self.selected.as_int)) # update currently selected value self.value[RampModel.SCALAR_INDEX].set_value(value) else: #print(" - ramp ("+str(self.ramp_type)+") save_value: set scalar "+str(value)+" index: "+ str(scalar_index) + " (length value: "+str(len(self.value))+")") #print(" - sample: "+str(self.value)) if (self.ramp_type == "alpha"): self.value[0].set_value(value) else: self.value[scalar_index].set_value(value) if self.clamp_values: #print(" - ramp: set scalar index + clamp: "+ str(scalar_index)) if (self.ramp_type == "alpha"): self.value[0].set_value(max(self.min_value, value)) else: self.value[scalar_index].set_value(max(self.min_value, value)) else: #print(" - ramp: set scalar index, no clamp: "+ str(scalar_index)) self.value[scalar_index].set_value(value) else: #print(" - ramp: save value, no scalar: "+ str(scalar_index)) # update widgets if self.clamp_values: for i in range(3): self.value[i].set_value(max(self.min_value, value[i])) else: for i in range(3): self.value[i].set_value(value[i]) # get RGBA value for a given parameter position def lookup(self, ct): # get parameters num_key = len(self.key_positions) # check default cases if (num_key == 1): return self.key_values[0] elif (num_key == 0): return [0.0, 0.0, 0.0, 0.0] # init parameters cur_id = 0 # iterate to current parameter position for i, cur_pos in enumerate(self.key_positions): if ct > cur_pos: cur_id = i + 1 else: break cur_id = min(cur_id, num_key - 1) # get values and parameters cur_val = self.key_values[cur_id] prev_val = self.key_values[max(cur_id-1,0)] cur_t = self.key_positions[cur_id] prev_t = self.key_positions[max(cur_id-1,0)] # check parameter positions cur_it = 0.0 if (cur_t != prev_t): cur_it = min(max((ct - prev_t) / (cur_t - prev_t), 0.0), 1.0) if isinstance(self.key_values[0], float): # interpolate single instance #print(" - lookup interp (ct="+str(ct)+"): "+str(cur_it)+" ("+str(prev_t)+","+str(cur_t)+") with values: prev: "+str(prev_val)+" cur:"+str(cur_val)) return (1.0 - cur_it) * prev_val + cur_it * cur_val elif len(self.key_values[0]) == 4: # interpolate rgba values itr = (1.0 - cur_it) * prev_val[0] + cur_it * cur_val[0] itg = (1.0 - cur_it) * prev_val[1] + cur_it * cur_val[1] itb = (1.0 - cur_it) * prev_val[2] + cur_it * cur_val[2] ita = (1.0 - cur_it) * prev_val[3] + cur_it * cur_val[3] rgba_result = [itr, itg, itb, ita] #print(" * lookup RGBA value: "+str(rgba_result)) return rgba_result def add_key(self, position): value = 0 # check if prim attributes are valid if self.key_positions_attr.IsValid() and self.key_values_attr.IsValid(): # lookup parameter position (interpolates RGBA value) value = self.lookup(position) # print(" - RampModel.add_key: adding value "+str(value)+" at "+str(position)+" to ramp "+str(self.ramp_type)) self.key_positions = list(self.key_positions_attr.Get()) self.key_values = list(self.key_values_attr.Get()) self.key_positions.append(position) self.key_values.append(value) self.update_num_keys() new_index = self.order_keys(self.num_keys - 1, position) self.key_values_attr.Set(self.key_values) return new_index def remove_selected_key(self): index = self.selected.as_int self.key_positions = list(self.key_positions_attr.Get()) if len(self.key_positions) > 1: self.key_values = list(self.key_values_attr.Get()) self.key_positions.pop(index) self.key_values.pop(index) self.update_num_keys() self.key_values_attr.Set(self.key_values) return index - 1 else: return -1 def select_index(self, index): #print(f"select_index {index}") if index < 0: return self.selected.set_value(index) def update_widgets(self, is_scalar=False, scalar_index=-1): #print("update widgets") index = self.selected.as_int if index < 0: return if len(self.key_positions) <= 0 or len(self.key_values) <= 0: return if self.position: self.position.set_value(self.key_positions[index]) if self.value: if is_scalar: if scalar_index < 0: #print(" * ramp:update_widget: value length: "+str(len(self.value)) +" SCALAR_INDEX: "+str(RampModel.SCALAR_INDEX)) self.value[RampModel.SCALAR_INDEX].set_value(self.key_values[index][3]) else: num_value = len(self.value) #print("RampModel.update_widget: value length: "+str(num_value) +" index: "+str(scalar_index)) #print(" - key value length: "+str(len(self.key_values)) +" index: "+str(index)+" sample: "+str(self.key_values[0])) if (isinstance(self.key_values[0], list)): self.value[min(scalar_index, num_value-1)].set_value(self.key_values[index][scalar_index]) #else: print(" ! RampModel.update_widget: Warning: input is no array type.") else: for i in range(3): self.value[i].set_value(self.key_values[index][i]) # private def initialize_if_empty_ramp(self): if self.key_positions_attr and len(self.key_positions_attr.Get()) == 0 or \ self.key_values_attr and len(self.key_values_attr.Get()) == 0: self.key_positions_attr.Set(self.default_key_positions) self.key_values_attr.Set(self.default_key_values) def order_keys(self, index, position): self.key_positions.sort() new_index = self.key_positions.index(position, 0, self.num_keys) if new_index != index: value = self.key_values.pop(index) self.key_values.insert(new_index, value) return new_index def update_num_keys(self): num_positions = len(self.key_positions) num_keys = len(self.key_values) self.num_keys = min(num_positions, num_keys) #print(f"num keys: {self.num_keys}") init_key_positions = None init_key_values = None def store_undo_data(self): #print("store undo data") self.init_key_positions = self.key_positions.copy() self.init_key_values = self.key_values.copy() def append_to_undo_stack(self): #print("append to undo stack") if self.init_key_positions != self.key_positions or \ self.init_key_values != self.key_values: return RampValues(prim_path=self.prim_path, pos_attr_name=self.positions_attr_name, val_attr_name=self.values_attr_name, old_positions=self.init_key_positions, old_values=self.init_key_values, new_positions=self.key_positions, new_values=self.key_values) return None class RampWidget: key_handle_scalar_style = {"background_color": 0xFF909090, "border_color": 0xFF000000, "border_width": 1} key_handle_scalar_over_range_style = {"background_color": 0xFFDFDFDF, "border_color": 0xFF000000, "border_width": 1} key_handle_scalar_selected_style = {"background_color": 0xFF909090, "border_color": 0xFFFFFFFF, "border_width": 1} key_handle_scalar_over_range_selected_style = {"background_color": 0xFFDFDFDF, "border_color": 0xFFFFFFFF, "border_width": 1} key_handle_outline_style = {"background_color": 0x00000000, "border_color": 0xFF000000, "border_width": 1} key_handle_selected_style = {"border_color": 0xFFFFFFFF, "border_width": 2} key_handle_style = {"border_color": 0xFF000000, "border_width": 1} # attr_names - a list with 2 strings specifiying attribute names (positions, values) # default_keys - a list with 2 elements: # key positions - a list of floats # key values - a list of tuples def __init__(self, parent_widget, model, model_add, model_remove, is_scalar=False, width=400, height=20, scalar_index=-1, name=""): self.parent_widget = parent_widget self.model = model self.model_add = model_add self.model_remove = model_remove self.is_scalar = is_scalar self.width = width self.height = height self.scalar_index = scalar_index self.name = name self.image = None self.key_handle_size = 10 self.key_handle_offset_x = -0.5 * self.key_handle_size self.placers_to_indices = {} self.indices_to_placers = {} self.handles = {} self.new_placer = None self.new_placer_offset_x = None self.new_placer_offset_y = None self.sub_position_changed = None self.sub_value_changed = None self.initial_key_index = -1 self.key_index = -1 self.width_ratio = 1 self.height_ratio = 1 self.async_task_update_keys = None self.async_task_add_new_key = None # AK: update flag #self.do_ramp_update = False with ui.ZStack(): vstack = ui.VStack(height=self.height) with vstack: self.byte_image_provider = ui.ByteImageProvider() self.image = ui.ImageWithProvider(self.byte_image_provider, fill_policy=ui.IwpFillPolicy.IWP_STRETCH, mouse_pressed_fn=functools.partial(self.on_mouse_button_pressed_2, vstack), mouse_moved_fn=functools.partial(self.on_mouse_moved_2, vstack), mouse_released_fn=self.on_mouse_button_released_2, style={"border_color": 0xFF000000, "border_width": 1}) self.image.set_computed_content_size_changed_fn(self.update_ui_elements) self.zstack_keys = ui.ZStack(height=self.key_handle_size * 2) if len(self.indices_to_placers): placer = self.indices_to_placers[0] self.on_mouse_button_pressed(placer) self.update() # public # call this when the ramp has to sync with the usd stage def update(self, dt=None): #print("update") if not self.image: return self.model.update() self.update_ui_elements() def on_shutdown(self): self.sub_position_changed = None self.sub_value_changed = None self.image = None # private def basic_clamp(self, num): return max(min(num, 1.0), 0.0) def update_ui_elements(self): #print("update ui elements") self.width_ratio = self.image.computed_width / self.width self.height_ratio = self.image.computed_height / self.height if self.is_scalar: self.model.update_limits(self.scalar_index) selected_key_index = self.model.selected.as_int if selected_key_index >= 0: if self.key_index >= 0: index = self.key_index else: index = self.initial_key_index if index < 0: index = selected_key_index self.update_ramp() self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys()) def set_key_position(self): #print("set key positions") selected_key_index = self.model.selected.as_int if selected_key_index >= 0: if self.key_index >= 0: index = self.key_index else: index = self.initial_key_index if index < 0: index = selected_key_index self.update_ramp() self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys()) def set_key_value(self): #print("set key values") selected_key_index = self.model.selected.as_int if selected_key_index >= 0: if self.key_index >= 0: index = self.key_index else: index = self.initial_key_index if index < 0: index = selected_key_index self.update_ramp() self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys()) async def async_update_keys(self): await ok.app.get_app().next_update_async() self.update_keys() def on_mouse_button_double_clicked(self, *_): #print("delete key") selected_key_index = self.model.selected.as_int if selected_key_index >= 0: self.model_remove.set_value(-1) self.model_remove.set_value(selected_key_index) self.initial_key_index = -1 def on_mouse_button_pressed_2(self, *arg): #print("mouse button pressed - add key") self.RELEASED = True # add key on the next Kit tick if self.async_task_add_new_key: self.async_task_add_new_key.cancel() self.async_task_add_new_key = asyncio.ensure_future(self.async_add_new_key_on_mouse_button_press(arg)) def on_mouse_moved_2(self, *arg): #print("add key, moved") vstack = arg[0] # omni.ui bug prevents us from moving the placer right # upon its creation, so lets calculate its position x/y # that will be used in on_mouse_moved cursor_position_x = arg[1] self.new_placer_offset_x = cursor_position_x - vstack.screen_position_x if self.is_scalar: cursor_position_y = arg[2] self.new_placer_offset_y = cursor_position_y - vstack.screen_position_y self.on_mouse_moved(self.new_placer) def update_usd_data(self): # update usd values to send to index cmap_prim = self.model.prim cmap_attr = cmap_prim.GetAttribute("colormapValues") cmap_data = cmap_attr.Get() num_cmap = len(cmap_data) #print(" - properties: colormapValues: "+str(num_cmap)+" ramp type: "+str(self.model.ramp_type)) key_vals = self.model.key_values num_keys = len(key_vals) #print(" - key values: "+str(num_keys)+" sample: "+str(key_vals[0])) # check if current model has RGBA or alpha data if (isinstance(key_vals[0], float)): print("RampWidget: updating usd float type values (alpha channel only)") # update alpha channel only new_data = np.ones((num_cmap, 4)) for x in range(num_cmap): ct = x / num_cmap alpha_it = self.model.lookup(ct) #print(" - interp alpha "+str(ct)+": "+str(alpha_it)) new_data[x] = cmap_data[x] new_data[x][3] = max(min(alpha_it,1.0),0.0) cmap_attr.Set(new_data) else: num_values = len(key_vals[0]) print("RampWidget: updating usd data with "+str(num_values)+" channel RGBA type") # update RGBA color data in usd new_data = np.ones((num_cmap, 4)) for x in range(num_cmap): ct = x / num_cmap col_it = self.model.lookup(ct) new_data[x] = col_it cmap_attr.Set(new_data) def on_mouse_button_released_2(self, *_): # write data from control points to usd RGBA field # self.update_usd_data() # now handled directly by omni.indexusd # if user only clicked on the ramp the self.key_index # won't be updated by ::on_mouse_move, use the # self.initial_key_index instead if self.key_index < 0: self.key_index = self.initial_key_index if self.key_index < 0: self.key_index = self.model.selected.as_int if self.key_index < 0: self.key_index = 0 self.new_placer_offset_x = None self.new_placer_offset_y = None # PRESSED = False def on_mouse_button_pressed(self, placer, *_): #print("mouse button pressed") if self.RELEASED: self.initial_placer_position = placer.offset_x.value if self.is_scalar: self.initial_placer_value = placer.offset_y.value index = self.placers_to_indices[placer] self.model.select_index(index) self.RELEASED = False def select_key(self, selected_key_index): #print(f"select key {selected_key_index} in model "+self.model.ramp_type) if selected_key_index < 0: return # establish initial index and buffer index self.initial_key_index = selected_key_index self.key_index = -1 if len(self.handles) == 0: return if self.model.num_keys != len(self.handles): return # highlite selected key for ii in range(self.model.num_keys): if self.initial_key_index == ii: if self.is_scalar: key_style = self.key_handle_scalar_selected_style if self.model.max_range and self.model.max_range.as_bool: if self.scalar_index < 0: scalar_value = self.model.key_values[ii] else: scalar_value = self.model.key_values[ii][self.scalar_index] if scalar_value > self.model.max_display_value: key_style = self.key_handle_scalar_over_range_selected_style self.handles[ii].set_style(key_style) else: self.handles[ii][2].set_style(self.key_handle_selected_style) self.handles[ii][3].set_style(self.key_handle_selected_style) else: if self.is_scalar: key_style = self.key_handle_scalar_style if self.model.max_range and self.model.max_range.as_bool: if self.scalar_index < 0: scalar_value = self.model.key_values[ii] else: scalar_value = self.model.key_values[ii][self.scalar_index] if scalar_value > self.model.max_display_value: key_style = self.key_handle_scalar_over_range_style self.handles[ii].set_style(key_style) else: self.handles[ii][2].set_style(self.key_handle_style) self.handles[ii][3].set_style(self.key_handle_style) async def async_add_new_key_on_mouse_button_press(self, *arg): await ok.app.get_app().next_update_async() if self.RELEASED: #print("async add key") vstack = arg[0][0] cursor_position_x = arg[0][1] position = (cursor_position_x - vstack.screen_position_x) / self.image.computed_width self.model_add.set_value(-1) self.model_add.set_value(position) self.RELEASED = False async def async_update_keys_on_mouse_button_release(self, index): await ok.app.get_app().next_update_async() #print("asymc mouse button released") self.update_keys() self.RELEASED = True RELEASED = False def on_mouse_button_released(self, *_): #print("mouse button released") self.RELEASED = True # remap ui widgets if user reordered keys if self.initial_key_index >= 0 and self.key_index >= 0 and self.initial_key_index != self.key_index: placer1 = self.indices_to_placers[self.initial_key_index] placer2 = self.indices_to_placers[self.key_index] self.placers_to_indices[placer1] = self.key_index self.placers_to_indices[placer2] = self.initial_key_index self.indices_to_placers[self.initial_key_index] = placer2 self.indices_to_placers[self.key_index] = placer1 handles1 = self.handles[self.initial_key_index] handles2 = self.handles[self.key_index] self.handles[self.initial_key_index] = handles2 self.handles[self.key_index] = handles1 if self.is_scalar: self.model.update_limits(self.scalar_index) # update keys on the next tick if self.async_task_update_keys: self.async_task_update_keys.cancel() if self.key_index >= 0: index = self.key_index else: index = self.initial_key_index if index < 0: index = self.model.selected.as_int self.async_task_update_keys = asyncio.ensure_future(self.async_update_keys_on_mouse_button_release(index)) # restore initial conditions self.initial_key_index = -1 self.key_index = -1 self.new_placer = None self.RELEASED = False def on_mouse_moved(self, *arg): #print("move key") placer = arg[0] y = 0 if self.new_placer_offset_x is None: x = placer.offset_x.value else: x = self.new_placer_offset_x if self.is_scalar: # Workaround to omni.ui bug where new placers # cannot be moved right after their creation. # If moving existing key use it's placer position, # otherwise use the values provided by on_mouse_moved_2. if self.new_placer_offset_y is None: y = placer.offset_y.value else: y = self.new_placer_offset_y key_scalar_value = (self.height - y) * (self.model.range / self.height) if key_scalar_value < self.model.min_value: key_scalar_value = self.model.min_value # elif key_scalar_value > self.model.max_value: # key_scalar_value = self.model.max_value self.model.save_value(key_scalar_value, self.is_scalar, self.scalar_index) width = self.width * self.width_ratio key_position = round(max(0, min(1, x / width)), 4) if self.key_index < 0: self.key_index = self.initial_key_index self.model.save_position(self.key_index, key_position) def update_ramp(self): #print("update ramp") self.model.initialize_if_empty_ramp() num_pixels_x = self.width num_pixels_y = self.height if self.is_scalar else 1 # initialize pixel values pixels = [1] * num_pixels_x * num_pixels_y * 4 if self.model.key_positions_attr.IsValid() and self.model.key_values_attr.IsValid(): if self.is_scalar: if self.scalar_index == RampModel.ALPHA_INDEX: # pixels = self.ramp.get_alpha_array_as_rgba8(self.width, self.height, # self.model.min_value, self.model.max_value, # self.model.key_positions_attr.GetPath().pathString, # self.model.key_values_attr.GetPath().pathString) #self.model.key_positions #print("creating alpha pixel map") # create pixel pattern if (True): # AK: create pixel pattern for x in range(num_pixels_x): # interpolate alpha value xt = float(x / num_pixels_x) cur_rgba = self.model.lookup(xt) cur_alpha = cur_rgba[RampModel.ALPHA_INDEX] max_y = (1.0 - cur_alpha) * num_pixels_y # fill column for y in range(num_pixels_y): index = y * num_pixels_x * 4 + x * 4 if (max_y < y): pixels[index + 0] = 0.5 pixels[index + 1] = 0.5 pixels[index + 2] = 0.5 pixels[index + 3] = cur_alpha else: pixels[index + 0] = 0.0 pixels[index + 1] = 0.0 pixels[index + 2] = 0.0 pixels[index + 3] = 0.0 elif self.scalar_index < 0: # pixels = self.ramp.get_float_array_as_rgba8(self.width, self.height, # self.model.min_value, self.model.range - self.model.min_value, # self.model.key_positions_attr.GetPath().pathString, # self.model.key_values_attr.GetPath().pathString) #print("creating float pixel map (sample: "+str(self.model.key_values[0])+")") if (True): # AK: create pixel pattern for x in range(num_pixels_x): # interpolate alpha value xt = float(x / num_pixels_x) cur_rgba = self.model.lookup(xt) cur_alpha = cur_rgba[RampModel.ALPHA_INDEX] max_y = (1.0 - cur_alpha) * num_pixels_y # fill column for y in range(num_pixels_y): index = y * num_pixels_x * 4 + x * 4 if (max_y < y): pixels[index + 0] = 0.5 pixels[index + 1] = 0.5 pixels[index + 2] = 0.5 pixels[index + 3] = cur_alpha else: pixels[index + 0] = 0.0 pixels[index + 1] = 0.0 pixels[index + 2] = 0.0 pixels[index + 3] = 0.0 # set flag #self.do_ramp_update = False else: positions = [x / (num_pixels_x - 1) for x in range(num_pixels_x)] #print("creating generic pixel map from values (#positions: "+str(len(positions))+", sample: "+str(positions[1])+")") #print(" - num-x: "+str(num_pixels_x)+" num-y: "+str(num_pixels_y)) #print(" - length values: "+str(len(self.model.key_values))) #print(" - positions: "+str((self.model.key_positions))) #print(" - values: "+str((self.model.key_values))) num_values = len(self.model.key_values) num_positions = len(self.model.key_positions) #FIXME: find out why these are not always the same?!?? pidx = 0 # values = self.ramp.get_float4_array(positions, # self.model.key_positions_attr.GetPath().pathString, # self.model.key_values_attr.GetPath().pathString, "") if True: for x in range(num_pixels_x): xt = x / num_pixels_x key_pos = self.model.key_positions[pidx] key_pos_prev = self.model.key_positions[max(pidx-1,0)] if (key_pos != key_pos_prev): key_it = min(max((xt - key_pos_prev) / (key_pos - key_pos_prev),0.0),1.0) else: key_it = 0.0 key_value_next = self.model.key_values[pidx] key_value_prev = self.model.key_values[max(pidx-1,0)] itr = (1.0 - key_it) * key_value_prev[0] + (key_it) * key_value_next[0] itg = (1.0 - key_it) * key_value_prev[1] + (key_it) * key_value_next[1] itb = (1.0 - key_it) * key_value_prev[2] + (key_it) * key_value_next[2] ita = (1.0 - key_it) * key_value_prev[3] + (key_it) * key_value_next[3] #print(" ramp: it: "+str(key_it)) if key_pos < xt and pidx + 1 < min(num_values, num_positions): pidx += 1 for y in range(num_pixels_y): # pixels[index + 0] = values[x][0] # pixels[index + 1] = values[x][1] # pixels[index + 2] = values[x][2] # pixels[index + 3] = values[x][3] index = y * num_pixels_x * 4 + x * 4 pixels[index + 0] = itr pixels[index + 1] = itg pixels[index + 2] = itb pixels[index + 3] = 1.0 self.byte_image_provider.set_bytes_data(pixels, [num_pixels_x, num_pixels_y]) def update_keys(self): #print("update keys") # currently omni.ui API cannot delete widgets - hide them instead for placer in self.indices_to_placers.values(): placer.visible = False for handle in self.handles.values(): if self.is_scalar: handle.visible = False else: handle[0].visible = False handle[1].visible = False handle[2].visible = False handle[3].visible = False self.placers_to_indices = {} self.indices_to_placers = {} self.handles = {} self.model.update_num_keys() with self.zstack_keys: for i in range(self.model.num_keys): x = self.model.key_positions[i] * self.width value = None if self.is_scalar: if self.model.range: if self.scalar_index < 0: scalar_value = self.model.key_values[i] else: scalar_value = self.model.key_values[i][self.scalar_index] if self.model.max_range and self.model.max_range.as_bool: # the key will be clamped to max display value scalar_value = min(scalar_value, self.model.max_display_value) y = self.height - abs((scalar_value - self.model.min_value) / self.model.range * self.height) else: y = self.height else: y = 0 value = self.model.key_values[i] self.create_key_handle(i, x, y, value) self.select_key(self.model.selected.as_int) def create_key_handle(self, index, x, y, value): offset = self.key_handle_offset_x with ui.Placer(offset_x=offset, offset_y=offset): placer = ui.Placer(width=self.key_handle_size, height=self.key_handle_size, offset_x=x * self.width_ratio, offset_y=y * self.height_ratio, draggable=True, drag_axis=ui.Axis.XY if self.is_scalar else ui.Axis.X, stable_size=True) placer.set_offset_x_changed_fn(functools.partial(self.on_mouse_moved, placer)) if self.is_scalar: placer.set_offset_y_changed_fn(functools.partial(self.on_mouse_moved, placer)) with placer: with ui.ZStack(mouse_pressed_fn=functools.partial(self.on_mouse_button_pressed, placer), mouse_released_fn=self.on_mouse_button_released): if self.is_scalar: circle = ui.Circle(radius=self.key_handle_size * 0.5, mouse_double_clicked_fn=self.on_mouse_button_double_clicked, style=self.key_handle_scalar_style) self.handles[index] = circle else: with ui.Placer(): border_triangle = ui.Triangle( width=self.key_handle_size, height=self.key_handle_size * 0.5, alignment=ui.Alignment.CENTER_TOP, style=self.key_handle_outline_style ) with ui.Placer(offset_y=self.key_handle_size * 0.5 + 0.5): border_rectangle = ui.Rectangle(width=self.key_handle_size, height=self.key_handle_size - 2, style=self.key_handle_outline_style) r = int(self.basic_clamp(value[0]) * 255) g = int(self.basic_clamp(value[1]) * 255) << 8 b = int(self.basic_clamp(value[2]) * 255) << 16 a = 255 << 24 with ui.Placer(offset_x=1, offset_y=1): triangle = ui.Triangle( width=self.key_handle_size - 2, height=self.key_handle_size * 0.5 - 1, mouse_double_clicked_fn=self.on_mouse_button_double_clicked, alignment=ui.Alignment.CENTER_TOP, style={"background_color": (r + g + b + a)} ) with ui.Placer(offset_x=1, offset_y=self.key_handle_size * 0.5 - 0.5): rectangle = ui.Rectangle( width=self.key_handle_size - 1.75, height=self.key_handle_size - 2, mouse_double_clicked_fn=self.on_mouse_button_double_clicked, style={"background_color": (r + g + b + a)} ) self.handles[index] = (triangle, rectangle, border_triangle, border_rectangle) self.placers_to_indices[placer] = index self.indices_to_placers[index] = placer return placer
45,780
Python
38.398451
170
0.514111
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/shader_properties_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ui as ui import omni.usd as ou from pxr import Sdf, Usd, UsdShade from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder from omni.kit.window.property.templates import HORIZONTAL_SPACING from carb.input import KeyboardInput as Key from ..presets import ShaderPresets from .index_properties_base_widget import IndexPropertiesBaseWidget class ShaderPropertiesWidget(IndexPropertiesBaseWidget): def __init__(self): super().__init__("IndeX Shader", "Shader") self.xac_source_asset_model = None self.xac_source_code_field = None self.id_combo_box = None def switch_implementation_source(self, value): key = "info:implementationSource" # self.request_rebuild() # update UI to change mode self.store_value(key, value, "") def reload_shader(self): prim = self.get_prim() key = "info:xac:sourceAsset" if prim.GetAttribute("info:implementationSource").Get() == "sourceAsset" and prim.GetAttribute(key).Get(): asset = prim.GetAttribute(key).Get() prim.GetAttribute(key).Clear() # force an update custom = False prim.CreateAttribute(key, Sdf.ValueTypeNames.Asset, custom, Sdf.VariabilityUniform).Set(asset) def convert_to_source_code(self): prim = self.get_prim() shader = UsdShade.Shader(prim) if not shader: return XAC_SOURCE_TYPE = "xac" source_asset = shader.GetSourceAsset(XAC_SOURCE_TYPE) if not source_asset: return xac_path = source_asset.resolvedPath if not xac_path: carb.log_error("Error: Could not resolve asset path '" + str(source_asset) + "' for prim '" + prim.GetPath().pathString + "'") return try: with open(xac_path, 'r') as file: contents = file.read() except IOError: carb.log_error("Error: Could not load file '" + str(xac_path) + "' for prim '" + prim.GetPath().pathString + "'") return self.store_value("info:xac:sourceCode", contents) self.switch_implementation_source("sourceCode") def update_shader(self): self.store_value("info:xac:sourceCode", self.xac_source_code_field.model.as_string) def load_shader_preset(self, prim, preset_name): if prim and preset_name: UsdShade.Shader(prim).SetSourceCode(ShaderPresets.get(preset_name), "xac") def on_key_pressed(self, key: int, key_mod: int, key_down: bool): key = Key(key) # Convert to enumerated type if key == Key.F9: self.update_shader() def _on_prop_changed(self, path): e = path.elementString if e == ".info:id" and self.id_combo_box: value = self.get_prim().GetAttribute("info:id").Get() or "" model = self.id_combo_box.model if value in model.get_item_list(): model.set_current_index(model.get_item_list().index(value)) else: model.set_current_index(0) if e == ".info:implementationSource": self.request_rebuild() elif e == ".info:xac:sourceAsset" and self.xac_source_asset_model: asset = self.get_prim().GetAttribute("info:xac:sourceAsset").Get() self.xac_source_asset_model.set_value(asset.path if asset else "") elif e == ".info:xac:sourceCode" and self.xac_source_code_field: source_code = self.get_prim().GetAttribute("info:xac:sourceCode").Get() or "" self.xac_source_code_field.model.set_value(source_code) def build_properties(self, stage, prim, prim_path): with ui.VStack(spacing=5): # # implementation source: asset, source code or id # with ui.HStack(): # self.info_id_implementation_source_model = UsdPropertiesWidgetBuilder._tftoken_builder( # stage, # "info:implementationSource", # Sdf.ValueTypeNames.Token, # { 'allowedTokens': ['id', 'sourceAsset', 'sourceCode'], 'default': 'id', 'typeName': 'token' }, # metadata # [ prim_path ] # ) key = "info:implementationSource" with ui.HStack(): self.build_label("Implementation Source") value = prim.GetAttribute(key).Get() or "" self.implementation_source_combo_box = ui.ComboBox(self.create_combo_list_model(value, ['id', 'sourceAsset', 'sourceCode']), name=key) self.implementation_source_combo_box.model.add_item_changed_fn(lambda m, i: self.switch_implementation_source(m.get_current_string())) implementation_source = prim.GetAttribute("info:implementationSource").Get() or "id" # # source asset # if implementation_source == 'sourceAsset': with ui.HStack(): models = UsdPropertiesWidgetBuilder._sdf_asset_path_builder( stage, "info:xac:sourceAsset", Sdf.ValueTypeNames.Asset, { Sdf.PropertySpec.DisplayNameKey: 'Source Asset', 'default': '', 'typeName': 'asset' }, [ prim_path ] ) if isinstance(models, list): self.xac_source_asset_model = models[0] else: self.xac_source_asset_model = models with ui.HStack(): ui.Button("Reload Asset", clicked_fn=self.reload_shader, name="reloadAsset") with ui.HStack(): ui.Button("Integrate Asset Contents", clicked_fn=self.convert_to_source_code, name="integrateAssetContents", tooltip="Switches 'implementationSource' to 'sourceCode'") # # source code # elif implementation_source == 'sourceCode': key = "info:xac:sourceCode" with ui.HStack(): self.build_label("Source Code") with ui.HStack(): source_code = prim.GetAttribute(key).Get() or "" self.xac_source_code_field = ui.StringField(name=key, multiline=True, tabInputAllowed=True, height=200) self.xac_source_code_field.model.set_value(source_code) self.xac_source_code_field.set_key_pressed_fn(self.on_key_pressed) # Don't automatically update, as that would trigger recompile on each change #self.xac_source_code_field.model.add_value_changed_fn(self.set_script) with ui.HStack(): ui.Button("Save and Compile [F9]", clicked_fn=self.update_shader, name="saveAndCompile") # # id # else: key = "info:id" with ui.HStack(): self.build_label("Implementation ID") id_value = prim.GetAttribute(key).Get() or "" self.id_combo_box = ui.ComboBox(self.create_combo_list_model(id_value, ['', 'nvindex:phong_gl']), name=key) self.id_combo_box.model.add_item_changed_fn(lambda m, i: self.store_value(key, m.get_current_string(), "")) with ui.HStack(): self.build_label("Load Shader Preset") preset_combo_box = ui.ComboBox(self.create_combo_list_model('', [''] + ShaderPresets.get_labels()), name='loadShaderPreset') preset_combo_box.model.add_item_changed_fn(lambda model, i: self.load_shader_preset(prim, model.get_current_string()))
8,320
Python
43.497326
154
0.579808
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/__init__.py
from .common_settings import IndeXCommonSettingStack from .cluster_settings import IndeXClusterSettingStack
108
Python
35.333322
54
0.888889
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/index_properties_base_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import carb.settings from omni.kit.async_engine import run_coroutine import omni.kit.window.property as p import omni.usd as ou import omni.ui as ui from pxr import Usd, Sdf, Tf from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget from omni.kit.window.property.templates import LABEL_WIDTH, LABEL_HEIGHT class ComboListItem(ui.AbstractItem): def __init__(self, item): super().__init__() self.model = ui.SimpleStringModel(item) class ComboListModel(ui.AbstractItemModel): def __init__(self, item_list, default_index): super().__init__() self._default_index = default_index self._current_index = ui.SimpleIntModel(default_index) self._current_index.add_value_changed_fn(lambda a: self._item_changed(None)) self._item_list = item_list self._items = [] if item_list: for item in item_list: self._items.append(ComboListItem(item)) def get_item_children(self, item): return self._items def get_item_list(self): return self._item_list def get_item_value_model(self, item=None, column_id=-1): if item is None: return self._current_index return item.model def get_current_index(self): return self._current_index.get_value_as_int() def set_current_index(self, index): self._current_index.set_value(index) def get_current_string(self): return self._items[self._current_index.get_value_as_int()].model.get_value_as_string() def is_default(self): return self.get_current_index() == self._default_index class IndexPropertiesBaseWidget(UsdPropertiesWidget): USD_RENDERSETTINGS = 'nvindex.renderSettings' def __init__(self, title, element_types): super().__init__(title, collapsed=False, multi_edit=False) if not isinstance(element_types, list): element_types = [element_types] self.element_types = element_types w = p.get_window() w.register_widget("prim", self.element_types[0], self) settings = carb.settings.get_settings() self.show_advanced_settings = settings.get("/nvindex/showAdvancedSettings") def clean(self): self.reset() super().clean() def reset(self): super().reset() def on_shutdown(self): w = p.get_window() w.unregister_widget("prim", self.element_types[0]) def on_new_payload(self, payload): if not super().on_new_payload(payload): return False if len(self._payload) == 0: return False for path in self._payload: prim = self._get_prim(path) if prim is None: return False if prim.GetTypeName() in self.element_types: return True return False def get_prim(self): return ou.get_context().get_stage().GetPrimAtPath(self._payload[-1]) # def get_script(self): # stage = ou.get_context().get_stage() # return stage.GetPrimAtPath(self._payload[-1]).GetAttribute("inputs:script").Get() or "" def set_render_setting(self, key, value, default): prim = self.get_prim() #render_settings = prim.GetCustomDataByKey(self.USD_RENDERSETTINGS) path = self.USD_RENDERSETTINGS + ":" + key if value == default: prim.ClearCustomDataByKey(path ) # if render_settings and key in render_settings: # del render_settings[key] else: prim.SetCustomDataByKey(path, value) # if render_settings == None: # render_settings = {} # render_settings[key] = value # if render_settings: # prim.SetCustomDataByKey(self.USD_RENDERSETTINGS, render_settings) # else: # prim.ClearCustomDataByKey(self.USD_RENDERSETTINGS) def set_volume_type(self, combo_model, item): prim = self.get_prim() volume_type = combo_model.get_current_string() if volume_type == "default": prim.GetAttribute("nvindex:type").Clear() else: prim.CreateAttribute("nvindex:type", Sdf.ValueTypeNames.Token, True, Sdf.VariabilityUniform).Set(volume_type) def _on_domain_changed(self, *args): pass # self.target_attrib_name_model._set_dirty() def create_combo_list_model(self, current_value, items_list): index = 0 if current_value in items_list: index = items_list.index(current_value) return ComboListModel(items_list, index) def build_label(self, caption, full_width=False): if full_width: ui.Label(caption, name="label", word_wrap=True, height=LABEL_HEIGHT) else: ui.Label(caption, name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT) def store_value(self, key, value, default = '', valueType = Sdf.ValueTypeNames.String, custom = False): prim = self.get_prim() if value == default: prim.GetAttribute(key).Clear() else: prim.CreateAttribute(key, valueType, custom, Sdf.VariabilityUniform).Set(value) def get_render_setting_value(self, key, default, render_settings): if render_settings and key in render_settings: return render_settings[key] else: return default def build_render_setting_combo_box(self, caption, key, items_list, render_settings): with ui.HStack(): self.build_label(caption) current_value = self.get_render_setting_value(key, "default", render_settings) index = 0 if current_value in items_list: index = items_list.index(current_value) widget = ui.ComboBox(self.create_combo_list_model(current_value, items_list), name=key) widget.model.add_item_changed_fn(lambda m, i: self.set_render_setting(key, m.get_current_string(), "default")) def build_render_setting_float(self, caption, key, default, render_settings): with ui.HStack(): self.build_label(caption) current_value = self.get_render_setting_value(key, default, render_settings) widget = ui.FloatField(name=key) widget.model.set_value(current_value) widget.model.add_value_changed_fn(lambda m: self.set_render_setting(key, m.get_value_as_float(), default)) def build_render_setting_int(self, caption, key, default, render_settings): with ui.HStack(): self.build_label(caption) current_value = self.get_render_setting_value(key, default, render_settings) widget = ui.IntField(name=key) widget.model.set_value(current_value) widget.model.add_value_changed_fn(lambda m: self.set_render_setting(key, m.get_value_as_int(), default)) def build_render_setting_bool(self, caption, key, default, render_settings): with ui.HStack(): self.build_label(caption) current_value = self.get_render_setting_value(key, default, render_settings) widget = ui.CheckBox(name=key) widget.model.set_value(current_value) widget.model.add_value_changed_fn(lambda m: self.set_render_setting(key, m.get_value_as_bool(), default)) # Copied from UsdPropertiesWidget with minor changes (force rebuild on # non-property change, to handle modified custom data) def _on_usd_changed(self, notice, stage): if stage != self._payload.get_stage(): return if not self._collapsable_frame: return if len(self._payload) == 0: return if self._pending_rebuild_task is not None: return dirty_paths = set() for path in notice.GetResyncedPaths(): if path in self._payload: self.request_rebuild() return elif path.GetPrimPath() in self._payload: prop = stage.GetPropertyAtPath(path) if (not prop.IsValid()) != (self._models.get(path) is None): self.request_rebuild() return else: dirty_paths.add(path) for path in notice.GetChangedInfoOnlyPaths(): dirty_paths.add(path) if path in self._payload and not path.IsPropertyPath(): # Handle changed custom data self.request_rebuild() return self._pending_dirty_paths.update(dirty_paths) if self._pending_dirty_task_or_future is None: self._pending_dirty_task_or_future = run_coroutine(self._delayed_dirty_handler()) def build_items(self): self.reset() if len(self._payload) == 0: return prim_path = self._payload[-1] last_prim = self._get_prim(prim_path) if not last_prim: return stage = last_prim.GetStage() if not stage: return self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage) self.build_properties(stage, last_prim, prim_path)
9,656
Python
34.766667
122
0.619615
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/colormap.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 as ok import omni.ui as ui import omni.usd as ou from .ramp import RampWidget, RampModel class ColorMap: def rebuild_ramp(self): self.parent_widget.rebuild() def __init__(self, parent_widget, prim, attr_names=["xPoints", "rgbaPoints"], width=400, height=20, height_scalar=50, label="", clamp_values=True): self.parent_widget = parent_widget self.label = label self.selected_model = ui.SimpleIntModel(-1) self.selected_model.add_value_changed_fn(self.select_key) self.rgba_model = RampModel("rgba", self.selected_model, prim, [attr_names[0], attr_names[1]], [[0], [(1, 1, 1, 1)]], True) #self.rgba_model = RampModel(self.selected_model, prim, [attr_names[0], attr_names[1]], [default_positions, default_values], clamp_values) self.alpha_model = RampModel("alpha", self.selected_model, prim, [attr_names[0], attr_names[1]], [[0], [(1, 1, 1, 1)]], True) #self.alpha_model = RampModel(self.selected_model, prim, [attr_names[0], attr_names[2]], [default_positions, default_scale], clamp_values) self.alpha_model.selected.add_value_changed_fn(self.select_key) self.add_key_model = ui.SimpleFloatModel(0) self.add_key_model.add_value_changed_fn(self.add_key) self.remove_key_model = ui.SimpleIntModel(0) self.remove_key_model.add_value_changed_fn(self.remove_key) self.margin = 2 self.max_display_intensity = 1 self.ramp_widget_rgb = None self.ramp_widget_alpha = None self.intensity_range = None self.alpha_range = None ok.undo.subscribe_on_change(self.undo_redo_on_change) usd_watcher = ou.get_watcher() self.usd_subscription = usd_watcher.subscribe_to_change_info_path( prim.GetPath(), self.on_usd_changed ) from omni.kit.window.property.templates import LABEL_WIDTH, HORIZONTAL_SPACING with self.parent_widget: with ui.HStack(spacing=HORIZONTAL_SPACING): if label != "": ui.Label(self.label, style={"alignment": ui.Alignment.RIGHT_TOP}, width=LABEL_WIDTH) ui.Spacer(width=HORIZONTAL_SPACING) with ui.VStack(height=0, spacing=12): with ui.HStack(spacing=HORIZONTAL_SPACING): ui.Label(" ", style={"alignment": ui.Alignment.LEFT}) with ui.HStack(): ui.Spacer(width=HORIZONTAL_SPACING) self.ramp_widget_alpha = RampWidget( parent_widget, self.alpha_model, self.add_key_model, self.remove_key_model, True, width, height_scalar, scalar_index=RampModel.ALPHA_INDEX, name="alpha") with ui.HStack(): ui.Spacer(width=HORIZONTAL_SPACING) self.ramp_widget_rgb = RampWidget( parent_widget, self.rgba_model, self.add_key_model, self.remove_key_model, False, width, height, name="rgb") with ui.HStack(style={"margin": self.margin}): # element to change parameter position ui.Label("position", alignment=ui.Alignment.RIGHT_CENTER) self.position_drag = ui.FloatDrag(width=50, min=0, max=1, name="colormapPointPosition") self.position_changed = self.position_drag.model.subscribe_value_changed_fn(self.set_key_position) self.rgba_model.position = self.position_drag.model self.alpha_model.position = self.position_drag.model # add label for alpha & color selector ui.Label("color", alignment=ui.Alignment.RIGHT_CENTER) # add color selector widget self.value_widget = ui.ColorWidget(0.0, 0.0, 0.0, width=50,name="colormapPointColor") self.sub_value_changed = self.value_widget.model.add_item_changed_fn(self.set_rgb) sub_models = self.value_widget.model.get_item_children() self.rgba_model.value.append(self.value_widget.model.get_item_value_model(sub_models[0])) self.rgba_model.value.append(self.value_widget.model.get_item_value_model(sub_models[1])) self.rgba_model.value.append(self.value_widget.model.get_item_value_model(sub_models[2])) # add opacity float box, sync value in both ramp models ui.Label("opacity", alignment=ui.Alignment.RIGHT_CENTER) self.alpha_drag = ui.FloatDrag(width=60, min=0, max=1, name="colormapPointOpacity") self.alpha_model.value.append(self.alpha_drag.model) self.rgba_model.value.append(self.alpha_drag.model) self.alpha_value_changed = self.alpha_model.value[RampModel.SCALAR_INDEX].subscribe_value_changed_fn(self.set_alpha) ui.Spacer(width=HORIZONTAL_SPACING) self.update_ui_elements() self.selected_model.set_value(0) # public def update_ui_elements(self, *_): # print("update_ui_elements") # update both ramp models new_index_rgba = self.rgba_model.update() new_index_intensity = self.alpha_model.update() # update values if new_index_rgba > 0 or new_index_intensity > 0: self.selected_model.set_value(max(new_index_rgba, new_index_intensity)) # update both ramp widgets self.ramp_widget_rgb.update_ui_elements() self.ramp_widget_alpha.update_ui_elements() def on_shutdown(self): ok.undo.unsubscribe_on_change(self.undo_redo_on_change) self.value_widget.model.remove_item_changed_fn(self.sub_value_changed) # clear widgets & models self.position_changed = None self.intensity_value_changed = None self.alpha_value_changed = None self.ramp_widget_rgb = None self.rgba_model = None self.usd_subscription = None def undo_redo_on_change(self, cmds): if "IndexSetRampValuesCommand" in cmds: self.update_ui_elements() self.update_widgets() # private def on_usd_changed(self, *_): self.update_ui_elements() self.update_widgets() def set_key_position(self, *_): # print("set_key_position") # update order of all value models first new_index = self.rgba_model.update_position() self.alpha_model.update_position() # then update positions self.rgba_model.save_and_select_position(new_index) if self.ramp_widget_rgb: self.ramp_widget_rgb.set_key_position() if self.ramp_widget_alpha: self.ramp_widget_alpha.set_key_position() def set_intensity(self, *_): self.alpha_model.update_value(True) if self.ramp_widget_alpha: self.ramp_widget_alpha.set_key_value() def set_alpha(self, *_): self.rgba_model.update_value(True, RampModel.ALPHA_INDEX) def set_rgb(self, *_): self.rgba_model.update_value() if self.ramp_widget_rgb: self.ramp_widget_rgb.set_key_value() def select_key(self, model): self.update_widgets() index = model.as_int if self.ramp_widget_rgb: self.ramp_widget_rgb.select_key(index) if self.ramp_widget_alpha: self.ramp_widget_alpha.select_key(index) def add_key(self, model): position = model.as_float if position < 0: return self.store_undo_data() # add value to all models first new_index = self.rgba_model.add_key(position) self.alpha_model.add_key(position) self.append_to_undo_stack() # then update positions self.rgba_model.save_and_select_position(new_index) self.update_ui_elements() def remove_key(self, model): if model.as_int < 0: return self.store_undo_data() # remove value from all models first new_index = self.rgba_model.remove_selected_key() self.alpha_model.remove_selected_key() # then update positions self.rgba_model.save_and_select_position(new_index) self.append_to_undo_stack() self.update_ui_elements() def update_widgets(self): self.value_widget.model.remove_item_changed_fn(self.sub_value_changed) # update all values self.rgba_model.update_widgets() self.rgba_model.update_widgets(True, RampModel.ALPHA_INDEX) self.alpha_model.update_widgets(True) self.sub_value_changed = self.value_widget.model.add_item_changed_fn(self.set_rgb) def store_undo_data(self): # print("store undo data") self.rgba_model.store_undo_data() self.alpha_model.store_undo_data() def append_to_undo_stack(self): # print("append to undo stack") rampValues_rgba = self.rgba_model.append_to_undo_stack() rampValues_intensity = self.alpha_model.append_to_undo_stack() if rampValues_rgba and rampValues_intensity: ok.commands.execute("IndexSetRampValuesCommand", ramps=[rampValues_rgba, rampValues_intensity])
10,369
Python
38.132075
146
0.582409
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/widgets/colormap_properties_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ui as ui import omni.usd as ou from pxr import Sdf from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder from ..presets import ColormapPresets from .index_properties_base_widget import IndexPropertiesBaseWidget from .colormap import ColorMap from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame class ColormapPropertiesWidget(IndexPropertiesBaseWidget): USD_RENDERSETTINGS = 'nvindex.renderSettings' def __init__(self): super().__init__("IndeX Colormap", "Colormap") self.colormap_source_combo_box = None def switch_colormap_source(self, value): key = "colormapSource" self.request_rebuild() # update UI to change mode self.store_value(key, value, "colormapValues") def load_colormap_preset(self, prim, preset_name, colormapSource): if prim and preset_name: if colormapSource == "rgbaPoints": (xPoints, rgbaPoints) = ColormapPresets.generate(preset_name, colormap_source=colormapSource) xPoints_attr = prim.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray) xPoints_attr.Set(xPoints) rgbaPoints_attr = prim.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array) rgbaPoints_attr.Set(rgbaPoints) else: colormap_data = ColormapPresets.generate(preset_name) colormap_attr = prim.CreateAttribute("colormapValues", Sdf.ValueTypeNames.Color4fArray) colormap_attr.Set(colormap_data) def build_properties(self, stage, prim, prim_path): with ui.VStack(spacing=5): stage = ou.get_context().get_stage() node_prim_path = self._payload[-1] #TODO: Make this explicit to handle missing attributes self.domain_model = UsdPropertiesWidgetBuilder._vec2_per_channel_builder( stage, "domain", Sdf.ValueTypeNames.Float2, { Sdf.PropertySpec.DisplayNameKey: 'Domain' }, # metadata [ node_prim_path ] ) with ui.HStack(): key = "domainBoundaryMode" with ui.HStack(): self.build_label("Domain Boundary Mode") value = prim.GetAttribute(key).Get() or "" self.domain_boundary_mode_combo_box = ui.ComboBox(self.create_combo_list_model(value, ['clampToEdge', 'clampToTransparent']), name=key) self.domain_boundary_mode_combo_box.model.add_item_changed_fn(lambda m, i: self.store_value("domainBoundaryMode", m.get_current_string(), 'clampToEdge', Sdf.ValueTypeNames.Token)) with ui.HStack(): key = "colormapSource" with ui.HStack(): self.build_label("Colormap Source") value = prim.GetAttribute(key).Get() or "" self.colormap_source_combo_box = ui.ComboBox(self.create_combo_list_model(value, ['colormapValues', 'rgbaPoints']), name=key) self.colormap_source_combo_box.model.add_item_changed_fn(lambda m, i: self.switch_colormap_source(m.get_current_string())) colormapSource = prim.GetAttribute("colormapSource").Get() or "colormapValues" if colormapSource == "rgbaPoints": # adding custom colormap editor frame = CustomLayoutFrame(hide_extra=True) with frame: colormap_frame = ui.Frame(height=0) with colormap_frame: ColorMap(frame, prim, ["xPoints", "rgbaPoints"]) with ui.HStack(): self.build_label("Load Colormap Preset") preset_combo_box = ui.ComboBox(self.create_combo_list_model('', [''] + ColormapPresets.get_labels()), name='loadColormapPreset') preset_combo_box.model.add_item_changed_fn(lambda model, i: self.load_colormap_preset(prim, model.get_current_string(), colormapSource))
4,502
Python
46.904255
199
0.639938
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/tests/__init__.py
from .test_settings import TestIndeXSettingsUI from .test_properties import TestIndeXPropertiesUI
98
Python
31.999989
50
0.877551
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/tests/test_properties.py
#!/usr/bin/env python3 # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.test import omni.usd from omni.kit import ui_test from pxr import Sdf, UsdShade # Test custom properties UI for NVIDIA IndeX class TestIndeXPropertiesUI(omni.kit.test.AsyncTestCase): async def setUp(self): super().setUp() self._usd_context = omni.usd.get_context() from omni.hydra.index.tests import USD_DIR test_file_path = USD_DIR.joinpath("torus-settings.usda").absolute() await self._usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() self._stage = self._usd_context.get_stage() self.assertIsNotNone(self._stage) def _print_sub_widget(self, parent): for w in parent.find_all("**"): print("-", w, w.realpath) if hasattr(w.widget, 'identifier') and w.widget.identifier: print(" id =", w.widget.identifier) if hasattr(w.widget, 'name') and w.widget.name: print(" name =", w.widget.name) if hasattr(w.widget, 'title') and w.widget.title: print(" title =", w.widget.title) # Test "IndeX Volume" properties of UsdVolume prims async def test_volume_properties(self): prim = self._stage.GetPrimAtPath("/World/Volume") self.assertTrue(prim.IsValid()) # Select the prim. self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) # Need to wait for additional frames for omni.ui rebuild to take effect await ui_test.wait_n_updates(20) index_volume = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Volume'") self.assertTrue(index_volume) custom_data = prim.GetCustomData() self.assertTrue('nvindex.renderSettings' in custom_data) render_settings = custom_data['nvindex.renderSettings'] filter_mode_widget = index_volume.find("**/ComboBox[0].name=='filterMode'") self.assertTrue(filter_mode_widget) self.assertEqual(filter_mode_widget.model.get_current_string(), render_settings['filterMode']) sampling_distance_widget = index_volume.find("**/FloatField[0].name=='samplingDistance'") self.assertTrue(sampling_distance_widget) self.assertEqual(sampling_distance_widget.model.get_value_as_float(), render_settings['samplingDistance']) # Modify values in UI and check if USD is updated filter_mode_widget.model.set_current_index(0) # set to default filter # await sampling_distance_widget.input(str(2.345)) # This doesn't seem to work sampling_distance_widget.model.set_value(2.345) await ui_test.wait_n_updates(2) custom_data = prim.GetCustomData() render_settings = custom_data['nvindex.renderSettings'] self.assertTrue('filterMode' not in render_settings) # default value will not be stored self.assertEqual(sampling_distance_widget.model.get_value_as_float(), render_settings['samplingDistance']) # Now modify the USD and check if UI is updated new_filter_mode = "nearest" new_sampling_distance = 1.2345 prim.SetCustomDataByKey("nvindex.renderSettings:filterMode", new_filter_mode) prim.SetCustomDataByKey("nvindex.renderSettings:samplingDistance", new_sampling_distance) await omni.kit.app.get_app().next_update_async() custom_data = prim.GetCustomData() # Need to reacquire widgets after rebuild filter_mode_widget = index_volume.find("**/ComboBox[0].name=='filterMode'") self.assertTrue(filter_mode_widget) self.assertEqual(filter_mode_widget.model.get_current_string(), new_filter_mode) sampling_distance_widget = index_volume.find("**/FloatField[0].name=='samplingDistance'") self.assertTrue(sampling_distance_widget) self.assertEqual(sampling_distance_widget.model.get_value_as_float(), new_sampling_distance) # Test "IndeX Colormap" properties of (custom) Colormap prims async def test_colormap_properties(self): prim = self._stage.GetPrimAtPath("/World/Volume/mat/Colormap") self.assertTrue(prim.IsValid()) self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) await ui_test.wait_n_updates(20) index_colormap = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Colormap'") self.assertTrue(index_colormap) # Colormap domain domain_group = index_colormap.find("**/drag_per_channel_domain") self.assertTrue(domain_group) domain_value = [] for float_drag in domain_group.find_all("**/FloatDrag[0]"): domain_value.append(float_drag.widget.model.get_value_as_float()) self.assertEqual(domain_value, prim.GetAttribute("domain").Get()) # Colormap domain boundary mode domain_boundary_mode_widget = index_colormap.find("**/ComboBox[0].name=='domainBoundaryMode'") self.assertTrue(domain_boundary_mode_widget) self.assertEqual(domain_boundary_mode_widget.model.get_current_string(), prim.GetAttribute("domainBoundaryMode").Get()) # Colormap source colormap_source_widget = index_colormap.find("**/ComboBox[0].name=='colormapSource'") self.assertTrue(colormap_source_widget) self.assertEqual(colormap_source_widget.model.get_current_string(), "colormapValues") # Set a simple rgbaValues colormap prim.CreateAttribute("xPoints", Sdf.ValueTypeNames.FloatArray).Set([0.5, 0.7, 1.0]) prim.CreateAttribute("rgbaPoints", Sdf.ValueTypeNames.Float4Array).Set([(0, 1, 0, 0.14), (1, 0, 0, 0.25), (1, 1, 0, 0.25)]) # Switch colormap source colormap_source_widget = index_colormap.find("**/ComboBox[0].name=='colormapSource'") colormap_source_widget.model.set_current_index(1) await ui_test.wait_n_updates(2) # Verify values of the first control point in colormap editor colormap_point_position_widget = index_colormap.find("**/FloatDrag[*].name=='colormapPointPosition'") self.assertTrue(colormap_point_position_widget) self.assertEqual(colormap_point_position_widget.model.get_value_as_float(), prim.GetAttribute("xPoints").Get()[0]) colormap_point_color_widget = index_colormap.find("**/ColorWidget[*].name=='colormapPointColor'") self.assertTrue(colormap_point_color_widget) color_model = colormap_point_color_widget.model sub_models = color_model.get_item_children(None) rgba_value = [ color_model.get_item_value_model(s).get_value_as_float() for s in sub_models ] colormap_point_opacity_widget = index_colormap.find("**/FloatDrag[*].name=='colormapPointOpacity'") self.assertTrue(colormap_point_opacity_widget) rgba_value.append(colormap_point_opacity_widget.model.get_value_as_float()) self.assertEqual(rgba_value, prim.GetAttribute("rgbaPoints").Get()[0]) # Modify values in UI and check if USD is updated colormap_point_position_widget.model.set_value(0.2) for s, v in zip(sub_models, [0.1, 0.2, 0.3]): color_model.get_item_value_model(s).set_value(v) colormap_point_opacity_widget.model.set_value(0.4) await ui_test.wait_n_updates(2) self.assertEqual(colormap_point_position_widget.model.get_value_as_float(), prim.GetAttribute("xPoints").Get()[0]) self.assertEqual(colormap_point_opacity_widget.model.get_value_as_float(), prim.GetAttribute("rgbaPoints").Get()[0][3]) # Load a colormap preset load_colormap_preset_widget = index_colormap.find("**/ComboBox[0].name=='loadColormapPreset'") self.assertTrue(load_colormap_preset_widget) preset_name = "Green Ramp" presets = load_colormap_preset_widget.model.get_item_list() self.assertTrue(preset_name in presets) load_colormap_preset_widget.model.set_current_index(presets.index(preset_name)) await ui_test.wait_n_updates(2) self.assertEqual(prim.GetAttribute("rgbaPoints").Get()[0], [0, 1, 0, 0]) # check that USD was updated # Test "IndeX Shader" properties of UsdShader prims async def test_shader_properties(self): prim = self._stage.GetPrimAtPath("/World/Volume/mat/VolumeShader") self.assertTrue(prim.IsValid()) self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) await ui_test.wait_n_updates(20) index_shader = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Shader'") self.assertTrue(index_shader) # Shader implementation source implementation_source_widget = index_shader.find("**/ComboBox[0].name=='info:implementationSource'") self.assertTrue(implementation_source_widget) self.assertEqual(implementation_source_widget.model.get_current_string(), "id") # Provide shader from asset implementation_source_widget.model.set_current_index(implementation_source_widget.model.get_item_list().index("sourceAsset")) await ui_test.wait_n_updates(2) source_asset_widget = index_shader.find("**/sdf_asset_info:xac:sourceAsset.identifier=='sdf_asset_info:xac:sourceAsset'") self.assertTrue(source_asset_widget) source_asset_widget.model.set_value("./torus-shader.cu") await ui_test.wait_n_updates(2) shader = UsdShade.Shader(prim) self.assertTrue(shader.GetSourceAsset('xac')) # Integrate the asset integrate_asset_widget = index_shader.find("**/Button[*].name=='integrateAssetContents'") self.assertTrue(integrate_asset_widget) await integrate_asset_widget.click() await ui_test.wait_n_updates(2) self.assertTrue(shader.GetSourceCode('xac').startswith("NV_IDX_XAC_VERSION_1_0")) # Edit the code source_code_widget = index_shader.find("**/StringField[*].name=='info:xac:sourceCode'") self.assertTrue(source_code_widget) source_code = source_code_widget.model.get_value_as_string() + "// foo bar baz!" source_code_widget.model.set_value(source_code) await ui_test.wait_n_updates(2) self.assertNotEqual(shader.GetSourceCode('xac'), source_code) # not saved yet save_compile_widget = index_shader.find("**/Button[*].name=='saveAndCompile'") self.assertTrue(save_compile_widget) await save_compile_widget.click() await ui_test.wait_n_updates(2) self.assertEqual(shader.GetSourceCode('xac'), source_code) # Load a shader preset load_shader_preset_widget = index_shader.find("**/ComboBox[0].name=='loadShaderPreset'") self.assertTrue(load_shader_preset_widget) preset_name = "Minimal Volume Shader" presets = load_shader_preset_widget.model.get_item_list() self.assertTrue(preset_name in presets) load_shader_preset_widget.model.set_current_index(presets.index(preset_name)) await ui_test.wait_n_updates(2) self.assertTrue(shader.GetSourceCode('xac').startswith("NV_IDX_XAC_VERSION_1_0")) self.assertTrue("foo bar baz" not in shader.GetSourceCode('xac')) # Test the "Create Volume Material" button in "IndeX Volume" properties of UsdVolume prims async def test_create_volume_material(self): prim = self._stage.GetPrimAtPath("/World/Volume") self.assertTrue(prim.IsValid()) self._usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) await ui_test.wait_n_updates(20) index_volume = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='IndeX Volume'") self.assertTrue(index_volume) old_material = UsdShade.MaterialBindingAPI(prim).GetDirectBinding().GetMaterial() self.assertTrue(old_material) # Create new volume material create_material_widget = index_volume.find("**/Button[*].name=='createVolumeMaterial'") self.assertTrue(create_material_widget) await create_material_widget.click() await ui_test.wait_n_updates(2) # Check that the material was created and bound new_material = UsdShade.MaterialBindingAPI(prim).GetDirectBinding().GetMaterial() self.assertTrue(new_material) self.assertEqual(new_material.GetPath(), str(prim.GetPath()) + "/Material") # Restore previous material UsdShade.MaterialBindingAPI(prim).Bind(old_material)
12,948
Python
48.613027
133
0.678638
omniverse-code/kit/exts/omni.index.settings.core/omni/index/settings/core/tests/test_settings.py
#!/usr/bin/env python3 # 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 import omni.kit.test import omni.usd from omni.kit import ui_test settings = carb.settings.get_settings() class TestIndeXSettingsUI(omni.kit.test.AsyncTestCase): async def setUp(self): super().setUp() await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() def get_render_setings_window(self): render_settings_window = ui_test.find("Render Settings") render_settings_window.widget.height = 600 render_settings_window.widget.width = 600 render_settings_window.widget.visible = True return render_settings_window def assertSetting(self, setting_name, setting_value): self.assertTrue(settings.get(setting_name) == setting_value) async def test_settings(self): # Set initial state roi_min_org = [0, 0, 0] roi_max_org = [10, 10, 10] settings.set("/nvindex/dataBboxMin", roi_min_org) settings.set("/nvindex/dataBboxMax", roi_max_org) settings.set("/rtx/index/regionOfInterestMin", roi_min_org) settings.set("/rtx/index/regionOfInterestMax", roi_max_org) render_settings_window = self.get_render_setings_window() self.assertTrue(render_settings_window) # Select IndeX "Cluster" settings in the global "Render Settings" tab button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]") self.assertTrue(button) await button.click() # Cluster / Cluster Compositing Settings collapsable_frame = render_settings_window.find("**/Cluster Compositing Settings") self.assertTrue(collapsable_frame) collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() # Select IndeX "Common" settings in the global "Render Settings" tab button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[1]") self.assertTrue(button) await button.click() # Common / Scene Settings collapsable_frame = render_settings_window.find("**/Scene Settings") self.assertTrue(collapsable_frame) collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() setting_name = "/rtx/index/regionOfInterest" roi_min_org = settings.get(setting_name + "Min") roi_max_org = settings.get(setting_name + "Max") setting_hstack = collapsable_frame.find("/**/HStack_Region_of_Interest_Min") self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack)) setting_hstack = collapsable_frame.find("/**/HStack_Region_of_Interest_Max") self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack)) settings.set(setting_name + "Max", [5, 10, 10]) await omni.kit.app.get_app().next_update_async() self.assertSetting(setting_name + "Min", roi_min_org) self.assertSetting(setting_name + "Max", [5, 10, 10]) button = collapsable_frame.find("/**/Button[0]") self.assertTrue(button) await button.click(); self.assertSetting(setting_name + "Min", roi_min_org) self.assertSetting(setting_name + "Max", roi_max_org) # Common / Render Settings collapsable_frame = render_settings_window.find("**/Render Settings") self.assertTrue(collapsable_frame) collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() setting_hstack = collapsable_frame.find("/**/HStack_Background_Color") self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack)) # Background color setting_name = "/rtx/index/backgroundColor" self.assertSetting(setting_name, [0.0, 0.0, 0.0]) # default background_color_field = setting_hstack.find("**/MultiFloatDragField[0]") self.assertTrue(background_color_field) color_model = background_color_field.model sub_models = color_model.get_item_children(None) color_model.get_item_value_model(sub_models[0]).set_value(1.0) color_model.get_item_value_model(sub_models[2]).set_value(0.25) await omni.kit.app.get_app().next_update_async() self.assertSetting(setting_name, [1.0, 0.0, 0.25])
4,792
Python
40.318965
98
0.673831
omniverse-code/kit/exts/omni.index.settings.core/docs/index.rst
omni.index.settings.core ########################### .. toctree:: :maxdepth: 1
84
reStructuredText
11.142856
27
0.440476
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_portable.py
import omni.kit.test from .test_base import KitLaunchTest class TestPortable(KitLaunchTest): async def test_kit_portable(self): # empty kit file kit_file = "[dependencies]\n" # script to check portable location is as passed in script = """ import omni.kit.app import carb.tokens from pathlib import Path data = Path(carb.tokens.get_tokens_interface().resolve("${{data}}")).resolve() portable_path = Path(r'{0}').resolve() def is_subpath(path, root): return root in path.parents if not is_subpath(data, portable_path): print(f"Fail, expected portable path: {{(portable_path)}}") omni.kit.app.get_app().post_quit(-1) """ # kit.portable: portable_file = f"{self._temp_folder}/kit.portable" with open(portable_file, "w") as f: f.write("foo") portable_path = f"{self._temp_folder}/foo" await self._run_kit_with_script( script.format(portable_path), args=[], kit_file=kit_file, portable=False, kit_file_name="test_bar.kit" ) # test_bar.portable (like app name) (overrides kit.portable too) portable_file = f"{self._temp_folder}/test_bar.portable" with open(portable_file, "w") as f: f.write("wow") portable_path = f"{self._temp_folder}/wow" await self._run_kit_with_script( script.format(portable_path), args=[], kit_file=kit_file, portable=False, kit_file_name="test_bar.kit" ) # arg: `--portable-root` (overrides everything) portable_path = f"{self._temp_folder}/lake" await self._run_kit_with_script( script.format(portable_path), args=["--portable-root", portable_path], kit_file=kit_file, portable=False, kit_file_name="test_bar.kit", )
1,832
Python
31.157894
114
0.608079
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_non_ascii_cmd_params.py
import omni.kit.test import omni.kit.app from pathlib import Path from .test_base import KitLaunchTest class TestNonAsciiCmdParams(KitLaunchTest): async def test_kit_app_with_only_core_exts(self): # Disabling tests untill OM-39027 is resolved return kit_file = "[dependencies]\n" kit_file += '"omni.kit.loop-default" = {}\n' script = """ import carb.settings import omni.kit.app s = carb.settings.get_settings() def check(path, expected): v = s.get(path) if v != expected: print(f"[Test Fail] setting path: {path}, expected: {expected}, got: {v}") omni.kit.app.get_app().post_quit(-1) """ testParamPaths = ["/my/test/unicode_param", "/my/test/usual_param", "/my/test/unicode_param2"] testParamValues = ["\U0001F44D", "test", "\u0627\u1F600"] # Adding checks if unicode params were properly set into settings script += "".join(map(lambda x, y: f"check(\"{x}\", \"{y}\")\n", testParamPaths, testParamValues)) # Making sure the executed script has proper unicode symbols script += f""" test_unicode_char = \"{testParamValues[0]}\" test_char_code = ord(test_unicode_char) expected_code = 128077 if test_char_code != expected_code: print(f"[Test Fail] Wrong tested unicode character code: {{test_unicode_char}}, expected: {{expected_code}}, got: {{test_char_code}}") omni.kit.app.get_app().post_quit(-1) """ # Adding necessary command line arguments additional_args = [*map(lambda x, y: f"--{x}={y}", testParamPaths, testParamValues)] await self._run_kit_with_script(script, args=["--/app/quitAfter=10", *additional_args], kit_file=kit_file)
1,697
Python
33.653061
138
0.647613
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_default_stage.py
import omni.kit.test from .test_base import KitLaunchTest from pathlib import Path import omni class TestDefaultStage(KitLaunchTest): async def test_default_stage(self): """Test to ensure a default stage is created when it's requested.""" kit_file = "[dependencies]\n" kit_file += '"omni.usd" = {}\n' kit_file += '"omni.kit.loop-default" = {}\n' kit_file += '"omni.kit.stage_templates" = {}\n' kit_file += """ # Register extension folder from this repo in kit [settings.app.exts] folders.'++' = ["${app}/../exts" ] [settings.app.extensions] enabledDeprecated = [ ] """ script = f""" import omni.usd import omni.kit.app import asyncio from pxr import Sdf, Usd async def main(): for i in range(10): await omni.kit.app.get_app().next_update_async() usd_context = omni.usd.get_context() # Gets stage to see if a default stage is created. stage = usd_context.get_stage() stage.DefinePrim("/test") asyncio.ensure_future(main()) """ await self._run_kit_with_script( script, args=["--no-window", "--/app/quitAfter=20", "--/app/content/emptyStageOnStart=True"], kit_file=kit_file )
1,293
Python
24.372549
97
0.584687
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_runloop.py
import omni.kit.test from .test_base import KitLaunchTest class TestKitRunLoop(KitLaunchTest): async def test_kit_runloop(self): # Build kit file kit_file = "[dependencies]\n" kit_file += '"omni.kit.loop-default" = {}\n' kit_file += "[settings.app.runLoops]\n" LOOPS = [("loop60", 60), ("loop30", 30), ("main", 300)] for loop, freq in LOOPS: kit_file += f"{loop}.rateLimitEnabled = true\n" kit_file += f"{loop}.rateLimitFrequency = {freq}\n" kit_file += f"{loop}.rateLimitUseBusyLoop = true\n" # Subscribe to update events, count them. Validate count and thread ids. Measure time. Overall test code should # take 1 second = 300 main updates. script = f""" from collections import defaultdict import threading import time import omni.kit.app app = omni.kit.app.get_app() def simple_assert(v, message): if not v: print(f"[error] simple_assert failure: {{message}}") omni.kit.app.get_app().post_quit(123) subs = [] cnt = defaultdict(int) threads = {{}} start_t = time.time() for loop, freq in {LOOPS}: def on_update(e, loop=loop): cnt[loop] += 1 # Check thread id tid = threading.get_ident() if loop not in threads: threads[loop] = tid simple_assert(threads[loop] == tid, f"runloop: {{loop}}, thread id is incorrect") if loop == "main" and cnt[loop] >= 300: # validate count for loop, freq in {LOOPS}: f = cnt[loop] / freq simple_assert(f >= 0.80 and f <= 1.20, f"runloop: {{loop}}, expected: {{freq}}, result: {{cnt[loop]}}") dt = time.time() - start_t simple_assert(dt >= 0.8 and dt <= 1.2, f"test took longer than expected: {{dt}}") omni.kit.app.get_app().post_quit(0) subs.append(app.get_update_event_stream(loop).create_subscription_to_pop( on_update )) """ await self._run_kit_with_script(script, args=["--/app/quitAfter=10000"], kit_file=kit_file)
2,086
Python
31.107692
119
0.580537
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_ext_api.py
import omni.kit.app import omni.kit.test import os from pathlib import Path class TestExtAPI(omni.kit.test.AsyncTestCase): async def test_ext_helpers(self): manager = omni.kit.app.get_app().get_extension_manager() # Enable ext id my_id = manager.get_enabled_extension_id("omni.kit.core.tests") self.assertEqual(my_id.split("-")[0], "omni.kit.core.tests") # Ext name self.assertEqual(omni.ext.get_extension_name(my_id), "omni.kit.core.tests") self.assertEqual(omni.ext.get_extension_name("omni.kit.some_ext_id"), "omni.kit.some_ext_id") self.assertEqual(omni.ext.get_extension_name("omni.kit.some_ext_id-1.0.0"), "omni.kit.some_ext_id") self.assertEqual(omni.ext.get_extension_name("omni.kit.some_ext_id-variant-1.0.0"), "omni.kit.some_ext_id-variant") # Ext id from module self.assertEqual(manager.get_extension_id_by_module(__name__), my_id) self.assertEqual(manager.get_extension_id_by_module("omni.kit.core.tests"), my_id) self.assertEqual(manager.get_extension_id_by_module("omni.kit.core.tests.test_base"), my_id) self.assertEqual(manager.get_extension_id_by_module("omni.kit.core"), None) # Ext path root = Path(os.path.dirname(__file__)).parent.parent.parent.parent self.assertEqual(root, Path(manager.get_extension_path(my_id))) self.assertEqual(root, Path(manager.get_extension_path_by_module(__name__))) self.assertEqual(root, Path(manager.get_extension_path_by_module("omni.kit.core.tests"))) self.assertEqual(root, Path(manager.get_extension_path_by_module("omni.kit.core.tests.test_base"))) self.assertEqual(manager.get_extension_path_by_module("omni.kit.core"), None) async def test_solve_extensions(self): manager = omni.kit.app.get_app().get_extension_manager() expected_sequence = ["omni.kit.actions.core", "omni.kit.commands"] # pass by name result, exts, err = manager.solve_extensions(["omni.kit.commands"], add_enabled=False, return_only_disabled=False) self.assertTrue(result) self.assertListEqual([e["name"] for e in exts], expected_sequence) self.assertEqual(err, "") commands_ext_id = exts[1]["id"] # pass by id result, exts, err = manager.solve_extensions([commands_ext_id], add_enabled=False, return_only_disabled=False) self.assertTrue(result) self.assertListEqual([e["name"] for e in exts], expected_sequence) self.assertEqual(err, "") # pass both result, exts, err = manager.solve_extensions(expected_sequence, add_enabled=False, return_only_disabled=False) self.assertTrue(result) self.assertListEqual([e["name"] for e in exts], expected_sequence) self.assertEqual(err, "") # pass wrong version result, exts, err = manager.solve_extensions(["omni.kit.actions.core-55.5.5", "omni.kit.commands"], add_enabled=False, return_only_disabled=False) self.assertFalse(result) self.assertTrue(len(err) > 0) # do not return enabled result, exts, err = manager.solve_extensions(["omni.kit.core.tests"], add_enabled=False, return_only_disabled=True) self.assertTrue(result) self.assertTrue(len(exts) == 0)
3,325
Python
45.194444
154
0.664662
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/__init__.py
from .test_core_only import * from .test_ext_api import * from .test_app_api import * from .test_runloop import * from .test_portable import * from .test_persistent_settings import * from .test_post_quit_hang import * from .test_non_ascii_cmd_params import * from .test_script_exec import * from .test_extensions import * from .test_python_bat import * from .test_default_stage import * # Expose our public functions __all__ = ["validate_extensions_load", "validate_extensions_tests", "app_startup_time", "app_startup_warning_count"] from .scripts.extensions_load import validate_extensions_load from .scripts.extensions_tests import validate_extensions_tests from .scripts.app_startup import app_startup_time, app_startup_warning_count
738
Python
37.894735
116
0.772358
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_python_bat.py
import carb.tokens import omni.kit.test import os from .test_base import run_process class TestPythonBat(omni.kit.test.AsyncTestCase): async def test_python_bat(self): resolve = carb.tokens.get_tokens_interface().resolve python_path = resolve("${kit}/python${shell_ext}") self.assertTrue(os.path.exists(python_path)) async def _run_python_and_check(args, timeout=30): launch_args = [python_path] + args code, err_messages, *_ = await run_process(launch_args, timeout) if len(err_messages) > 0: print(err_messages) self.assertEqual(len(err_messages), 0, msg=err_messages) self.assertEqual(code, 0) # smoke test and it even runs python ok await _run_python_and_check(["-c", "import sys"]) # check that we can import a few popular modules await _run_python_and_check(["-c", "import carb; import omni.kit.app"]) await _run_python_and_check(["-c", "import omni.usd"]) await _run_python_and_check(["-c", "import omni.ui"])
1,084
Python
35.166665
79
0.621771
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_persistent_settings.py
import omni.kit.test from .test_base import KitLaunchTest # fmt: off class TestPersistentSettings(KitLaunchTest): async def test_persistent_settings(self): kit_file_name = "test_persistent_settings.kit" # In total in that test we have 3 setting values: regular, persistent set in kit file, persistent new kit_file = """ [settings] test_banana.just_some_value = 2 persistent.test_banana.saved_thing = 10 """ # Functions / header to use in all scripts script_base = """ import carb.settings s = carb.settings.get_settings() def check(path, expected): v = s.get(path) if v != expected: print(f"[Test Fail] setting path: {path}, expected: {expected}, got: {v}") omni.kit.app.get_app().post_quit(-1) """ # Clean start, set a bunch of settings persistent or not script = script_base + """ check("/test_banana/just_some_value", 2) check("/persistent/test_banana/saved_thing", 10) s.set("/test_banana/just_some_value", 3) s.set("/persistent/test_banana/saved_thing", 1515) s.set("/persistent/test_banana/another_saved_thing", 78) """ await self._run_kit_with_script(script, args=["--reset-user"], kit_file=kit_file, kit_file_name=kit_file_name) # Check persistent kept script = script_base + """ check("/test_banana/just_some_value", 2) check("/persistent/test_banana/saved_thing", 1515) check("/persistent/test_banana/another_saved_thing", 78) """ await self._run_kit_with_script(script, args=[], kit_file=kit_file, kit_file_name=kit_file_name) # Check that in different app or with different config path they are not loaded: script = script_base + """ check("/test_banana/just_some_value", 2) check("/persistent/test_banana/saved_thing", 10) check("/persistent/test_banana/another_saved_thing", None) """ await self._run_kit_with_script(script, args=[], kit_file=kit_file, kit_file_name="test_persistent_settings_other_app.kit") await self._run_kit_with_script(script, args=["--/app/userConfigPath='${data}/lol.json'"], kit_file=kit_file, kit_file_name=kit_file_name) # Check we can override them with cmd script = script_base + """ check("/test_banana/just_some_value", 333) check("/persistent/test_banana/saved_thing", 888) check("/persistent/test_banana/another_saved_thing", 999) """ args = [ "--/persistent/test_banana/saved_thing=888", "--/persistent/test_banana/another_saved_thing=999", "--/test_banana/just_some_value=333" ] await self._run_kit_with_script(script, args=args, kit_file=kit_file, kit_file_name=kit_file_name) # Run without args to check that persistent kept script = script_base + """ check("/test_banana/just_some_value", 2) check("/persistent/test_banana/saved_thing", 888) check("/persistent/test_banana/another_saved_thing", 999) """ await self._run_kit_with_script(script, args=[], kit_file=kit_file, kit_file_name=kit_file_name) # Reset settings script = script_base + """ check("/test_banana/just_some_value", 2) check("/persistent/test_banana/saved_thing", 10) check("/persistent/test_banana/another_saved_thing", None) """ await self._run_kit_with_script(script, args=["--reset-user"], kit_file=kit_file, kit_file_name=kit_file_name) # fmt: on
3,363
Python
38.57647
146
0.663098
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_script_exec.py
import omni.kit.test import os from pathlib import Path from .test_base import KitLaunchTest class TestScriptExec(KitLaunchTest): async def test_script_exec(self): kit_file = "\n" script_base = """ import omni.kit.app import sys def check(v, expected): if v != expected: print(f"[Test Fail] expected: {expected}, got: {v}") omni.kit.app.get_app().post_quit(-1) """ # Regular run script = script_base + """ check(len(sys.argv), 1) """ await self._run_kit_with_script(script, kit_file=kit_file) # Pass args script = script_base + """ check(len(sys.argv), 3) check(sys.argv[1], "abc") check(sys.argv[2], "42") """ await self._run_kit_with_script(script, kit_file=kit_file, script_extra_args=" \"abc\" 42") # Subfolder with a space in path subfolder = f"{self._temp_folder}/abc def" os.makedirs(subfolder) script = script_base + """ check(len(sys.argv), 1) """ script_file = f"\"{subfolder}/script_1.py\"" await self._run_kit_with_script(script, kit_file=kit_file, script_file=script_file) # Subfolder with a space in path + args script = script_base + """ check(len(sys.argv), 3) check(sys.argv[1], "abc") check(sys.argv[2], "42") """ script_file = f"\"{subfolder}/script_2.py\"" await self._run_kit_with_script(script, kit_file=kit_file, script_file=script_file, script_extra_args=" \"abc\" 42")
1,502
Python
27.903846
124
0.595206
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_core_only.py
import omni.kit.test import omni.kit.app from pathlib import Path from .test_base import KitLaunchTest class TestCoreOnlyConfiguration(KitLaunchTest): async def test_kit_app_with_only_core_exts(self): manager = omni.kit.app.get_app().get_extension_manager() core_exts = [] for ext in manager.get_extensions(): info = manager.get_extension_dict(ext["id"]) ext_folder_name = Path(info["path"]).parts[-2] if ext_folder_name == "extscore": core_exts.append(ext["name"]) self.assertTrue(info["isCore"]) self.assertGreater(len(core_exts), 0) # Enable only core exts: kit_file = "[dependencies]\n" for ext in core_exts: kit_file += '"{0}" = {{}}\n'.format(ext) kit_file += "\n[settings.app.exts]\n" kit_file += r'folders = ["${kit}/extscore"]' # Check all extensions enabled script = f""" import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() core_exts = {core_exts} for ext in core_exts: if not manager.is_extension_enabled(ext): print("failed to enable extension: " + ext) omni.kit.app.get_app().post_quit(-1) """ await self._run_kit_with_script(script, args=["--/app/quitAfter=10"], kit_file=kit_file)
1,337
Python
31.634146
96
0.598355
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_app_api.py
import carb.tokens import omni.kit.app import omni.kit.test import os import sys from pathlib import Path class TestAppAPI(omni.kit.test.AsyncTestCase): async def test_tokens(self): resolve = carb.tokens.get_tokens_interface().resolve ABS_TOKENS = ["${cache}", "${kit}", "${data}", "${logs}", "${app}", "${temp}"] for t in ABS_TOKENS: path = resolve(t) self.assertTrue(os.path.isabs(path)) self.assertTrue(os.path.exists(path)) python_exe = sys.prefix + "/" + ("python.exe" if sys.platform == "win32" else "bin/python3") self.assertEqual(os.path.normpath(resolve("${python}")), os.path.normpath(python_exe))
693
Python
30.545453
100
0.623377
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_extensions.py
import omni.kit.test from .test_base import KitLaunchTest from .scripts import extensions_load, extensions_tests import inspect import sys class TestExtensions(KitLaunchTest): async def setUp(self): await super().setUp() self.app_to_test = "omni.app.full" # basic kit file with additional test dependencies # Note we need to manually add some [[test]] dependencies (could be automated) self.kit_file = f""" [dependencies] "{self.app_to_test}" = {{}} "omni.kit.ui_test" = {{}} # test dependency from omni.app.full.kit "omni.kit.test_suite.helpers" = {{}} # test dependency from omni.app.full.kit "omni.kit.test_helpers_gfx" = {{}} # test dependency from omni.renderer.core "omni.kit.hydra_texture" = {{}} # test dependency from omni.kit.viewport.legacy_gizmos "omni.rtx.tests" = {{}} # test dependency from omni.hydra.scene_api """ async def test_l1_extensions_have_tests(self): # This list should be empty or near empty ideally EXCLUSION_LIST = [ "omni.physx.cct", "omni.kit.widget.live", "omni.mdl", "omni.mdl.neuraylib", ] # These extensions only run tests on win32 for now if sys.platform != "win32": EXCLUSION_LIST.append("omni.hydra.scene_api") EXCLUSION_LIST.append("omni.rtx.tests") script = inspect.getsource(extensions_tests) script = script.replace("EXCLUSION_LIST = []", f"EXCLUSION_LIST = {EXCLUSION_LIST}") # when it fails it will assert with the number of extensions that have no tests, scroll up in the log to find them await self._run_kit_with_script( script, args=[ "--/app/extensions/disableStartup=1", # extensions startup is disabled "--/app/extensions/registryEnabled=0", "--/app/quitAfter=10", "--/crashreporter/gatherUserStory=0", # don't pop up the GUI on crash "--no-window", ], kit_file=self.kit_file, timeout=60, ) async def test_l1_extensions_load(self): script = inspect.getsource(extensions_load) await self._run_kit_with_script( script, args=[ "--/app/extensions/disableStartup=1", # extensions startup is disabled "--/app/extensions/registryEnabled=0", "--/app/quitAfter=10", "--/crashreporter/gatherUserStory=0", # don't pop up the GUI on crash ], kit_file=self.kit_file, timeout=60, )
2,677
Python
37.811594
122
0.581621
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_base.py
import carb import asyncio import shutil import sys import os import subprocess import tempfile from time import time import omni.kit.test async def run_process(args, timeout, capture_output=False): returncode = 0 fail_messages = [] proc = None stdout = None try: cmd = " ".join(args) print(f">>> running process: {cmd}\n") async def run_proc(): nonlocal proc proc = await asyncio.create_subprocess_exec( *args, stdout=subprocess.PIPE if capture_output else None, stderr=subprocess.STDOUT, bufsize=0, ) await proc.wait() nonlocal returncode, stdout returncode = proc.returncode if capture_output: stdout = [] async for line in proc.stdout: stdout.append(line.decode(errors="replace").replace("\r\n", "\n").replace("\r", "\n")) proc = None await asyncio.wait_for(run_proc(), timeout) except subprocess.CalledProcessError as e: returncode = e.returncode fail_messages.append(f"subprocess.CalledProcessError was raised: {e.output}") except asyncio.TimeoutError: fail_messages.append(f"Process timed out (timeout: {timeout}). Terminating.") if proc: proc.terminate() # return code failure check if returncode != 0: fail_messages.append(f"Process return code: {returncode} != 0.") return (returncode, fail_messages, stdout) class KitLaunchTest(omni.kit.test.AsyncTestCase): def __init__(self, tests=()): super().__init__(tests) async def _run_kit(self, args, portable=True, timeout=180, **kwargs): launch_args = [sys.argv[0]] + args launch_args += ["--/log/flushStandardStreamOutput=1", "--/app/fastShutdown=1", "--/crashreporter/gatherUserStory=0"] if portable: launch_args += ["--portable"] return await run_process(launch_args, timeout, **kwargs) async def _run_kit_and_check(self, args, portable=True, timeout=180): code, err_messages, stdout = await self._run_kit(args, portable, timeout) if len(err_messages) > 0: print(err_messages) self.assertEqual(len(err_messages), 0, msg=err_messages) self.assertEqual(code, 0) async def _run_kit_and_capture_stdout(self, args, portable=True, timeout=180, expect_errors=[], expect_success=True): code, err_messages, stdout = await self._run_kit(args, portable, timeout, capture_output=True) left_errors = list(expect_errors) # Check that all expected errors are present in the output # Replace [Error] with [SkippedError] to avoid main test failure for line in stdout: if "[Error]" in line: line = line.replace("[Error]", "[SkippedError]") for err in left_errors: if err in line: left_errors.remove(err) sys.stdout.write(line) self.assertTrue(len(left_errors) == 0, f"Expected errors not found: {left_errors}") if expect_success: self.assertEqual(code, 0) else: self.assertNotEqual(code, 0) async def _run_kit_with_script( self, script_content, args=[], kit_file=None, add_exec_check=True, portable=True, kit_file_name=None, script_file=None, script_extra_args="", timeout=180, ): ts = int(time()) # Touch special file and check after running kit that file exist. This way we can communicate failure to execute a script. exec_check_file = f"{self._temp_folder}/exec_ok_{ts}" if add_exec_check: script_content += "\n" script_content += "from pathlib import Path\n" script_content += f"Path(r'{exec_check_file}').touch()\n" if not script_file: script_file = f"{self._temp_folder}/script_{ts}.py" with open(script_file.strip('"'), "w") as f: f.write(script_content) carb.log_info(f"dump '{script_file}':\n{script_content}") launch_args = [] # Optionally build kit file if kit_file: if not kit_file_name: kit_file_name = f"test_{ts}.kit" kit_file_path = f"{self._temp_folder}/{kit_file_name}" with open(kit_file_path, "w") as f: f.write(kit_file) launch_args += [kit_file_path] carb.log_info(f"dump '{kit_file_path}':\n{kit_file}") launch_args += args launch_args += ["--exec", script_file + script_extra_args] await self._run_kit_and_check(launch_args, portable, timeout) if add_exec_check: self.assertTrue(os.path.exists(exec_check_file), "Script was not fully executed.") async def setUp(self): self._temp_folder = tempfile.mkdtemp() async def tearDown(self): shutil.rmtree(self._temp_folder)
5,083
Python
33.351351
130
0.581743
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/test_post_quit_hang.py
import omni.kit.test from .test_base import KitLaunchTest from pathlib import Path import omni class TestPostQuitHang(KitLaunchTest): """Test for https://nvidia-omniverse.atlassian.net/browse/OM-34203""" async def test_post_quit_api(self): kit_file = "[dependencies]\n" kit_file += '"omni.usd" = {}\n' kit_file += '"omni.kit.renderer.core" = {}\n' kit_file += '"omni.kit.loop-default" = {}\n' kit_file += '"omni.kit.mainwindow" = {}\n' kit_file += '"omni.kit.uiapp" = {}\n' kit_file += '"omni.kit.menu.file" = {}\n' kit_file += '"omni.kit.selection" = {}\n' kit_file += '"omni.kit.stage_templates" = {}\n' kit_file += """ # Register extension folder from this repo in kit [settings.app.exts] folders.'++' = ["${app}/../exts" ] [settings.app.extensions] enabledDeprecated = [ ] """ script = f""" import omni.usd import omni.kit.app import asyncio from pxr import Sdf, Usd async def main(): usd_context = omni.usd.get_context() for i in range(10): root_layer = Sdf.Layer.CreateAnonymous("test.usd") stage = Usd.Stage.Open(root_layer) await usd_context.attach_stage_async(stage) stage = usd_context.get_stage() if stage: prim = stage.DefinePrim("/World") stage.SetDefaultPrim(prim) prim = stage.GetDefaultPrim() prim.CreateAttribute("testing", Sdf.ValueTypeNames.String).Set("test") await usd_context.save_stage_async() omni.kit.app.get_app().post_quit() asyncio.ensure_future(main()) """ await self._run_kit_with_script(script, args=["--no-window"], kit_file=kit_file)
1,765
Python
29.982456
88
0.580737
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/app_startup.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["app_startup_time", "app_startup_warning_count"] import json import time from typing import Tuple import carb import carb.settings import omni.kit.app def app_startup_time(test_id: str) -> float: """Get startup time - send to nvdf""" test_start_time = time.time() startup_time = omni.kit.app.get_app().get_time_since_start_s() test_result = {"startup_time_s": startup_time} print(f"App Startup time: {startup_time}") _post_to_nvdf(test_id, test_result, time.time() - test_start_time) return startup_time def app_startup_warning_count(test_id: str) -> Tuple[int, int]: """Get the count of warnings during startup - send to nvdf""" test_start_time = time.time() warning_count = 0 error_count = 0 log_file_path = carb.settings.get_settings().get("/log/file") with open(log_file_path, "r") as file: for line in file: if "[Warning]" in line: warning_count += 1 elif "[Error]" in line: error_count += 1 test_result = {"startup_warning_count": warning_count, "startup_error_count": error_count} print(f"App Startup Warning count: {warning_count}") print(f"App Startup Error count: {error_count}") _post_to_nvdf(test_id, test_result, time.time() - test_start_time) return warning_count, error_count # TODO: should call proper API from Kit def _post_to_nvdf(test_id: str, test_result: dict, test_duration: float): """Send results to nvdf""" try: from omni.kit.test.nvdf import _can_post_to_nvdf, _get_ci_info, _post_json, get_app_info, to_nvdf_form if not _can_post_to_nvdf(): return data = {} data["ts_created"] = int(time.time() * 1000) data["app"] = get_app_info() data["ci"] = _get_ci_info() data["test"] = { "passed": True, "skipped": False, "unreliable": False, "duration": test_duration, "test_id": test_id, "ext_test_id": "omni.create.tests", "test_type": "unittest", } data["test"].update(test_result) project = "omniverse-kit-tests-results-v2" json_str = json.dumps(to_nvdf_form(data), skipkeys=True) _post_json(project, json_str) # print(json_str) # uncomment to debug except Exception as e: carb.log_warn(f"Exception occurred: {e}") if __name__ == "__main__": app_startup_time() app_startup_warning_count() omni.kit.app.get_app().post_quit(0)
2,969
Python
32.75
110
0.626474
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/extensions_load.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["validate_extensions_load"] import omni.kit.app import omni.kit.test def validate_extensions_load(): failures = [] manager = omni.kit.app.get_app().get_extension_manager() for ext in manager.get_extensions(): ext_id = ext["id"] ext_name = ext["name"] info = manager.get_extension_dict(ext_id) enabled = ext.get("enabled", False) if not enabled: continue failed = info.get("state/failed", False) if failed: failures.append(ext_name) if len(failures) == 0: print("\n[success] All extensions loaded successfuly!\n") else: print("") print(f"[error] Found {len(failures)} extensions that could not load:") for count, ext in enumerate(failures): print(f" {count+1}: {ext}") print("") return len(failures) if __name__ == "__main__": result = validate_extensions_load() omni.kit.app.get_app().post_quit(result)
1,415
Python
29.782608
79
0.650883
omniverse-code/kit/exts/omni.kit.core.tests/omni/kit/core/tests/scripts/extensions_tests.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["validate_extensions_tests"] import omni.kit.app import omni.kit.test import carb.settings EXCLUSION_LIST = [] def validate_extensions_tests(exclusion_list=[]): """Return the number of enabled extensions without python tests""" failures = [] EXCLUSION_LIST.extend(exclusion_list) settings = carb.settings.get_settings() manager = omni.kit.app.get_app().get_extension_manager() for ext in manager.get_extensions(): ext_id = ext["id"] ext_name = ext["name"] info = manager.get_extension_dict(ext_id) # No apps if info.get("isKitFile", False): print(f"[ ok ] {ext_name} is an app") continue # Exclusion list if ext_name in EXCLUSION_LIST: print(f"[ ok ] {ext_name} is in the exclusion list") continue waiver = False reason = "" cpp_tests = False test_info = info.get("test", None) if isinstance(test_info, list) or isinstance(test_info, tuple): for t in test_info: if "waiver" in t: reason = t.get("waiver", "") waiver = True if "cppTests" in t: cpp_tests = True if waiver: print(f"[ ok ] {ext_name} has a waiver: {reason}") continue enabled = ext.get("enabled", False) if not enabled: print(f"[ ok ] {ext_name} is not enabled") continue # another test will report that the extension failed to load failed = info.get("state/failed", False) if failed: print(f"[ !! ] {ext_name} failed to load") continue include_tests = [] python_dict = info.get("python", {}) python_modules = python_dict.get("module", []) + python_dict.get("modules", []) for m in python_modules: module = m.get("name") if module: include_tests.append("{}.*".format(module)) settings.set("/exts/omni.kit.test/includeTests", include_tests) print(f"[ .. ] {ext_name} get tests...") test_count = omni.kit.test.get_tests() if len(test_count) > 0: print(f"[ ok ] {ext_name} has {len(test_count)} tests") elif cpp_tests: print(f"[ ok ] {ext_name} has cpp tests") else: failures.append(ext_name) print(f"[fail] {ext_name} has {len(test_count)} tests") if len(failures) == 0: print("\n[success] All extensions have tests or waiver!\n") else: print("") print(f"[error] Found {len(failures)} extensions without tests or waiver:") for count, ext in enumerate(failures): print(f" {count+1}: {ext}") print("") return len(failures) if __name__ == "__main__": result = validate_extensions_tests() omni.kit.app.get_app().post_quit(result)
3,375
Python
32.425742
87
0.576593
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/config/extension.toml
[package] title = "Audio Oscilloscope" category = "Audio" feature = true version = "0.1.0" description = "Displays the waveform of Kit's audio output." authors = ["NVIDIA"] keywords = ["audio", "debug"] [dependencies] "carb.audio" = {} "omni.usd.libs" = {} "omni.usd" = {} "omni.ui" = {} "omni.usd.schema.semantics" = {} "omni.usd.schema.audio" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.audio.oscilloscope" [[python.module]] name = "omni.kit.audio.oscilloscope" [[test]] # Just go with default timeout unless you're testing locally. # What takes 3 seconds locally could take 3 minutes in CI. #timeout = 30 args = [ # Use the null device backend so we have a consistent backend channel count, # since that'll affect the generated image. "--/audio/deviceBackend=null", # This is needed or `omni.kit.ui_test.get_menubar().find_menu("Window")` # will return `None`. "--/app/menu/legacy_mode=false", # omni.kit.property.audio causes kit to add a "do you want to save your changes" # dialogue when kit is exiting unless this option is specified. "--/app/file/ignoreUnsavedOnExit=true", # disable DPI scaling & use no-window "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.property.audio", # needed for the (manual) USD test "omni.kit.mainwindow", # needed for omni.kit.ui_test "omni.kit.ui_test", ] stdoutFailPatterns.exclude = [ "*" # I don't want these but OmniUiTest forces me to use them, so ignore all! ]
1,589
TOML
26.413793
84
0.670233
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/__init__.py
from .oscilloscope import *
28
Python
13.499993
27
0.785714
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/oscilloscope.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.audio import omni.kit.audio.oscilloscope import omni.kit.ui import omni.ui import threading import time import re import asyncio class OscilloscopeWindowExtension(omni.ext.IExt): """Audio Recorder Window Extension""" def _menu_callback(self, a, b): self._window.visible = not self._window.visible def _read_callback(self, event): img = self._oscilloscope.get_image(); self._waveform_image_provider.set_bytes_data(img, [self._waveform_width, self._waveform_height]) def _record_clicked(self): if self._recording: self._record_button.set_style({"image_url": "resources/glyphs/audio_record.svg"}) self._recording = False; self._oscilloscope.stop() else: self._record_button.set_style({"image_url": "resources/glyphs/timeline_stop.svg"}) self._recording = True self._oscilloscope.start() def on_startup(self): self._timer = None self._waveform_width = 512; self._waveform_height = 460; try: self._oscilloscope = omni.kit.audio.oscilloscope.create_oscilloscope(self._waveform_width, self._waveform_height); except Exception as e: return; self._window = omni.ui.Window("Audio Oscilloscope", width=512, height=540) self._recording = False with self._window.frame: with omni.ui.VStack(height=0, spacing=8): # waveform with omni.ui.HStack(height=460): omni.ui.Spacer() self._waveform_image_provider = omni.ui.ByteImageProvider() self._waveform_image = omni.ui.ImageWithProvider( self._waveform_image_provider, width=omni.ui.Percent(100), height=omni.ui.Percent(100), fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, ) omni.ui.Spacer() # buttons with omni.ui.HStack(): omni.ui.Spacer() self._record_button = omni.ui.Button( width=32, height=32, clicked_fn=self._record_clicked, style={"image_url": "resources/glyphs/audio_record.svg"}, ) omni.ui.Spacer() self._sub = self._oscilloscope.get_event_stream().create_subscription_to_pop(self._read_callback) self._menuEntry = omni.kit.ui.get_editor_menu().add_item("Window/Oscilloscope", self._menu_callback) self._window.visible = False def on_shutdown(self): # pragma: no cover self._sub = None self._recorder = None self._window = None self._menuEntry = None self._oscilloscope = None menu = omni.kit.ui.get_editor_menu() if menu is not None: menu.remove_item("Window/Oscilloscope")
3,436
Python
37.188888
126
0.592549
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/tests/test_window_audio_oscilloscope.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test import omni.kit.ui_test import omni.ui as ui import omni.usd import omni.timeline import carb.tokens import omni.usd.audio from omni.ui.tests.test_base import OmniUiTest import pathlib import asyncio; class TestOscilloscopeWindow(OmniUiTest): # pragma: no cover async def _dock_window(self): await self.docked_test_window( window=self._win.window, width=512, height=540) # Before running each test async def setUp(self): await super().setUp() import omni.kit.material.library # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.audio.oscilloscope}") self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() self._golden_img_dir = self._test_path.joinpath("golden") # open the dropdown window_menu = omni.kit.ui_test.get_menubar().find_menu("Window") self.assertIsNotNone(window_menu) await window_menu.click() # click the oscilloscope window to open it oscilloscope_menu = omni.kit.ui_test.get_menubar().find_menu("Oscilloscope") self.assertIsNotNone(oscilloscope_menu) await oscilloscope_menu.click() self._win = omni.kit.ui_test.find("Audio Oscilloscope") self.assertIsNotNone(self._win) self._record_button = self._win.find("**/Button[*]") self.assertIsNotNone(self._record_button) # After running each test async def tearDown(self): self._win = None await super().tearDown() async def _test_just_opened(self): await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_just_opened.png") async def _test_recording(self): # docking the window breaks the UI system entirely for some reason #await self._dock_window() await self._record_button.click() # the user hit the record button await asyncio.sleep(4.0) # wait for the bar to fill up await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_recording.png") await self._record_button.click() # the user hit stop await asyncio.sleep(0.25) # wait so the window will be updated await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_stopped.png") async def _test_real_audio(self): # Comment this out to run the test. # Since this test is timing dependent, it'll never work 100% and we don't # have any sort of smart comparison that could handle a shift in the image. # It works about 80% of the time. return context = omni.usd.get_context() self.assertIsNotNone(context) context.new_stage() stage = context.get_stage() self.assertIsNotNone(stage) audio = omni.usd.audio.get_stage_audio_interface() self.assertIsNotNone(audio) prim_path = "/test_sound" prim = stage.DefinePrim(prim_path, "OmniSound") self.assertIsNotNone(prim) prim.GetAttribute("filePath").Set(str(self._test_path / "1hz.oga")) prim.GetAttribute("auralMode").Set("nonSpatial") i = 0 while audio.get_sound_asset_status(prim) == omni.usd.audio.AssetLoadStatus.IN_PROGRESS: await asyncio.sleep(0.001) if i > 5000: raise Exception("asset load timed out") i += 1 await self._record_button.click() # the user hit the record button # use a voice to bypass the timeline voice = audio.spawn_voice(prim) i = 0 while voice.is_playing(): await asyncio.sleep(0.001) i += 1 if (i == 5000): self.assertFalse("test timed out") await self._dock_window() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_real_audio.png") # tests need to be run sequentially, so we can only have 1 test function in this module async def test_all(self): await self._test_just_opened() await self._test_recording() await self._test_real_audio()
4,929
Python
34.724637
109
0.653479
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/window/audio/oscilloscope/tests/__init__.py
from .test_window_audio_oscilloscope import * # pragma: no cover
66
Python
32.499984
65
0.757576
omniverse-code/kit/exts/omni.kit.window.audio.oscilloscope/omni/kit/audio/oscilloscope/__init__.py
from ._oscilloscope import *
29
Python
13.999993
28
0.758621
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_path.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import os import omni.kit.app import omni.usd import carb from omni.kit.test.teamcity import is_running_in_teamcity import sys import unittest from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper PERSISTENT_SETTINGS_PREFIX = "/persistent" class DragDropFileViewportPath(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await open_stage(get_test_data_path(__name__, "empty_stage.usda")) # After running each test async def tearDown(self): await wait_stage_loading() carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") async def test_l1_drag_drop_path_viewport_absolute(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute") usd_context = omni.usd.get_context() stage = usd_context.get_stage() viewport_window = ui_test.find("Viewport") await viewport_window.focus() # drag/drop from content browser to stage window async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "materials/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=viewport_window.center) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertTrue(os.path.isabs(asset.path)) async def test_l1_drag_drop_path_viewport_relative(self): carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative") usd_context = omni.usd.get_context() stage = usd_context.get_stage() viewport_window = ui_test.find("Viewport") await viewport_window.focus() # drag/drop from content browser to stage window async with ContentBrowserTestHelper() as content_browser_helper: mdl_path = get_test_data_path(__name__, "materials/badname.mdl") await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=viewport_window.center) # verify prims shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False) self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found") asset = shader.GetSourceAsset("mdl") self.assertFalse(os.path.isabs(asset.path)) @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_l1_drag_drop_hilighting(self): from pathlib import Path import omni.kit.test from omni.kit.viewport.utility.tests.capture import capture_viewport_and_compare from carb.input import MouseEventType from carb.tokens import get_tokens_interface await ui_test.find("Content").focus() viewport_window = ui_test.find("Viewport") await viewport_window.focus() await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__, "shapes").replace("\\", "/") await content_browser_helper.toggle_grid_view_async(False) selections = await content_browser_helper.select_items_async(usd_path, ["basic_cube.usda"]) self.assertIsNotNone(selections) widget = await content_browser_helper.get_treeview_item_async(selections[-1].name) self.assertIsNotNone(widget) start_pos = widget.center pos_0 = viewport_window.center pos_1 = ui_test.Vec2(50, pos_0.y + 75) pos_2 = ui_test.Vec2(viewport_window.size.x - 50, pos_0.y - 25) wait_delay = 4 drag_delay = 12 await ui_test.input.emulate_mouse(MouseEventType.MOVE, start_pos) await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN) await ui_test.human_delay(wait_delay) await ui_test.input.emulate_mouse_slow_move(start_pos, pos_0, human_delay_speed=drag_delay) await ui_test.human_delay(wait_delay) await ui_test.input.emulate_mouse_slow_move(pos_0, pos_1, human_delay_speed=drag_delay) await ui_test.human_delay(wait_delay) await ui_test.input.emulate_mouse_slow_move(pos_1, pos_2, human_delay_speed=drag_delay) await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP) await ui_test.human_delay(wait_delay) EXTENSION_ROOT = Path(get_tokens_interface().resolve("${omni.kit.test_suite.viewport}")).resolve().absolute() GOLDEN_IMAGES = EXTENSION_ROOT.joinpath("data", "tests", "images") OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) passed, fail_msg = await capture_viewport_and_compare(image_name="test_l1_drag_drop_hilighting.png", output_img_dir=OUTPUTS_DIR, golden_img_dir=GOLDEN_IMAGES) self.assertTrue(passed, msg=fail_msg)
6,013
Python
46.730158
119
0.673374
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/__init__.py
from .viewport_assign_material_single import * from .viewport_assign_material_multi import * from .select_bound_objects_viewport import * from .drag_drop_material_viewport import * from .drag_drop_usd_viewport_item import * from .viewport_setup import * from .drag_drop_path import * from .drag_drop_external_audio_viewport import *
333
Python
36.111107
48
0.786787
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/viewport_setup.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportSetup"] import omni.kit.test from omni.kit.test.async_unittest import AsyncTestCase import omni.usd import carb from pxr import UsdGeom class ViewportSetup(AsyncTestCase): # Before running each test async def setUp(self): super().setUp() async def test_camera_startup_values(self): usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 18.147562, places=5) self.assertEqual(persp.GetFStopAttr().Get(), 0) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) self.assertEqual(top.GetHorizontalApertureAttr().Get(), 5000) # Legacy Viewport does some legacy hi-jinks based on resolution # self.assertEqual(top.GetVerticalApertureAttr().Get(), 5000) # Test typed-defaults and creation settings = carb.settings.get_settings() try: perps_key = '/persistent/app/primCreation/typedDefaults/camera' ortho_key = '/persistent/app/primCreation/typedDefaults/orthoCamera' settings.set(perps_key + '/focalLength', 150) settings.set(perps_key + '/fStop', 22) settings.set(perps_key + '/horizontalAperture', 1234) settings.set(ortho_key + '/horizontalAperture', 1000) settings.set(ortho_key + '/verticalAperture', 2000) await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 150) self.assertAlmostEqual(persp.GetFStopAttr().Get(), 22) self.assertAlmostEqual(persp.GetHorizontalApertureAttr().Get(), 1234) # Legacy Viewport does some legacy hi-jinks based on resolution # self.assertFalse(persp.GetVerticalApertureAttr().IsAuthored()) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) # Legacy Viewport does some legacy hi-jinks based on resolution # self.assertAlmostEqual(top.GetHorizontalApertureAttr().Get(), 1000) # self.assertAlmostEqual(top.GetVerticalApertureAttr().Get(), 2000) finally: # Reset now for all other tests settings.destroy_item(perps_key) settings.destroy_item(ortho_key)
3,154
Python
40.513157
85
0.671528
omniverse-code/kit/exts/omni.kit.test_suite.viewport/omni/kit/test_suite/viewport/tests/drag_drop_usd_viewport_item.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import asyncio import os import carb import omni.usd import omni.kit.app from omni.kit.async_engine import run_coroutine import concurrent.futures from typing import List from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Tf, Usd, Sdf from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, wait_stage_loading, delete_prim_path_children, arrange_windows ) from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class DragDropUsdViewportItem(AsyncTestCase): # Before running each test async def setUp(self): carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") await arrange_windows("Stage", 512) await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) await delete_prim_path_children("/World") self._usd_path = get_test_data_path(__name__, "shapes").replace("\\", "/") # After running each test async def tearDown(self): await wait_stage_loading() carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference") def assertPathsEqual(self, path_a: str, path_b: str): # Make drive comparison case insensitive on Windows drive_a, path_a = os.path.splitdrive(path_a) drive_b, path_b = os.path.splitdrive(path_b) self.assertEqual(path_a, path_b) self.assertEqual(drive_a.lower(), drive_b.lower()) async def wait_for_import(self, stage, prim_paths, drag_drop_fn): # create future future_test = asyncio.Future() all_expected_prim_paths = set(prim_paths) def on_objects_changed(notice, sender, future_test): for p in notice.GetResyncedPaths(): if p.pathString in all_expected_prim_paths: all_expected_prim_paths.discard(p.pathString) if not all_expected_prim_paths: async def future_test_complete(future_test): await omni.kit.app.get_app().next_update_async() future_test.set_result(True) if not self._test_complete: self._test_complete = run_coroutine(future_test_complete(future_test)) break async def wait_for_event(future_test): await future_test # create listener self._test_complete = None listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, lambda n, s, : on_objects_changed(n, s, future_test), stage) # do drag/drop if asyncio.isfuture(drag_drop_fn()): await drag_drop_fn() else: concurrent.futures.wait(drag_drop_fn()) # wait for Tf.Notice event try: await asyncio.wait_for(wait_for_event(future_test), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_import timeout") # release listener listener.Revoke() def _verify(self, stage, prim_path, usd, reference): prim = stage.GetPrimAtPath(prim_path) self.assertIsNotNone(prim) payloads = omni.usd.get_composed_payloads_from_prim(prim) references = omni.usd.get_composed_references_from_prim(prim) if reference: items = references self.assertEqual(payloads, []) self.assertEqual(len(references), 1) else: items = payloads self.assertEqual(len(payloads), 1) self.assertEqual(references, []) for (ref, layer) in items: # unlike stage_window this ref.assetPath is not absoloute abs_path = get_test_data_path(__name__, f"{ref.assetPath}").replace("\\", "/") self.assertPathsEqual(abs_path, usd) async def _drag_drop_usd_items(self, usd_path: str, usd_names: List[str], reference: bool = False): await ui_test.find("Content").focus() viewport_window = ui_test.find("Viewport") await viewport_window.focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() await wait_stage_loading() # set dragDropImport import_method = "reference" if reference else "payload" carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", import_method) all_expected_prim_paths = [] for usd_name in usd_names: prim_name, _ = os.path.splitext(os.path.basename(usd_name)) all_expected_prim_paths.append(f"/World/{prim_name}") # drag/drop content_browser_helper = ContentBrowserTestHelper() await self.wait_for_import(stage, all_expected_prim_paths, lambda: run_coroutine(content_browser_helper.drag_and_drop_tree_view( usd_path, names=usd_names, drag_target=viewport_window.center )) ) await wait_stage_loading() # verify for usd_name, prim_path in zip(usd_names, all_expected_prim_paths): self._verify(stage, prim_path, f"{usd_path}/{usd_name}", reference) async def test_l1_drag_drop_usd_stage_item_reference(self): await self._drag_drop_usd_items(self._usd_path, ["basic_sphere.usda"], reference=True) async def test_l1_drag_drop_usd_viewport_item_payload(self): await self._drag_drop_usd_items(self._usd_path, ["basic_cone.usda"], reference=False) async def test_l1_drag_drop_multiple_usd_stage_items_reference(self): usd_names = ["basic_cube.usda", "basic_cone.usda", "basic_sphere.usda"] await self._drag_drop_usd_items(self._usd_path, usd_names, reference=True) async def test_l1_drag_drop_multiple_usd_viewport_items_payload(self): usd_names = ["basic_cube.usda", "basic_cone.usda", "basic_sphere.usda"] await self._drag_drop_usd_items(self._usd_path, usd_names, reference=False)
6,423
Python
39.658228
125
0.640822
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.7] - 2022-09-21 ### Added - Test for drag drop usd file across mulitple objects in Viewport ## [1.0.6] - 2022-08-03 ### Changes - Added external drag/drop audio file tests ## [1.0.5] - 2022-07-25 ### Changes - Refactored unittests to make use of content_browser test helpers ## [1.0.4] - 2022-06-14 ### Added - Fixed drag/drop test for viewport next ## [1.0.3] - 2022-06-09 ### Added - Test new default startup values ## [1.0.2] - 2022-06-04 ### Changes - Make path comparisons case insensitive for Windows drive - Remove extra timeout for tests not running with RTX ## [1.0.1] - 2022-05-23 ### Changes - Add missing explicit dependencies ## [1.0.0] - 2022-02-09 ### Changes - Created
796
Markdown
20.54054
80
0.674623
omniverse-code/kit/exts/omni.kit.test_suite.viewport/docs/index.rst
omni.kit.test_suite.viewport ############################ viewport tests .. toctree:: :maxdepth: 1 CHANGELOG
118
reStructuredText
10.899999
28
0.525424
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/capture.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.kit.app import asyncio from typing import Any, Callable, Sequence class Capture: '''Base capture delegate''' def __init__(self, *args, **kwargs): self.__future = asyncio.Future() def capture(self, aov_map, frame_info, hydra_texture, result_handle): carb.log_error(f'Capture used, but capture was not overriden') async def wait_for_result(self, completion_frames: int = 2): await self.__future while completion_frames: await omni.kit.app.get_app().next_update_async() completion_frames = completion_frames - 1 return self.__future.result() def _set_completed(self, value: Any = True): if not self.__future.done(): self.__future.set_result(value) class RenderCapture(Capture): '''Viewport capturing delegate that iterates over multiple aovs and calls user defined capture_aov method for all of interest''' def __init__(self, aov_names: Sequence[str], per_aov_data: Sequence[Any] = None, *args, **kwargs): super().__init__(*args, **kwargs) # Accept a 1:1 mapping a 1:0 mapping or a N:1 mapping of AOV to data if per_aov_data is None: self.__aov_mapping = {aov:None for aov in aov_names} elif len(aov_names) == len(per_aov_data): self.__aov_mapping = {aov:data for aov, data in zip(aov_names, per_aov_data)} else: if len(per_aov_data) != 1: assert len(aov_names) == len(per_aov_data), f'Mismatch between {len(aov_names)} aovs and {len(per_aov_data)} per_aov_data' self.__aov_mapping = {aov:per_aov_data for aov in aov_names} self.__frame_info = None self.__hydra_texture = None self.__result_handle = None self.__render_capture = None @property def aov_data(self): return self.__aov_mapping.values() @property def aov_names(self): return self.__aov_mapping.keys() @property def resolution(self): return self.__frame_info.get('resolution') @property def view(self): return self.__frame_info.get('view') @property def projection(self): return self.__frame_info.get('projection') @property def frame_number(self): return self.__frame_info.get('frame_number') @property def viewport_handle(self): return self.__frame_info.get('viewport_handle') @property def hydra_texture(self): return self.__hydra_texture @property def result_handle(self): return self.__result_handle @property def frame_info(self): return self.__frame_info @property def render_capture(self): if not self.__render_capture: try: import omni.renderer_capture self.__render_capture = omni.renderer_capture.acquire_renderer_capture_interface() except ImportError: carb.log_error(f'omni.renderer_capture extension must be loaded to use this interface') raise return self.__render_capture def capture(self, aov_map, frame_info, hydra_texture, result_handle): try: self.__hydra_texture = hydra_texture self.__result_handle = result_handle self.__frame_info = frame_info color_data, color_data_set = None, False completed = [] for aov_name, user_data in self.__aov_mapping.items(): aov_data = aov_map.get(aov_name) if aov_data: self.capture_aov(user_data, aov_data) completed.append(aov_name) elif aov_name == '': color_data, color_data_set = user_data, True if color_data_set: aov_name = 'LdrColor' aov_data = aov_map.get(aov_name) if aov_data is None: aov_name = 'HdrColor' aov_data = aov_map.get(aov_name) if aov_data: self.capture_aov(color_data, aov_data) completed.append(aov_name) except: raise finally: self.__hydra_texture = None self.__result_handle = None self.__render_capture = None self._set_completed(completed) def capture_aov(self, user_data, aov: dict): carb.log_error('RenderCapture used, but capture_aov was not overriden') def save_aov_to_file(self, file_path: str, aov: dict, format_desc: dict = None): if format_desc: if hasattr(self.render_capture, 'capture_next_frame_rp_resource_to_file'): self.render_capture.capture_next_frame_rp_resource_to_file(file_path, aov['texture']['rp_resource'], format_desc=format_desc, metadata = self.__frame_info.get('metadata')) return carb.log_error('Format description provided to capture, but not honored') self.render_capture.capture_next_frame_rp_resource(file_path, aov['texture']['rp_resource'], metadata = self.__frame_info.get('metadata')) def deliver_aov_buffer(self, callback_fn: Callable, aov: dict): self.render_capture.capture_next_frame_rp_resource_callback(callback_fn, aov['texture']['rp_resource'], metadata = self.__frame_info.get('metadata')) def save_product_to_file(self, file_path: str, render_product: str): self.render_capture.capture_next_frame_using_render_product(self.viewport_handle, file_path, render_product) class MultiAOVFileCapture(RenderCapture): '''Class to capture multiple AOVs into multiple files''' def __init__(self, aov_names: Sequence[str], file_paths: Sequence[str], format_desc: dict = None, *args, **kwargs): super().__init__(aov_names, file_paths, *args, **kwargs) self.__format_desc = format_desc @property def format_desc(self): return self.__format_desc @format_desc.setter def format_desc(self, value: dict): self.__format_desc = value def capture_aov(self, file_path: str, aov: dict, format_desc: dict = None): self.save_aov_to_file(file_path, aov, self.__format_desc) class MultiAOVByteCapture(RenderCapture): '''Class to deliver multiple AOVs buffer/bytes to a callback function''' def __init__(self, aov_names: Sequence[str], callback_fns: Sequence[Callable] = None, *args, **kwargs): super().__init__(aov_names, callback_fns, *args, **kwargs) def capture_aov(self, callback_fn: Callable, aov: dict): self.deliver_aov_buffer(callback_fn or self.on_capture_completed, aov) def on_capture_completed(buffer, buffer_size, width, height, format): pass class FileCapture(MultiAOVFileCapture): '''Class to capture a single AOVs (defaulting to color) into one file''' def __init__(self, file_path: str, aov_name: str = '', *args, **kwargs): super().__init__([aov_name], [file_path], *args, **kwargs) class ByteCapture(MultiAOVByteCapture): '''Class to capture a single AOVs (defaulting to color) to a user callback''' def __init__(self, callback_fn: Callable = None, aov_name: str = '', *args, **kwargs): super().__init__([aov_name], [callback_fn], *args, **kwargs)
7,872
Python
38.365
157
0.609756
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/extension.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportWidgetExtension'] import omni.ext class ViewportWidgetExtension(omni.ext.IExt): def on_startup(self): pass def on_shutdown(self): from .widget import ViewportWidget from .impl.utility import _report_error for instance in ViewportWidget.get_instances(): # pragma: no cover try: instance.destroy() except Exception: _report_error()
884
Python
33.03846
76
0.704751
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/__init__.py
from .extension import ViewportWidgetExtension # Expose our public classes for from omni.kit.widget.viewport import ViewportWidget __all__ = ['ViewportWidget'] from .widget import ViewportWidget
197
Python
27.28571
83
0.807107
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/api.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportAPI'] import omni.usd import carb from .impl.utility import _report_error from .capture import Capture from pxr import Usd, UsdGeom, Sdf, Gf, CameraUtil from typing import Callable, Optional, Sequence, Tuple, Union import weakref import asyncio class ViewportAPI(): class __ViewportSubscription: def __init__(self, fn: Callable, callback_container: set): self.__callback_container = callback_container self.__callback = fn self.__callback_container.add(self.__callback) def destroy(self): if not self.__callback_container: return # Clear out self of references early, and then operate on the re-scoped objects scoped_container = self.__callback_container scoped_callback = self.__callback self.__callback_container, self.__callback = None, None try: scoped_container.remove(scoped_callback) except KeyError: # pragma: no cover pass def __del__(self): self.destroy() def __init__(self, usd_context_name: str, viewport_id: str, viewport_changed_fn: Optional[Callable]): self.__usd_context_name = usd_context_name self.__viewport_id = viewport_id self.__viewport_changed = viewport_changed_fn self.__viewport_texture, self.__hydra_texture = None, None self.__aspect_ratios = (1, 1) self.__projection = Gf.Matrix4d(1) self.__flat_rendered_projection = self.__flatten_matrix(self.__projection) self.__transform = Gf.Matrix4d(1) self.__view = Gf.Matrix4d(1) self.__ndc_to_world = None self.__world_to_ndc = None self.__time = Usd.TimeCode.Default() self.__view_changed = set() self.__frame_changed = set() self.__render_settings_changed = set() self.__fill_frame = False self.__lock_to_render_result = True self.__first_synch = True self.__updates_enabled = True self.__freeze_frame = False self.__scene_views = [] # Attribute to store the requirement status of the scene camera model. # We initialize it to None and will only fetch the status when needed. self.__requires_scene_camera_model = None # Attribute to flag whether importing the SceneCameraModel failed or not. # We use this to avoid continuously trying to import an unavailable or failing module. self.__scene_camera_model_import_failed = False # This stores the instance of SceneCameraModel if it's required and successfully imported. # We initialize it to None as we don't need it immediately at initialization time. self.__scene_camera_model = None settings = carb.settings.get_settings() self.__accelerate_rtx_picking = bool(settings.get("/exts/omni.kit.widget.viewport/picking/rtx/accelerate")) self.__accelerate_rtx_picking_sub = settings.subscribe_to_node_change_events( "/exts/omni.kit.widget.viewport/picking/rtx/accelerate", self.__accelerate_rtx_changed ) def __del__(self): sub, self.__accelerate_rtx_picking_sub = self.__accelerate_rtx_picking_sub, None if sub: settings = carb.settings.get_settings() settings.unsubscribe_to_change_events(sub) def add_scene_view(self, scene_view): '''Add an omni.ui.scene.SceneView to push view and projection changes to. The provided scene_view will be saved as a weak-ref.''' if not scene_view: # pragma: no cover raise RuntimeError('Provided scene_view is invalid') self.__clean_weak_views() self.__scene_views.append(weakref.ref(scene_view, self.__clean_weak_views)) _scene_camera_model = self._scene_camera_model if _scene_camera_model: scene_view.model = _scene_camera_model # Sync the model immediately model = scene_view.model model.set_floats('view', self.__flatten_matrix(self.__view)) model.set_floats('projection', self.__flatten_matrix(self.__projection)) def remove_scene_view(self, scene_view): '''Remove an omni.ui.scene.SceneView that was receiving view and projection changes.''' if not scene_view: raise RuntimeError('Provided scene_view is invalid') for sv in self.__scene_views: if sv() == scene_view: self.__scene_views.remove(sv) break self.__clean_weak_views() def subscribe_to_view_change(self, callback: Callable): return self.__subscribe_to_change(callback, self.__view_changed, 'subscribe_to_view_change') def subscribe_to_frame_change(self, callback: Callable): return self.__subscribe_to_change(callback, self.__frame_changed, 'subscribe_to_frame_change') def subscribe_to_render_settings_change(self, callback: Callable): return self.__subscribe_to_change(callback, self.__render_settings_changed, 'subscribe_to_render_settings_change') def request_pick(self, *args, **kwargs): return self.__hydra_texture.request_pick(*args, **kwargs) if self.__hydra_texture else None def request_query(self, mouse, *args, **kwargs): if self.__accelerate_rtx_picking and kwargs.get("view") is None: # If using scene_camera_model, pull view and projection from that and # avoid the flattening stage as well. if False: # self.__scene_camera_model: kwargs["view"] = self.__scene_camera_model.view kwargs["projection"] = self.__scene_camera_model.projection else: kwargs["view"] = self.__flatten_matrix(self.__view) kwargs["projection"] = self.__flat_rendered_projection return self.__hydra_texture.request_query(mouse, *args, **kwargs) if self.__hydra_texture else None def schedule_capture(self, delegate: Capture) -> Capture: if self.__viewport_texture: return self.__viewport_texture.schedule_capture(delegate) async def wait_for_render_settings_change(self): future = asyncio.Future() def rs_changed(*args): nonlocal scoped_sub scoped_sub = None if not future.done(): future.set_result(True) scoped_sub = self.subscribe_to_render_settings_change(rs_changed) return await future async def wait_for_rendered_frames(self, additional_frames: int = 0): future = asyncio.Future() def frame_changed(*args): nonlocal additional_frames, scoped_sub additional_frames = additional_frames - 1 if (additional_frames <= 0) and (not future.done()): future.set_result(True) scoped_sub = None scoped_sub = self.subscribe_to_frame_change(frame_changed) return await future # Deprecated def pick(self, *args, **kwargs): # pragma: no cover carb.log_warn('ViewportAPI.pick is deprecated, use request_pick') return self.__hydra_texture.pick(*args, **kwargs) if self.__hydra_texture else None def query(self, mouse, *args, **kwargs): # pragma: no cover carb.log_warn('ViewportAPI.query is deprecated, use request_query') return self.__hydra_texture.query(mouse, *args, **kwargs) if self.__hydra_texture else None def set_updates_enabled(self, enabled: bool = True): # pragma: no cover carb.log_warn('ViewportAPI.set_updates_enabled is deprecated, use updates_enabled') self.updates_enabled = enabled @property def hydra_engine(self): '''Get the name of the active omni.hydra.engine for this Viewport''' return self.__viewport_texture.hydra_engine if self.__viewport_texture else None @hydra_engine.setter def hydra_engine(self, hd_engine: str): '''Set the name of the active omni.hydra.engine for this Viewport''' if self.__viewport_texture: self.__viewport_texture.hydra_engine = hd_engine @property def render_mode(self): '''Get the render-mode for the active omni.hydra.engine used in this Viewport''' return self.__viewport_texture.render_mode if self.__viewport_texture else None @render_mode.setter def render_mode(self, render_mode: str): '''Set the render-mode for the active omni.hydra.engine used in this Viewport''' if self.__viewport_texture: self.__viewport_texture.render_mode = render_mode @property def set_hd_engine(self): '''Set the active omni.hydra.engine for this Viewport, and optionally its render-mode''' return self.__viewport_texture.set_hd_engine if self.__viewport_texture else None @property def camera_path(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' return self.__viewport_texture.camera_path if self.__viewport_texture else None @camera_path.setter def camera_path(self, camera_path: Union[Sdf.Path, str]): '''Set the active rendering camera from an Sdf.Path''' if self.__viewport_texture: self.__viewport_texture.camera_path = camera_path @property def resolution(self) -> Tuple[float, float]: '''Return a tuple of (resolution_x, resolution_y) this Viewport is rendering at, accounting for scale.''' return self.__viewport_texture.resolution if self.__viewport_texture else None @resolution.setter def resolution(self, value: Tuple[float, float]): '''Set the resolution to render with (resolution_x, resolution_y). The provided resolution should be full resolution, as any texture scaling will be applied to it.''' if self.__viewport_texture: self.__viewport_texture.resolution = value @property def resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' return self.__viewport_texture.resolution_scale if self.__viewport_texture else None @resolution_scale.setter def resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' if self.__viewport_texture: self.__viewport_texture.resolution_scale = value @property def full_resolution(self) -> Tuple[float, float]: '''Return a tuple of the full (full_resolution_x, full_resolution_y) this Viewport is rendering at, not accounting for scale.''' return self.__viewport_texture.full_resolution if self.__viewport_texture else None @property def render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' if self.__hydra_texture: render_product = self.__hydra_texture.get_render_product_path() if render_product and (not render_product.startswith('/')): render_product = '/Render/RenderProduct_' + render_product return render_product @render_product_path.setter def render_product_path(self, prim_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' if self.__hydra_texture: prim_path = str(prim_path) name = self.__hydra_texture.get_name() if prim_path == f'/Render/RenderProduct_{name}': prim_path = name return self.__hydra_texture.set_render_product_path(prim_path) @property def fps(self) -> float: '''Return the frames-per-second this Viewport is running at''' return self.frame_info.get('fps', 0) @property def frame_info(self) -> dict: return self.__viewport_texture.frame_info if self.__viewport_texture else {} @property def fill_frame(self) -> bool: return self.__fill_frame @fill_frame.setter def fill_frame(self, value: bool): value = bool(value) if self.__fill_frame != value: self.__fill_frame = value stage = self.stage if stage: self.viewport_changed(self.camera_path, stage) @property def lock_to_render_result(self) -> bool: return self.__lock_to_render_result @lock_to_render_result.setter def lock_to_render_result(self, value: bool): value = bool(value) if self.__lock_to_render_result != value: self.__lock_to_render_result = value if self.__viewport_texture: self.__viewport_texture._render_settings_changed() @property def freeze_frame(self) -> bool: return self.__freeze_frame @freeze_frame.setter def freeze_frame(self, value: bool): self.__freeze_frame = bool(value) @property def updates_enabled(self) -> bool: return self.__updates_enabled @updates_enabled.setter def updates_enabled(self, value: bool): value = bool(value) if self.__updates_enabled != value: self.__updates_enabled = value if self.__hydra_texture: self.__hydra_texture.set_updates_enabled(value) @property def viewport_changed(self): return self.__viewport_changed if self.__viewport_changed else lambda c, s: None @property def id(self) -> str: return self.__viewport_id @property def usd_context_name(self) -> str: '''Return the name of the omni.usd.UsdContext this Viewport is attached to''' return self.__usd_context_name @property def usd_context(self): '''Return the omni.usd.UsdContext this Viewport is attached to''' return omni.usd.get_context(self.__usd_context_name) @property def stage(self) -> Usd.Stage: '''Return the Usd.Stage of the omni.usd.UsdContext this Viewport is attached to''' return self.usd_context.get_stage() @property def projection(self) -> Gf.Matrix4d: '''Return the projection of the UsdCamera in terms of the ui element it sits in.''' return Gf.Matrix4d(self.__projection) @property def transform(self) -> Gf.Matrix4d: '''Return the world-space transform of the UsdGeom.Camera being used to render''' return Gf.Matrix4d(self.__transform) @property def view(self) -> Gf.Matrix4d: '''Return the inverse of the world-space transform of the UsdGeom.Camera being used to render''' return Gf.Matrix4d(self.__view) @property def time(self) -> Usd.TimeCode: '''Return the Usd.TimeCode this Viewport is using''' return self.__time @property def world_to_ndc(self) -> Gf.Matrix4d: if not self.__world_to_ndc: self.__world_to_ndc = self.view * self.projection return Gf.Matrix4d(self.__world_to_ndc) @property def ndc_to_world(self) -> Gf.Matrix4d: if not self.__ndc_to_world: self.__ndc_to_world = self.world_to_ndc.GetInverse() return Gf.Matrix4d(self.__ndc_to_world) @property def _scene_camera_model(self) -> "SceneCameraModel": """ This property fetches and returns the instance of SceneCameraModel. If the instance has not been fetched before, it fetches and stores it. If the instance was fetched previously, it retrieves it from the cache. Returns: Instance of SceneCameraModel, or None if it fails to fetch or not required. """ if self.__scene_camera_model is None: self.__scene_camera_model = self.__create_scene_camera_model() return self.__scene_camera_model def __create_scene_camera_model(self) -> "SceneCameraModel": """ Creates SceneCameraModel based on the requirement from app settings. If a scene camera model is required, it imports and initializes the SceneCameraModel. Returns: Instance of SceneCameraModel if required and successfully imported, else None. """ if self.__is_requires_scene_camera_model() and not self.__scene_camera_model_import_failed: # Determine viewport handle by checking if __viewport_texture exists # and has a viewport_handle attribute. if not self.__viewport_texture or not self.__viewport_texture.viewport_handle: viewport_handle = -1 else: viewport_handle = self.__viewport_texture.viewport_handle try: from omni.kit.viewport.scene_camera_model import SceneCameraModel return SceneCameraModel(self.usd_context_name, viewport_handle) except ImportError: # pragma: no cover carb.log_error("omni.kit.viewport.scene_camera_model must be enabled for singleCameraModel") self.__scene_camera_model_import_failed = True return None def __is_requires_scene_camera_model(self) -> bool: """ Determines if the SceneCameraModel is required based on app settings. If the setting has not been checked before, it fetches from the app settings and stores the boolean value. Returns: Boolean indicating whether or not the SceneCameraModel is required. """ if self.__requires_scene_camera_model is None: settings = carb.settings.acquire_settings_interface() self.__requires_scene_camera_model = bool( settings.get("/ext/omni.kit.widget.viewport/sceneView/singleCameraModel/enabled") ) return self.__requires_scene_camera_model def map_ndc_to_texture(self, mouse: Sequence[float]) -> Tuple[Tuple[float, float], 'ViewportAPI']: ratios = self.__aspect_ratios # Move into viewport's NDC-space: [-1, 1] bound by viewport mouse = (mouse[0] / ratios[0], mouse[1] / ratios[1]) # Move from NDC space to texture-space [-1, 1] to [0, 1] def check_bounds(coord): return coord >= -1 and coord <= 1 return tuple((x + 1.0) * 0.5 for x in mouse), self if (check_bounds(mouse[0]) and check_bounds(mouse[1])) else None def map_ndc_to_texture_pixel(self, mouse: Sequence[float]) -> Tuple[Tuple[float, float], 'ViewportAPI']: # Move into viewport's uv-space: [0, 1] mouse, viewport = self.map_ndc_to_texture(mouse) # Then scale by resolution flipping-y resolution = self.resolution return (int(mouse[0] * resolution[0]), int((1.0 - mouse[1]) * resolution[1])), viewport def __get_conform_policy(self): ''' TODO: Need python exposure via UsdContext or HydraTexture import carb conform_setting = carb.settings.get_settings().get("/app/hydra/aperture/conform") if (conform_setting is None) or (conform_setting == 1) or (conform_setting == 'horizontal'): return CameraUtil.MatchHorizontally if (conform_setting == 0) or (conform_setting == 'vertical'): return CameraUtil.MatchVertically if (conform_setting == 2) or (conform_setting == 'fit'): return CameraUtil.Fit if (conform_setting == 3) or (conform_setting == 'crop'): return CameraUtil.Crop if (conform_setting == 4) or (conform_setting == 'stretch'): return CameraUtil.DontConform ''' return CameraUtil.MatchHorizontally def _conform_projection(self, policy, camera: UsdGeom.Camera, image_aspect: float, canvas_aspect: float, projection: Sequence[float] = None): '''For the given camera (or possible incoming projection) return a projection matrix that matches the rendered image but keeps NDC co-ordinates for the texture bound to [-1, 1]''' if projection is None: # If no projection is provided, conform the camera based on settings # This wil adjust apertures on the gf_camera gf_camera = camera.GetCamera(self.__time) if policy == CameraUtil.DontConform: # For DontConform, still have to conform for the final canvas if image_aspect < canvas_aspect: gf_camera.horizontalAperture = gf_camera.horizontalAperture * (canvas_aspect / image_aspect) else: gf_camera.verticalAperture = gf_camera.verticalAperture * (image_aspect / canvas_aspect) else: CameraUtil.ConformWindow(gf_camera, policy, image_aspect) projection = gf_camera.frustum.ComputeProjectionMatrix() self.__flat_rendered_projection = self.__flatten_matrix(projection) else: self.__flat_rendered_projection = projection projection = Gf.Matrix4d(*projection) # projection now has the rendered image projection # Conform again based on canvas size so projection extends with the Viewport sits in the UI if image_aspect < canvas_aspect: self.__aspect_ratios = (image_aspect / canvas_aspect, 1) policy2 = CameraUtil.MatchVertically else: self.__aspect_ratios = (1, canvas_aspect / image_aspect) policy2 = CameraUtil.MatchHorizontally if policy != CameraUtil.DontConform: projection = CameraUtil.ConformedWindow(projection, policy2, canvas_aspect) return projection def _sync_viewport_api(self, camera: UsdGeom.Camera, canvas_size: Sequence[int], time: Usd.TimeCode = Usd.TimeCode.Default(), view: Sequence[float] = None, projection: Sequence[float] = None, force_update: bool = False): '''Sync the ui and viewport state, and inform any view-scubscribers if a change occured''' # Early exit if the Viewport is locked to a rendered image, not updates to SceneViews or internal state if not self.__updates_enabled or self.__freeze_frame: return # Store the current time if time: self.__time = time # When locking to render, allow one update to push initial USD state into Viewport # Otherwise, if locking to render results and no View provided, wait for next frame to deliver it. if self.__first_synch: self.__first_synch = False elif not force_update and (self.__lock_to_render_result and not view): return # If forcing UI resolution to match Viewport, set the resolution now if it needs to be updated. # Early exit in this case as it will trigger a subsequent UI -> Viewport sync. resolution = self.full_resolution canvas_size = (int(canvas_size[0]), int(canvas_size[1])) # We want to be careful not to resize to 0, 0 in the case the canvas is 0, 0 if self.__fill_frame and (canvas_size[0] and canvas_size[1]): if (resolution[0] != canvas_size[0]) or (resolution[1] != canvas_size[1]): self.resolution = canvas_size return prev_xform, prev_proj = self.__transform, self.__projection if view: self.__view = Gf.Matrix4d(*view) self.__transform = self.__view.GetInverse() else: self.__transform = camera.ComputeLocalToWorldTransform(self.__time) self.__view = self.__transform.GetInverse() image_aspect = resolution[0] / resolution[1] if resolution[1] else 1 canvas_aspect = canvas_size[0] / canvas_size[1] if canvas_size[1] else 1 policy = self.__get_conform_policy() self.__projection = self._conform_projection(policy, camera, image_aspect, canvas_aspect, projection) view_changed = self.__transform != prev_xform proj_changed = self.__projection != prev_proj if view_changed or proj_changed: self.__ndc_to_world = None self.__world_to_ndc = None self.__notify_scene_views(view_changed, proj_changed) self.__notify_objects(self.__view_changed) return True # Legacy methods that we also support def get_active_camera(self) -> Sdf.Path: '''Return an Sdf.Path to the active rendering camera''' return self.camera_path def set_active_camera(self, camera_path: Sdf.Path): '''Set the active rendering camera from an Sdf.Path''' self.camera_path = camera_path def get_render_product_path(self) -> str: '''Return a string to the UsdRender.Product used by the Viewport''' return self.render_product_path def set_render_product_path(self, product_path: str): '''Set the UsdRender.Product used by the Viewport with a string''' self.render_product_path = product_path def get_texture_resolution(self) -> Tuple[float, float]: '''Return a tuple of (resolution_x, resolution_y)''' return self.resolution def set_texture_resolution(self, value: Tuple[float, float]): '''Set the resolution to render with (resolution_x, resolution_y)''' self.resolution = value def get_texture_resolution_scale(self) -> float: '''Get the scaling factor for the Viewport's render resolution.''' return self.resolution_scale def set_texture_resolution_scale(self, value: float): '''Set the scaling factor for the Viewport's render resolution.''' self.resolution_scale = value def get_full_texture_resolution(self) -> Tuple[float, float]: '''Return a tuple of (full_resolution_x, full_resolution_y)''' return self.full_resolution # Semi Private access, do not assume these will always be available by guarding usage and access. @property def display_render_var(self) -> str: if self.__viewport_texture: return self.__viewport_texture.display_render_var @display_render_var.setter def display_render_var(self, name: str): if self.__viewport_texture: self.__viewport_texture.display_render_var = str(name) @property def _settings_path(self) -> str: return self.__hydra_texture.get_settings_path() if self.__hydra_texture else None @property def _hydra_texture(self): return self.__hydra_texture @property def _viewport_texture(self): return self.__viewport_texture def _notify_frame_change(self): self.__notify_objects(self.__frame_changed) def _notify_render_settings_change(self): self.__notify_objects(self.__render_settings_changed) # Very Private methods def __set_hydra_texture(self, viewport_texture, hydra_texture): # Transfer any local state this instance is carying if hydra_texture: hydra_texture.set_updates_enabled(self.__updates_enabled) _scene_camera_model = self._scene_camera_model if _scene_camera_model: if not viewport_texture or not viewport_texture.viewport_handle: _scene_camera_model.set_viewport_handle(-1) else: _scene_camera_model.set_viewport_handle(viewport_texture.viewport_handle) # Replace the references this instance has self.__viewport_texture = viewport_texture self.__hydra_texture = hydra_texture def __callback_args(self, fn_container: Sequence): # Send a proxy so nobody can retain the instance directly vp_api = weakref.proxy(self) if id(fn_container) == id(self.__render_settings_changed): return (self.camera_path, self.resolution, vp_api) return (vp_api,) def __subscribe_to_change(self, callback: Callable, container: set, name: str): if not callable(callback): raise ValueError(f'ViewportAPI {name} requires a callable object') # If we're in a valid state, invoke the callback now. # If it throws we leave it up to the caller to figure out why and re-subscribe if self.__viewport_texture and self.__hydra_texture: callback(*self.__callback_args(container)) return ViewportAPI.__ViewportSubscription(callback, container) def __notify_objects(self, fn_container: Sequence): if fn_container: args = self.__callback_args(fn_container) for fn in fn_container.copy(): try: fn(*args) except Exception: # pragma: no cover _report_error() def __notify_scene_views(self, view: bool, proj: bool): if not self.__scene_views: return # Since these are weak-refs, prune any objects that may have gone out of date active_views = [] # Flatten these once for the loop below if view: view = [self.__view[0][0], self.__view[0][1], self.__view[0][2], self.__view[0][3], self.__view[1][0], self.__view[1][1], self.__view[1][2], self.__view[1][3], self.__view[2][0], self.__view[2][1], self.__view[2][2], self.__view[2][3], self.__view[3][0], self.__view[3][1], self.__view[3][2], self.__view[3][3]] if proj: proj = [self.__projection[0][0], self.__projection[0][1], self.__projection[0][2], self.__projection[0][3], self.__projection[1][0], self.__projection[1][1], self.__projection[1][2], self.__projection[1][3], self.__projection[2][0], self.__projection[2][1], self.__projection[2][2], self.__projection[2][3], self.__projection[3][0], self.__projection[3][1], self.__projection[3][2], self.__projection[3][3]] for sv_ref in self.__scene_views: scene_view = sv_ref() if scene_view: active_views.append(sv_ref) try: sv_model = scene_view.model view_item, proj_item = None, None _scene_camera_model = self._scene_camera_model if _scene_camera_model is None and view: view_item = sv_model.get_item('view') sv_model.set_floats(view_item, view) if proj: proj_item = sv_model.get_item('projection') sv_model.set_floats(proj_item, proj) # Update both or just a single item sv_model._item_changed(None if (view_item and proj_item) else (view_item or proj_item)) except Exception: # pragma: no cover _report_error() self.__scene_views = active_views def __clean_weak_views(self, *args): self.__scene_views = [sv for sv in self.__scene_views if sv()] def __accelerate_rtx_changed(self, *args, **kwargs): settings = carb.settings.get_settings() self.__accelerate_rtx_picking = bool(settings.get("/exts/omni.kit.widget.viewport/picking/rtx/accelerate")) @staticmethod def __flatten_matrix(m): # Pull individual Gf.Vec4 for each row, then index each component of those individually. m0, m1, m2, m3 = m[0], m[1], m[2], m[3] return [m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3]]
31,558
Python
43.701133
419
0.627575
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/display_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportDisplayDelegate'] import omni.ui as ui class ViewportDisplayDelegate: def __init__(self, viewport_api): self.__zstack = None self.__image_provider = None self.__image = None def __del__(self): self.destroy() def destroy(self): if self.__zstack: self.__zstack.clear() self.__zstack.destroy() self.__zstack = None if self.__image: self.__image.destroy() self.__image = None if self.__image_provider: self.__image_provider = None @property def image_provider(self): return self.__image_provider @image_provider.setter def image_provider(self, image_provider: ui.ImageProvider): if not isinstance(image_provider, ui.ImageProvider): raise RuntimeError('ViewportDisplayDelegate.image_provider must be an omni.ui.ImageProvider') # Clear any existing ui.ImageWithProvider # XXX: ui.ImageWithProvider should have a method to swap this out if self.__image: self.__image.destroy() self.__image = None self.__image_provider = image_provider self.__image = ui.ImageWithProvider(self.__image_provider, style_type_name_override='ViewportImage', name='Color') def create(self, ui_frame, prev_delegate, *args, **kwargs): # Save the previous ImageProvider early to keep it alive image_provider = prev_delegate.image_provider if prev_delegate else None self.destroy() with ui_frame: self.__zstack = ui.ZStack() with self.__zstack: if not image_provider: image_provider = ui.ImageProvider(name='ViewportImageProvider') self.image_provider = image_provider return self.__zstack def update(self, viewport_api, texture, view, projection, presentation_key=None): self.__image_provider.set_image_data(texture, presentation_key=presentation_key) return self.size @property def size(self): return (int(self.__image.computed_width), int(self.__image.computed_height)) class OverlayViewportDisplayDelegate(ViewportDisplayDelegate): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__overlay_image = None self.__overlay_provider = None def __del__(self): self.destroy() def destroy(self): if self.__overlay_image: self.__overlay_image.destroy() self.__overlay_image = None if self.__overlay_provider: self.__overlay_provider = None super().destroy() def create(self, ui_frame, prev_delegate, *args, **kwargs): # Grab the last image and put to push as the last element in the parent ui.Stack prev_provider = prev_delegate.image_provider if prev_delegate else None # Build the default ui for the Viewports display, but don't pass along any previous delegate/image ui_stack = super().create(ui_frame, None, *args, **kwargs) if ui_stack and prev_provider: with ui_stack: self.__overlay_provider = prev_provider self.__overlay_image = ui.ImageWithProvider(self.__overlay_provider, style_type_name_override='ViewportImageOverlay', name='Overlay') return ui_stack def set_overlay_alpha(self, overlay_alpha: float): self.__overlay_image.set_style({ 'ViewportImageOverlay': { 'color': ui.color(1.0, 1.0, 1.0, overlay_alpha) } })
4,262
Python
36.725663
108
0.600657
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/widget.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['ViewportWidget'] from .api import ViewportAPI from .impl.texture import ViewportTexture from .impl.utility import init_settings, save_implicit_cameras, StageAxis from .display_delegate import ViewportDisplayDelegate from omni.kit.async_engine import run_coroutine import omni.ui as ui import omni.usd import carb.events import carb.settings from pxr import Usd, UsdGeom, Sdf, Tf from typing import Optional, Tuple, Union import weakref import asyncio import concurrent.futures class ViewportWidget: """The Viewport Widget Simplest implementation of a viewport which you must control 100% """ __g_instances = [] @classmethod def get_instances(cls): for inst in cls.__g_instances: yield inst @classmethod def __clean_instances(cls, dead, self=None): active = [] for p in ViewportWidget.__g_instances: try: if p and p != self: active.append(p) except ReferenceError: pass ViewportWidget.__g_instances = active @property def viewport_api(self): return self.__proxy_api @property def name(self): return self.__ui_frame.name @property def visible(self): return self.__ui_frame.visible @visible.setter def visible(self, value): self.__ui_frame.visible = bool(value) def __init__(self, usd_context_name: str = '', camera_path: Optional[str] = None, resolution: Optional[tuple] = None, hd_engine: Optional[str] = None, viewport_api: Union[ViewportAPI, str, None] = None, hydra_engine_options: Optional[dict] = None, *ui_args, **ui_kwargs): """ViewportWidget contructor Args: usd_context_name (str): The name of a UsdContext this Viewport will be viewing. camera_path (str): The path to a UsdGeom.Camera to render with. resolution: (x,y): The size of the backing texture that is rendered into (or 'fill_frame' to lock to UI size). viewport_api: (ViewportAPI, str) A ViewportAPI instance that users have access to via .viewport_api property or a unique string id used to create a default ViewportAPI instance. """ self.__ui_frame: ui.Frame = ui.Frame(*ui_args, **ui_kwargs) self.__viewport_texture: Optional[ViewportTexture] = None self.__display_delegate: Optional[ViewportDisplayDelegate] = None self.__g_instances.append(weakref.proxy(self, ViewportWidget.__clean_instances)) self.__stage_listener = None self.__rsettings_changed = None if not viewport_api or not isinstance(viewport_api, ViewportAPI): viewport_id = viewport_api if viewport_api else str(id(self)) self.__vp_api: ViewportAPI = ViewportAPI(usd_context_name, viewport_id, self._viewport_changed) else: self.__vp_api: ViewportAPI = viewport_api # This object or it's parent-scope instantiator own the API, so hand out a weak-ref proxy self.__proxy_api = weakref.proxy(self.__vp_api) self.__update_api_texture = self.__vp_api._ViewportAPI__set_hydra_texture self.__stage_up: Optional[StageAxis] = None self.__size_changed: bool = False self.__resize_future: Optional[asyncio.Future] = None self.__resize_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None self.__push_ui_to_viewport: bool = False self.__expand_viewport_to_ui: bool = False self.__full_resolution: Tuple[float, float] = (0.0, 0.0) # Whether to account for DPI when driving the Viewport resolution self.__resolution_uses_dpi: bool = True resolution = self.__resolve_resolution(resolution) # Save any arguments to send to HydraTexture in a local kwargs dict self.__hydra_engine_options = hydra_engine_options # TODO: Defer ui creation until stage open self.__build_ui(usd_context_name, camera_path, resolution, hd_engine) def on_usd_context_event(event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.OPENED): self.__on_stage_opened(self.__ensure_usd_stage(), camera_path, resolution, hd_engine) elif event.type == int(omni.usd.StageEventType.CLOSING): self.__remove_notifications() elif event.type == int(omni.usd.StageEventType.SETTINGS_SAVING): # XXX: This might be better handled at a higher level or allow opt into implicit camera saving if carb.settings.get_settings().get("/app/omni.usd/storeCameraSettingsToUsdStage"): if self.__vp_api: time, camera = self.__vp_api.time, str(self.__vp_api.camera_path) else: time, camera = None, None save_implicit_cameras(self.__ensure_usd_stage(), time, camera) usd_context = self.__ensure_usd_context() self.__stage_subscription = usd_context.get_stage_event_stream().create_subscription_to_pop( on_usd_context_event, name=f'ViewportWidget {self.name} on_usd_context_event' ) stage = usd_context.get_stage() if stage: self.__on_stage_opened(stage, camera_path, resolution, hd_engine) elif usd_context and carb.settings.get_settings().get("/exts/omni.kit.widget.viewport/autoAttach/mode") == 2: # Initialize the auto-attach now, but watch for all excpetions so that constructor returns properly and this # ViewportWidget is valid and fully constructed in order to try and re-setup on next stage open try: resolution, tx_resolution = self.__get_texture_resolution(resolution) self.__viewport_texture = ViewportTexture(usd_context_name, camera_path, tx_resolution, hd_engine, hydra_engine_options=self.__hydra_engine_options, update_api_texture=self.__update_api_texture) self.__update_api_texture(self.__viewport_texture, None) self.__viewport_texture._on_stage_opened(self.__set_image_data, camera_path, self.__is_first_instance()) except Exception: import traceback carb.log_error(traceback.format_exc()) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ # Clean ourself from the instance list ViewportWidget.__clean_instances(None, self) self.__stage_subscription = None self.__remove_notifications() if self.__vp_api: clear_engine = self.__vp_api.set_hd_engine if clear_engine: clear_engine(None) self.__update_api_texture(None, None) self.__destroy_ui() self.__vp_api = None self.__proxy_api = None self.__resize_task_or_future = None @property def usd_context_name(self): return self.__vp_api.usd_context_name @property def display_delegate(self): return self.__display_delegate @display_delegate.setter def display_delegate(self, display_delegate: ViewportDisplayDelegate): if not isinstance(display_delegate, ViewportDisplayDelegate): raise RuntimeError('display_delegate must be a ViewportDisplayDelegate, {display_delegate} is not') # Store the previous delegate for return value and comparison wtether anything is actually changing prev_delegate = self.__display_delegate # If the delegate is different, call the create method and change this instance's value if succesful if prev_delegate != display_delegate: self.__ui_frame.clear() display_delegate.create(self.__ui_frame, prev_delegate) self.__display_delegate = display_delegate # Return the previous delegate so callers can swap and restore return prev_delegate def _viewport_changed(self, camera_path: Sdf.Path, stage: Usd.Stage, time: Usd.TimeCode = Usd.TimeCode.Default()): # During re-open camera_path can wind up in an empty state, so be careful around getting the UsdGeom.Camera prim = stage.GetPrimAtPath(camera_path) if (camera_path and stage) else None camera = UsdGeom.Camera(prim) if prim else None if not camera: return None, None, None canvas_size = self.__display_delegate.size force_update = self.__size_changed self.__vp_api._sync_viewport_api(camera, canvas_size, time, force_update=force_update) return camera, canvas_size, time def __ensure_usd_context(self, usd_context: omni.usd.UsdContext = None): if not usd_context: usd_context = self.__vp_api.usd_context if not usd_context: raise RuntimeError(f'omni.usd.UsdContext "{self.usd_context_name}" does not exist') return usd_context def __ensure_usd_stage(self, usd_context: omni.usd.UsdContext = None): stage = self.__ensure_usd_context(usd_context).get_stage() if stage: return stage raise RuntimeError(f'omni.usd.UsdContext "{self.usd_context_name}" has no stage') def __remove_notifications(self): # Remove notifications that are -transient- or related to a stage and can be easily setup if self.__stage_listener: self.__stage_listener.Revoke() self.__stage_listener = None if self.__rsettings_changed and self.__viewport_texture: self.__viewport_texture._remove_render_settings_changed_fn(self.__rsettings_changed) self.__rsettings_changed = None if self.__ui_frame: self.__ui_frame.set_computed_content_size_changed_fn(None) # self.set_build_fn(None) def __setup_notifications(self, stage: Usd.Stage, hydra_texture): # Remove previous -soft- notifications self.__remove_notifications() # Proxy these two object so as not to extend their lifetime the API object if hydra_texture and not isinstance(hydra_texture, weakref.ProxyType): hydra_texture = weakref.proxy(hydra_texture) assert hydra_texture is None or isinstance(hydra_texture, weakref.ProxyType), "Not sending a proxied object" self.__update_api_texture(weakref.proxy(self.__viewport_texture), hydra_texture) # Stage changed notification (Tf.Notice) def stage_changed_notice(notice, sender): camera_path = self.__vp_api.camera_path if not camera_path: return first_instance = self.__is_first_instance() camera_path_str = camera_path.pathString for p in notice.GetChangedInfoOnlyPaths(): if p == Sdf.Path.absoluteRootPath: if self.__stage_up.update(sender, self.__vp_api.time, self.usd_context_name, first_instance): self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage()) break prim_path = p.GetPrimPath() # If it is the camera path, assume any property change can affect view/projection if prim_path != camera_path: # Not the camera path, but any transform change to any parent also affects view is_child = camera_path_str.startswith(prim_path.pathString) if not is_child or not UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name): continue self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage()) break # omni.ui notification that the widget size has changed def update_size(): try: self.__size_changed = True self.__root_size_changed() self.__vp_api.viewport_changed(self.__vp_api.camera_path, self.__ensure_usd_stage()) finally: self.__size_changed = False # async version to ellide intermediate resize event async def resize_future(n_frames: int, mouse_wait: int, mouse_up: bool, update_projection: bool = False): import omni.appwindow import omni.kit.app import carb.input if update_projection: prim = stage.GetPrimAtPath(self.__vp_api.camera_path) camera = UsdGeom.Camera(prim) if prim else None if not camera: update_projection = False app = omni.kit.app.get_app() async def skip_frame(): await app.next_update_async() if update_projection: self.__vp_api._sync_viewport_api(camera, self.__display_delegate.size, force_update=True) if mouse_wait or mouse_up: iinput = carb.input.acquire_input_interface() app_window = omni.appwindow.get_default_app_window() mouse = app_window.get_mouse() mouse_value = iinput.get_mouse_value(mouse, carb.input.MouseInput.LEFT_BUTTON) frames_waited, mouse_static, prev_mouse = 0, 0, None while mouse_value: await skip_frame() frames_waited = frames_waited + 1 # Check mouse up no matter what, up cancels even if waiting for mouse paused mouse_value = iinput.get_mouse_value(mouse, carb.input.MouseInput.LEFT_BUTTON) if mouse_wait and mouse_value: if mouse_static > mouse_wait: # Else if the mouse has been on same pixel for more than required time, done break else: # Compare current and previous mouse locations cur_mouse = iinput.get_mouse_coords_pixel(mouse) if prev_mouse: if (cur_mouse[0] == prev_mouse[0]) and (cur_mouse[1] == prev_mouse[1]): mouse_static = mouse_static + 1 else: mouse_static = 0 prev_mouse = cur_mouse # Make sure to wait the miniumum nuber of frames as well if n_frames: n_frames = max(0, n_frames - frames_waited) for _ in range(n_frames): await skip_frame() # Check it hasn't been handled alredy once more if self.__resize_future.done(): return # Finally flag it as handled and push the size change self.__resize_future.set_result(True) update_size() def size_changed_notification(*args, **kwargs): # Ellide intermediate resize events when pushing ui size to Viewport if self.__push_ui_to_viewport or self.__expand_viewport_to_ui or self.__vp_api.fill_frame: if self.__resize_future and not self.__resize_future.done(): return # Setting that controls the number of ui-frame delay settings = carb.settings.get_settings() f_delay = settings.get("/exts/omni.kit.widget.viewport/resize/textureFrameDelay") mouse_pause = settings.get("/exts/omni.kit.widget.viewport/resize/waitForMousePaused") mouse_up = settings.get("/exts/omni.kit.widget.viewport/resize/waitForMouseUp") update_proj = settings.get("/exts/omni.kit.widget.viewport/resize/updateProjection") if f_delay or mouse_pause or mouse_up: self.__resize_future = asyncio.Future() self.__resize_task_or_future = run_coroutine(resize_future(f_delay, mouse_pause, mouse_up, update_proj)) return update_size() # hydra_texture notification that the render-settings have changed (we only care about camera and resolution) def render_settings_changed(camera_path, resolution): # Notify everything else in the chain self.__vp_api.viewport_changed(camera_path, self.__ensure_usd_stage()) self.__vp_api._notify_render_settings_change() self.__stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, lambda n, s: stage_changed_notice(n, s), stage) self.__rsettings_changed = self.__viewport_texture._add_render_settings_changed_fn(render_settings_changed) self.__ui_frame.set_computed_content_size_changed_fn(size_changed_notification) # self.set_build_fn(update_size) # Update now if the widget is layed out if self.__ui_frame.computed_height: update_size() def __resolve_resolution(self, resolution): # XXX: ViewportWindow handles the de-serialization of saved Viewport resolution. # This means clients of ViewportWidget only must handle startup resolution themselves. if resolution is None: # Support legacy settings to force fit-viewport settings = carb.settings.get_settings() width, height = settings.get('/app/renderer/resolution/width'), settings.get('/app/renderer/resolution/height') # If both are set to values above 0, that is the default resolution for a Viewport # If either of these being zero or below causes autmoatic resolution to fill the UI frame if ((width is not None) and (width > 0)) and ((height is not None) and (height > 0)): resolution = (width, height) elif ((width is not None) and (width <= 0)) or ((height is not None) and (height <= 0)): resolution = 'fill_frame' # Allow a 'fill_frame' constant to be used for resolution # Any constant zero or below also fills frame (support legacy behavior) if (resolution is not None) and ((isinstance(resolution, str) and resolution == 'fill_frame') or int(resolution[0]) <= 0 or int(resolution[1]) <= 0): resolution = 'fill_frame' self.__vp_api.fill_frame = True # Allow a 'fill_frame' constant to be used for resolution # Any constant zero or below also fills frame (support legacy behavior) if (resolution is not None): if (isinstance(resolution, str) and resolution == 'fill_frame') or int(resolution[0]) <= 0 or int(resolution[1]) <= 0: resolution = 'fill_frame' self.__push_ui_to_viewport = True self.__vp_api.fill_frame = True else: self.__full_resolution = resolution return resolution def __get_texture_resolution(self, resolution: Union[str, tuple]): # Don't pass 'fill_frame' to ViewportTexture if it was requested, that will be done during layout anyway if resolution == 'fill_frame': return ((0, 0), None) return resolution, resolution def __build_ui(self, usd_context_name: str, camera_path: str, resolution: Union[str, tuple], hd_engine: str): # Required for a lot of things (like selection-color) to work! init_settings() resolution, tx_resolution = self.__get_texture_resolution(resolution) # the viewport texture is the base background inmage that is drive by the Hydra_Texture object self.__viewport_texture = ViewportTexture(usd_context_name, camera_path, tx_resolution, hd_engine, hydra_engine_options=self.__hydra_engine_options, update_api_texture=self.__update_api_texture) self.__update_api_texture(self.__viewport_texture, None) self.display_delegate = ViewportDisplayDelegate(self.__proxy_api) # Pull the current Viewport full resolution now (will call __root_size_changed) self.set_resolution(resolution) def __destroy_ui(self): self.__display_delegate.destroy() if self.__viewport_texture: self.__viewport_texture.destroy() self.__viewport_texture = None if self.__ui_frame: self.__ui_frame.destroy() self.__ui_frame = None def __is_first_instance(self) -> bool: for vp_instance in self.__g_instances: if vp_instance == self: # vpinstance is this object, and no other instances attached to named UsdContext has been seen return True elif vp_instance.usd_context_name == self.usd_context_name: # vpinstance is NOT this object, but vpinstance is attached to same UsdContext return False # Should be unreachable, but would be True in the event neither case above was triggered return True def __set_image_data(self, texture, presentation_key = 0): vp_api = self.__vp_api prim = self.__ensure_usd_stage().GetPrimAtPath(vp_api.camera_path) camera = UsdGeom.Camera(prim) if prim else None frame_info = vp_api.frame_info lock_to_render = vp_api.lock_to_render_result view = frame_info.get('view', None) if lock_to_render else None # omni.ui.scene may not handle RTX projection yet, so calculate from USD camera projection = None # frame_info.get('projection', None) if lock_to_render else None canvas_size = self.__display_delegate.update(viewport_api=vp_api, texture=texture, view=view, projection=projection, presentation_key=presentation_key) vp_api._sync_viewport_api(camera, canvas_size, vp_api.time, view, projection, force_update=True) vp_api._notify_frame_change() def __on_stage_opened(self, stage: Usd.Stage, camera_path: str, resolution: tuple, hd_engine: str): """Called when opening a new stage""" # We support creation of ViewportWidget with an explicit path. # If that path was not given or does not exists, fall-back to ov-metadata if camera_path: cam_prim = stage.GetPrimAtPath(camera_path) if not cam_prim or not UsdGeom.Camera(cam_prim): camera_path = False if not camera_path: # TODO: 104 Put in proper namespace and per viewport # camera_path = stage.GetMetadataByDictKey("customLayerData", f"cameraSettings:{self.__vp_api.id}:boundCamera") or # Fallback to < 103.1 boundCamera try: # Wrap in a try-catch so failure reading metadata does not cascade to caller. camera_path = stage.GetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera") except Tf.ErrorException as e: carb.log_error(f"Error reading Usd.Stage's boundCamera metadata {e}") # Cache the known up-axis to watch for changes self.__stage_up = StageAxis(stage) if self.__viewport_texture is None: self.__build_ui(self.usd_context_name, camera_path, resolution, hd_engine) else: self.__viewport_texture.camera_path = camera_path hydra_texture = self.__viewport_texture._on_stage_opened(self.__set_image_data, camera_path, self.__is_first_instance()) self.__setup_notifications(stage, hydra_texture) # XXX: Temporary API for driving Viewport resolution based on UI. These may be removed. @property def resolution_uses_dpi(self) -> bool: """Whether to account for DPI when driving the Viewport texture resolution""" return self.__resolution_uses_dpi @property def fill_frame(self) -> bool: """Whether the ui object containing the Viewport texture expands both dimensions of resolution based on the ui size""" return self.__push_ui_to_viewport @property def expand_viewport(self) -> bool: """Whether the ui object containing the Viewport texture expands one dimension of resolution to cover the full ui size""" return self.__expand_viewport_to_ui @resolution_uses_dpi.setter def resolution_uses_dpi(self, value: bool) -> None: """Tell the ui object whether to use DPI scale when driving the Viewport texture resolution""" value = bool(value) if self.__resolution_uses_dpi != value: self.__resolution_uses_dpi = value self.__root_size_changed() @fill_frame.setter def fill_frame(self, value: bool) -> None: """Tell the ui object containing the Viewport texture to expand both dimensions of resolution based on the ui size""" value = bool(value) if self.__push_ui_to_viewport != value: self.__push_ui_to_viewport = value if not self.__root_size_changed(): self.__vp_api.resolution = self.__full_resolution @expand_viewport.setter def expand_viewport(self, value: bool) -> None: """Tell the ui object containing the Viewport texture to expand one dimension of resolution to cover the full ui size""" value = bool(value) if self.__expand_viewport_to_ui != value: self.__expand_viewport_to_ui = value if not self.__root_size_changed(): self.__vp_api.resolution = self.__full_resolution def set_resolution(self, resolution: Tuple[float, float]) -> None: self.__full_resolution = resolution # When resolution is <= 0, that means ui.Frame drives Viewport resolution self.__push_ui_to_viewport = (resolution is None) or (resolution[0] <= 0) or (resolution[1] <= 0) if not self.__root_size_changed(): # If neither option is enabled, then just set the resolution directly self.__vp_api.resolution = resolution @property def resolution(self) -> Tuple[float, float]: return self.__vp_api.resolution @resolution.setter def resolution(self, resolution: Tuple[float, float]): self.set_resolution(resolution) @property def full_resolution(self): return self.__full_resolution def __root_size_changed(self, *args, **kwargs): # If neither options are enabled, then do nothing to the Viewport's resolution if not self.__push_ui_to_viewport and not self.__expand_viewport_to_ui: return False # Match the legacy Viewport resolution and fit # XXX: Note for a downsampled constant resolution, that is expanded to the Viewport dimensions # the order of operation is off if one expectes 512 x 512 @ 1 to 1024 x 1024 @ 0.5 to exapnd to the same result # Get the omni.ui.Widget computed size ui_frame = self.__ui_frame res_x, res_y = int(ui_frame.computed_width), int(ui_frame.computed_height) # Scale by DPI as legacy Viewport (to match legacy Viewport calculations) dpi_scale = ui.Workspace.get_dpi_scale() if self.__resolution_uses_dpi else 1.0 res_x, res_y = res_x * dpi_scale, res_y * dpi_scale # Full resolution width and hight fres_x, fres_y = self.__full_resolution if self.__full_resolution else (res_x, res_y) if self.__expand_viewport_to_ui and (fres_y > 0) and (res_y > 0): tex_ratio = fres_x / fres_y ui_ratio = res_x / res_y if tex_ratio < ui_ratio: fres_x = fres_x * (ui_ratio / tex_ratio) else: fres_y = fres_y * (tex_ratio / ui_ratio) # Limit the resolution to not grow too large res_x, res_y = min(res_x, fres_x), min(res_y, fres_y) self.__vp_api.resolution = res_x, res_y return True
28,492
Python
48.125862
159
0.615752
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_scene_view_integration.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestSceneViewIntegration"] from omni.kit.widget.viewport import ViewportWidget from omni.ui.tests.test_base import OmniUiTest import omni.usd from pathlib import Path import carb CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') TEST_WIDTH, TEST_HEIGHT = 360, 240 class TestSceneViewIntegration(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await omni.usd.get_context().new_stage_async() # After running each test async def tearDown(self): await super().tearDown() await self.linux_gpu_shutdown_workaround() async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''): await self.wait_n_updates(10) omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name)) await self.wait_n_updates(10) async def open_usd_file(self, filename: str, resolved: bool = False): usd_context = omni.usd.get_context() usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename) await usd_context.open_stage_async(usd_path) return usd_context def assertAlmostEqual(self, a, b, places: int = 4): if isinstance(a, float) or isinstance(a, int): super().assertAlmostEqual(a, b, places) else: for i in range(len(b)): super().assertAlmostEqual(a[i], b[i], places) async def test_scene_view_compositing(self): """Test adding a SceneView to the Viewport will draw correctly""" await self.open_usd_file("cube.usda") import omni.ui import omni.ui.scene await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # Need a Window otherwise the ui size calculations won't run window_flags = omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR style = {"border_width": 0} window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags, padding_x=0, padding_y=0) with window.frame: window.frame.set_style(style) with omni.ui.ZStack(): viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT), style=style) scene_view = omni.ui.scene.SceneView(style=style) with scene_view.scene: size = 50 vertex_indices = [0, 1, 3, 2, 4, 6, 7, 5, 6, 2, 3, 7, 4, 5, 1, 0, 4, 0, 2, 6, 5, 7, 3, 1] points = [(-size, -size, size), (size, -size, size), (-size, size, size), (size, size, size), (-size, -size, -size), (size, -size, -size), (-size, size, -size), (size, size, -size)] omni.ui.scene.PolygonMesh(points, [[1.0, 0.0, 1.0, 0.5]] * len(vertex_indices), vertex_counts=[4] * 6, vertex_indices=vertex_indices, wireframe=True, thicknesses=[2] * len(vertex_indices)) viewport_widget.viewport_api.add_scene_view(scene_view) await self.wait_n_updates(32) await self.finalize_test(golden_img_dir=TEST_FILES_DIR, golden_img_name="test_scene_view_compositing.png") viewport_widget.viewport_api.remove_scene_view(scene_view) viewport_widget.destroy() del viewport_widget
4,183
Python
42.583333
125
0.608654
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_widget.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestWidgetAPI"] import omni.kit.test from omni.kit.widget.viewport import ViewportWidget from omni.kit.widget.viewport.display_delegate import ViewportDisplayDelegate, OverlayViewportDisplayDelegate from omni.kit.test import get_test_output_path from omni.ui.tests.test_base import OmniUiTest import omni.kit.commands import omni.usd import carb from pxr import Gf, Sdf, Usd, UsdGeom from pathlib import Path import traceback CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') OUTPUTS_DIR = Path(get_test_output_path()) TEST_WIDTH, TEST_HEIGHT = 360, 240 class TestWidgetAPI(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await omni.usd.get_context().new_stage_async() # After running each test async def tearDown(self): await super().tearDown() await self.linux_gpu_shutdown_workaround() async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''): await self.wait_n_updates(10) omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name)) await self.wait_n_updates(10) async def open_usd_file(self, filename: str, resolved: bool = False): usd_context = omni.usd.get_context() usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename) await usd_context.open_stage_async(usd_path) return usd_context def assertAlmostEqual(self, a, b, places: int = 4): if isinstance(a, float) or isinstance(a, int): super().assertAlmostEqual(a, b, places) else: for i in range(len(b)): super().assertAlmostEqual(a[i], b[i], places) async def test_widget_pre_open(self): """Test ViewportWidget creation with existing UsdContext and Usd.Stage and startup resolutin settings""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('cube.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() settings = carb.settings.get_settings() viewport_widget = None try: settings.set("/app/renderer/resolution/width", 400) settings.set("/app/renderer/resolution/height", 400) await self.wait_n_updates(6) viewport_widget = ViewportWidget() viewport_api = viewport_widget.viewport_api # Test omni.usd.UsdContext and Usd.Stage properties self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) # Test startup resolution self.assertEqual(viewport_api.resolution, (400, 400)) self.assertEqual(viewport_api.resolution_scale, 1.0) # Test deprecated resolution API methods (not properties) self.assertEqual(viewport_api.resolution, viewport_api.get_texture_resolution()) viewport_api.set_texture_resolution((200, 200)) self.assertEqual(viewport_api.resolution, (200, 200)) # Test deprecated camera API methods (not properties) self.assertEqual(viewport_api.camera_path, viewport_api.get_active_camera()) viewport_api.set_active_camera(Sdf.Path('/OmniverseKit_Top')) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Top')) finally: settings.destroy_item("/app/renderer/resolution/width") settings.destroy_item("/app/renderer/resolution/height") if viewport_widget: viewport_widget.destroy() del viewport_widget await self.wait_n_updates(6) await self.finalize_test_no_image() async def test_widget_post_open(self): """Test ViewportWidget adopts a change to the Usd.Stage after it is visible and startup resolution scale setting""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) settings = carb.settings.get_settings() viewport_widget = None try: settings.set("/app/renderer/resolution/width", 400) settings.set("/app/renderer/resolution/height", 400) settings.set("/app/renderer/resolution/multiplier", 0.5) await self.wait_n_updates(6) viewport_widget = ViewportWidget() viewport_api = viewport_widget.viewport_api # Test omni.usd.UsdContext and Usd.Stage properties usd_context = await self.open_usd_file('sphere.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() # Test display-delegate API await self.__test_display_delegate(viewport_widget) self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) # Test startup resolution self.assertEqual(viewport_api.resolution, (200, 200)) self.assertEqual(viewport_api.resolution_scale, 0.5) finally: settings.destroy_item("/app/renderer/resolution/width") settings.destroy_item("/app/renderer/resolution/height") settings.destroy_item("/app/renderer/resolution/multiplier") if viewport_widget: viewport_widget.destroy() del viewport_widget await self.wait_n_updates(6) await self.finalize_test_no_image() async def test_widget_custom_camera_saved(self): """Test ViewportWidget will absorb the stored Kit bound camera""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('custom_camera.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) viewport_api = viewport_widget.viewport_api self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera')) cam_prim = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path) self.assertTrue(bool(cam_prim)) cam_geom = UsdGeom.Camera(cam_prim) self.assertTrue(bool(cam_geom)) coi_prop = cam_prim.GetProperty('omni:kit:centerOfInterest') self.assertTrue(bool(coi_prop)) coi_prop.Get() world_pos = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0)) self.assertAlmostEqual(world_pos, Gf.Vec3d(250, 825, 800)) self.assertAlmostEqual(coi_prop.Get(), Gf.Vec3d(0, 0, -1176.0633486339075)) viewport_widget.destroy() del viewport_widget await self.finalize_test_no_image() async def test_widget_custom_camera_contructor(self): """Test ViewportWidget can be contructed with a specified Camera""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('custom_camera.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT), camera_path='/World/Camera_01') viewport_api = viewport_widget.viewport_api self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera_01')) cam_prim = viewport_api.stage.GetPrimAtPath(viewport_api.camera_path) self.assertTrue(bool(cam_prim)) cam_geom = UsdGeom.Camera(cam_prim) self.assertTrue(bool(cam_geom)) coi_prop = cam_prim.GetProperty('omni:kit:centerOfInterest') self.assertTrue(bool(coi_prop)) coi_prop.Get() world_pos = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0)) self.assertAlmostEqual(world_pos, Gf.Vec3d(350, 650, -900)) self.assertAlmostEqual(coi_prop.Get(), Gf.Vec3d(0, 0, -1164.0446726822815)) viewport_widget.destroy() del viewport_widget await self.finalize_test_no_image() async def test_implicit_cameras(self): """Test ViewportWidget creation with existing UsdContext and Usd.Stage""" await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_context = await self.open_usd_file('cube.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) viewport_api = viewport_widget.viewport_api self.assertEqual(viewport_api.usd_context, usd_context) self.assertEqual(viewport_api.stage, usd_context_stage) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) time = Usd.TimeCode.Default() def test_default_camera_position(cam_path: str, expected_pos: Gf.Vec3d, expected_rot: Gf.Vec3d = None): prim = usd_context.get_stage().GetPrimAtPath(cam_path) camera = UsdGeom.Camera(prim) if prim else None self.assertTrue(bool(camera)) world_xform = camera.ComputeLocalToWorldTransform(time) world_pos = world_xform.Transform(Gf.Vec3d(0, 0, 0)) self.assertAlmostEqual(world_pos, expected_pos) if expected_rot: rot_prop = prim.GetProperty('xformOp:rotateXYZ') self.assertIsNotNone(rot_prop) rot_value = rot_prop.Get() self.assertAlmostEqual(rot_value, expected_rot) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(-35.26439, 45, 0)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000), Gf.Vec3d(0, 0, 0)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0), Gf.Vec3d(90, 0, 180)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0), Gf.Vec3d(0, -90, 0)) output_file = str(OUTPUTS_DIR.joinpath('implicit_cameras_same.usda')) (result, err, saved_layers) = await usd_context.save_as_stage_async(output_file) self.assertTrue(result) await omni.usd.get_context().new_stage_async() await usd_context.open_stage_async(output_file) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0)) # Change OmniverseKit_Persp location omni.kit.commands.create( 'TransformPrimCommand', path='/OmniverseKit_Persp', new_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(-100, -200, -300)), old_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(500, 500, 500)), time_code=time, ).do() # Change OmniverseKit_Front location omni.kit.commands.create( 'TransformPrimCommand', path='/OmniverseKit_Front', new_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(0, 0, 56789)), old_transform_matrix=Gf.Matrix4d().SetTranslate(Gf.Vec3d(0, 0, 50000)), time_code=time, ).do() # Change OmniverseKit_Top aperture UsdGeom.Camera(usd_context.get_stage().GetPrimAtPath('/OmniverseKit_Top')).GetHorizontalApertureAttr().Set(50000) output_file = str(OUTPUTS_DIR.joinpath('implicit_cameras_changed.usda')) (result, err, saved_layers) = await usd_context.save_as_stage_async(output_file) self.assertTrue(result) await omni.usd.get_context().new_stage_async() await usd_context.open_stage_async(output_file) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(-100, -200, -300)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 56789)) # These haven't changed and should be default test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0)) # Test ortho aperture change is picked up horiz_ap = UsdGeom.Camera(usd_context.get_stage().GetPrimAtPath('/OmniverseKit_Top')).GetHorizontalApertureAttr().Get() self.assertAlmostEqual(horiz_ap, 50000) # Test implicit camera creation for existing Z-Up scene # usd_context = await self.open_usd_file('implicit_cams_z_up.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Top')) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(54.73561, 0, 135)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(500, 0, 0), Gf.Vec3d(90, 0, 90)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 0, 25), Gf.Vec3d(0, 0, -90)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(0, -50000, 0), Gf.Vec3d(90, 0, 0)) # Test that creation of another ViewportWidget doesn't affect existing implict caameras viewport_widget_2 = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(500, 500, 500), Gf.Vec3d(54.73561, 0, 135)) viewport_widget_2.destroy() del viewport_widget_2 # Test saving metadata to usd, so copy the input files to writeable temp files from shutil import copyfile tmp_layers = str(OUTPUTS_DIR.joinpath('layers.usda')) copyfile(str(USD_FILES_DIR.joinpath('layers.usda')), tmp_layers) copyfile(str(USD_FILES_DIR.joinpath('sublayer.usda')), str(OUTPUTS_DIR.joinpath('sublayer.usda'))) # Open the copy and validate the default camera usd_context = await self.open_usd_file(tmp_layers, True) self.assertEqual(viewport_api.camera_path, Sdf.Path('/OmniverseKit_Persp')) # Switch to a known camera and re-validate viewport_api.camera_path = '/World/Camera' self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera')) # Save the file and re-open it # XXX: Need to dirty something in the stage for save to take affect stage = usd_context.get_stage() stage.GetPrimAtPath(viewport_api.camera_path).GetAttribute('focalLength').Set(51) # Move the target layer to a sub-layer and then attmept the save with Usd.EditContext(stage, stage.GetLayerStack()[-1]): await usd_context.save_stage_async() await omni.kit.app.get_app().next_update_async() await omni.usd.get_context().new_stage_async() # Re-open usd_context = await self.open_usd_file(tmp_layers, True) # Camera should match what was just saved self.assertEqual(viewport_api.camera_path, Sdf.Path('/World/Camera')) # Test dynmically switching Stage up-axis async def set_stage_axis(stage, cam_prim, up_axis: str, wait: int = 2): stage.SetMetadata(UsdGeom.Tokens.upAxis, up_axis) for i in range(wait): await omni.kit.app.get_app().next_update_async() return UsdGeom.Xformable(cam_prim).GetLocalTransformation() await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() self.assertIsNotNone(usd_context) stage = usd_context.get_stage() self.assertIsNotNone(stage) cam_prim = stage.GetPrimAtPath(viewport_api.camera_path) self.assertIsNotNone(cam_prim) cam_xformable = UsdGeom.Xformable(cam_prim) self.assertIsNotNone(cam_xformable) self.assertEqual(cam_prim.GetPath().pathString, '/OmniverseKit_Persp') xform_y = await set_stage_axis(stage, cam_prim, 'Y') xform_y1 = cam_xformable.GetLocalTransformation() self.assertEqual(xform_y, xform_y1) self.assertAlmostEqual(xform_y.ExtractRotation().GetAxis(), Gf.Vec3d(-0.59028449177967, 0.7692737418738016, 0.24450384215364918)) xform_z = await set_stage_axis(stage, cam_prim, 'Z') self.assertNotEqual(xform_y, xform_z) self.assertAlmostEqual(xform_z.ExtractRotation().GetAxis(), Gf.Vec3d(0.1870534627395223, 0.4515870066346049, 0.8723990930279281)) xform_x = await set_stage_axis(stage, cam_prim, 'X') self.assertNotEqual(xform_x, xform_z) self.assertNotEqual(xform_x, xform_y) self.assertAlmostEqual(xform_x.ExtractRotation().GetAxis(), Gf.Vec3d(0.541766002079245, 0.07132485246922922, 0.8374976802423478)) texture_pixel, vp_api = viewport_api.map_ndc_to_texture((0, 0)) self.assertAlmostEqual(texture_pixel, (0.5, 0.5)) self.assertEqual(vp_api, viewport_api) # Test return of Viewport is None when NDC is out of bounds texture_pixel, vp_api = viewport_api.map_ndc_to_texture((-2, -2)) self.assertIsNone(vp_api) # Test return of Viewport is None when NDC is out of bounds texture_pixel, vp_api = viewport_api.map_ndc_to_texture((2, 2)) self.assertIsNone(vp_api) # Test camera is correctly positioned/labeled with new stage and Z or Y setting settings = carb.settings.get_settings() async def new_stage_with_up_setting(up_axis: str, wait: int = 2): settings.set('/persistent/app/stage/upAxis', up_axis) for i in range(wait): await omni.kit.app.get_app().next_update_async() await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() self.assertIsNotNone(usd_context) stage = usd_context.get_stage() self.assertIsNotNone(stage) cam_prim = stage.GetPrimAtPath(viewport_api.camera_path) return UsdGeom.Xformable(cam_prim).GetLocalTransformation() # Switch to new stage as Z-up and test against values from previous Z-up try: xform_z = await new_stage_with_up_setting('Z') self.assertNotEqual(xform_y, xform_z) self.assertAlmostEqual(xform_z.ExtractRotation().GetAxis(), Gf.Vec3d(0.1870534627395223, 0.4515870066346049, 0.8723990930279281)) finally: settings.destroy_item('/persistent/app/stage/upAxis') try: # Test again against default up as Y xform_y1 = await new_stage_with_up_setting('Y') self.assertEqual(xform_y, xform_y1) self.assertAlmostEqual(xform_y.ExtractRotation().GetAxis(), Gf.Vec3d(-0.59028449177967, 0.7692737418738016, 0.24450384215364918)) finally: settings.destroy_item('/persistent/app/stage/upAxis') # Test opeinig a file with implicit cameras saved into it works properly usd_context = await self.open_usd_file('implcit_precision.usda') self.assertIsNotNone(usd_context.get_stage()) test_default_camera_position('/OmniverseKit_Persp', Gf.Vec3d(-1500, 400, 500), Gf.Vec3d(-15, 751, 0)) test_default_camera_position('/OmniverseKit_Front', Gf.Vec3d(0, 0, 50000), Gf.Vec3d(0, 0, 0)) test_default_camera_position('/OmniverseKit_Top', Gf.Vec3d(0, 50000, 0), Gf.Vec3d(90, 0, 180)) test_default_camera_position('/OmniverseKit_Right', Gf.Vec3d(-50000, 0, 0), Gf.Vec3d(0, -90, 0)) await self.__test_camera_startup_values(viewport_widget) await self.__test_camera_target_settings(viewport_widget) def get_tr(stage: Usd.Stage, cam: str): xf = UsdGeom.Camera(stage.GetPrimAtPath(f'/OmniverseKit_{cam}')).ComputeLocalToWorldTransform(0) return xf.ExtractTranslation() def get_rot(stage: Usd.Stage, cam: str): xf = UsdGeom.Camera(stage.GetPrimAtPath(f'/OmniverseKit_{cam}')).ComputeLocalToWorldTransform(0) decomp = (Gf.Vec3d(-1, 0, 0), Gf.Vec3d(0, -1, 0), Gf.Vec3d(0, 0, 1)) rotation = xf.ExtractRotation().Decompose(Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()) return rotation # Test re-opening ortho cameras keep orthogonal rotations usd_context = await self.open_usd_file('ortho_y.usda') stage = omni.usd.get_context().get_stage() self.assertTrue(Gf.IsClose(get_rot(stage, 'Top'), Gf.Vec3d(-90, 0, -180), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Front'), Gf.Vec3d(0, 0, 0), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Right'), Gf.Vec3d(0, -90, 0), 0.00001)) usd_context = await self.open_usd_file('ortho_z.usda') stage = omni.usd.get_context().get_stage() self.assertTrue(Gf.IsClose(get_rot(stage, 'Top'), Gf.Vec3d(0, 0, -90), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Front'), Gf.Vec3d(90, 90, 0), 0.00001)) self.assertTrue(Gf.IsClose(get_rot(stage, 'Right'), Gf.Vec3d(90, 0, 0), 0.00001)) usd_context = await self.open_usd_file('cam_prop_declaration_only.usda') stage = omni.usd.get_context().get_stage() self.assertTrue(Gf.IsClose(get_tr(stage, 'Persp'), Gf.Vec3d(-417, 100, -110), 0.00001)) self.assertTrue(Gf.IsClose(get_tr(stage, 'Top'), Gf.Vec3d(0, 50000, 0), 0.00001)) self.assertTrue(Gf.IsClose(get_tr(stage, 'Front'), Gf.Vec3d(0, 0, 50000), 0.00001)) self.assertTrue(Gf.IsClose(get_tr(stage, 'Right'), Gf.Vec3d(-50000, 0, 0), 0.00001)) viewport_widget.destroy() del viewport_widget await self.finalize_test_no_image() async def test_dont_save_implicit_cameras(self): usd_context = omni.usd.get_context() await usd_context.new_stage_async() self.assertIsNotNone(usd_context.get_stage()) settings = carb.settings.get_settings() # Save current state so it restored shouldsave = settings.get("/app/omni.usd/storeCameraSettingsToUsdStage") try: settings.set("/app/omni.usd/storeCameraSettingsToUsdStage", False) output_file = str(OUTPUTS_DIR.joinpath('dont_save_implicit_cameras.usda')) (result, err, saved_layers) = await usd_context.save_as_stage_async(output_file) self.assertTrue(result) usd_context = await self.open_usd_file(output_file, True) stage = usd_context.get_stage() self.assertFalse(stage.HasMetadataDictKey("customLayerData", "cameraSettings")) except Exception as e: raise e finally: settings.set("/app/omni.usd/storeCameraSettingsToUsdStage", shouldsave) await self.finalize_test_no_image() async def __test_camera_startup_values(self, viewport_widget): # await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 18.147562, places=5) self.assertEqual(persp.GetFStopAttr().Get(), 0) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) self.assertEqual(top.GetHorizontalApertureAttr().Get(), 5000) self.assertEqual(top.GetVerticalApertureAttr().Get(), 5000) # Test typed-defaults and creation settings = carb.settings.get_settings() try: perps_key = '/persistent/app/primCreation/typedDefaults/camera' ortho_key = '/persistent/app/primCreation/typedDefaults/orthoCamera' settings.set(perps_key + '/focalLength', 150) settings.set(perps_key + '/fStop', 22) settings.set(perps_key + '/clippingRange', (200, 2000)) settings.set(perps_key + '/horizontalAperture', 1234) settings.set(ortho_key + '/horizontalAperture', 1000) settings.set(ortho_key + '/verticalAperture', 2000) settings.set(ortho_key + '/clippingRange', (20000.0, 10000000.0)) await usd_context.new_stage_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) persp = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertIsNotNone(persp) self.assertAlmostEqual(persp.GetFocalLengthAttr().Get(), 150) self.assertAlmostEqual(persp.GetFStopAttr().Get(), 22) self.assertAlmostEqual(persp.GetHorizontalApertureAttr().Get(), 1234) self.assertAlmostEqual(persp.GetClippingRangeAttr().Get(), Gf.Vec2f(200, 2000)) self.assertFalse(persp.GetVerticalApertureAttr().IsAuthored()) top = UsdGeom.Camera.Get(stage, '/OmniverseKit_Top') self.assertIsNotNone(top) self.assertAlmostEqual(top.GetHorizontalApertureAttr().Get(), 1000) self.assertAlmostEqual(top.GetVerticalApertureAttr().Get(), 2000) # Test that the extension.toml default is used self.assertAlmostEqual(top.GetClippingRangeAttr().Get(), Gf.Vec2f(20000.0, 10000000.0)) finally: # Reset now for all other tests settings.destroy_item(perps_key) settings.destroy_item(ortho_key) # viewport_widget.destroy() # del viewport_widget async def __test_camera_target_settings(self, viewport_widget): """Test /app/viewport/defaultCamera/target/distance settings values""" settings = carb.settings.get_settings() # These all have no defaults (as feature is disabled until set) enabled_key = "/app/viewport/defaultCamera/target/distance/enabled" value_key = "/app/viewport/defaultCamera/target/distance/value" unit_key = "/app/viewport/defaultCamera/target/distance/units" async def test_stage_open(filepath: str, expected_coi: Gf.Vec3d): usd_context = await self.open_usd_file(filepath) stage = usd_context.get_stage() await self.wait_n_updates(3) persp_cam = UsdGeom.Camera.Get(stage, '/OmniverseKit_Persp') self.assertTrue(bool(persp_cam.GetPrim().IsValid())) coi_prop = persp_cam.GetPrim().GetProperty('omni:kit:centerOfInterest') self.assertTrue(bool(coi_prop.IsValid())) self.assertAlmostEqual(coi_prop.Get(), expected_coi) async def set_target_distance(value, unit): settings.set(enabled_key, True) settings.set(value_key, value) settings.set(unit_key, unit) await self.wait_n_updates(3) try: await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -1732.0508)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -1732.0508)) await set_target_distance(5, "stage") await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -0.04999)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -50)) await set_target_distance(5, "meters") await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -500)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -0.5)) await set_target_distance(5, 1) await test_stage_open("units/0_01-mpu.usda", Gf.Vec3d(0, 0, -5)) await test_stage_open("units/10_0-mpu.usda", Gf.Vec3d(0, 0, -5)) finally: # Make sure to clear the keys for remainig tests settings.destroy_item(enabled_key) settings.destroy_item(value_key) settings.destroy_item(unit_key) async def __test_display_delegate(self, viewport_widget): self.assertIsNotNone(viewport_widget.display_delegate) self.assertTrue(isinstance(viewport_widget.display_delegate, ViewportDisplayDelegate)) def test_set_display_delegate(display_delegate): success = False try: viewport_widget.display_delegate = display_delegate success = True except RuntimeError: pass return success result = test_set_display_delegate(None) self.assertFalse(result) result = test_set_display_delegate(32) self.assertFalse(result) result = test_set_display_delegate(OverlayViewportDisplayDelegate(viewport_widget.viewport_api)) self.assertTrue(result) async def test_ui_driven_resolution(self): """Test ViewportWidget driving the underlying Viewport texture resolution""" import omni.ui await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # Need a Window otherwise the ui size calculations won't run window_flags = omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR style = {"border_width": 0} window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags, padding_x=0, padding_y=0) startup_resolution = TEST_WIDTH * 0.5, TEST_HEIGHT * 0.25 with window.frame: window.frame.set_style(style) viewport_widget = ViewportWidget(resolution=startup_resolution, style=style) await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], startup_resolution[0]) self.assertEqual(current_res[1], startup_resolution[1]) viewport_widget.fill_frame = True await self.wait_n_updates(8) # Should match the ui.Frame which should be filling the ui.Window current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], window.frame.computed_width) self.assertEqual(current_res[1], window.frame.computed_height) viewport_widget.fill_frame = False viewport_widget.expand_viewport = True await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution # Some-what arbitrary numbers from implementation that are know to be correct for 360, 240 ui.Frame self.assertEqual(current_res[0], 180) self.assertEqual(current_res[1], 120) full_resolution = viewport_widget.full_resolution self.assertEqual(full_resolution[0], startup_resolution[0]) self.assertEqual(full_resolution[1], startup_resolution[1]) # Test reversion to no fill or exapnd returns back to the resolution explicitly specified. viewport_widget.fill_frame = False viewport_widget.expand_viewport = False await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], startup_resolution[0]) self.assertEqual(current_res[1], startup_resolution[1]) # Set render resolution to x3 viewport_widget.resolution = (TEST_WIDTH * 2.5, TEST_HEIGHT * 2.5) viewport_widget.expand_viewport = True # Set Window size to x2 two_x_res = TEST_WIDTH * 2, TEST_HEIGHT * 2 window.width, window.height = two_x_res await self.wait_n_updates(8) current_res = viewport_widget.viewport_api.resolution self.assertEqual(current_res[0], two_x_res[0]) self.assertEqual(current_res[1], two_x_res[1]) viewport_widget.destroy() del viewport_widget window.destroy() del window await self.finalize_test_no_image() async def __test_engine_creation_arguments(self, hydra_engine_options, verify_engine): viewport_widget, window = None, None try: import omni.ui await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) # Need a Window otherwise the ui size calculations won't run window = omni.ui.Window("Test", width=TEST_WIDTH, height=TEST_HEIGHT) startup_resolution = TEST_WIDTH * 0.5, TEST_HEIGHT * 0.25 with window.frame: viewport_widget = ViewportWidget(resolution=startup_resolution, width=TEST_WIDTH, height=TEST_HEIGHT, hydra_engine_options=hydra_engine_options) await self.wait_n_updates(5) await verify_engine(viewport_widget.viewport_api._hydra_texture) finally: if viewport_widget is not None: viewport_widget.destroy() del viewport_widget if window is not None: window.destroy() del window await self.finalize_test_no_image() async def test_engine_creation_default_arguments(self): """Test default engine creation arguments""" hydra_engine_options = {} async def verify_engine(hydra_texture): settings = carb.settings.get_settings() tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate") is_async = settings.get(f"{hydra_texture.get_settings_path()}async") is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency") self.assertEqual(is_async, bool(settings.get("/app/asyncRendering"))) self.assertEqual(is_async_ll, bool(settings.get("/app/asyncRenderingLowLatency"))) self.assertEqual(tick_rate, int(settings.get("/persistent/app/viewport/defaults/tickRate"))) await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine) async def test_engine_creation_forward_arguments(self): """Test forwarding of engine creation arguments""" settings = carb.settings.get_settings() # Make sure the defaults are in a state that overrides from hydra_engine_options can be tested self.assertFalse(bool(settings.get("/app/asyncRendering"))) self.assertFalse(bool(settings.get("/app/asyncRenderingLowLatency"))) self.assertNotEqual(30, int(settings.get("/persistent/app/viewport/defaults/tickRate"))) try: hydra_engine_options = { "is_async": True, "is_async_low_latency": True, "hydra_tick_rate": 30 } async def verify_engine(hydra_texture): tick_rate = settings.get(f"{hydra_texture.get_settings_path()}hydraTickRate") is_async = settings.get(f"{hydra_texture.get_settings_path()}async") is_async_ll = settings.get(f"{hydra_texture.get_settings_path()}asyncLowLatency") self.assertEqual(is_async, hydra_engine_options.get("is_async")) self.assertEqual(is_async_ll, hydra_engine_options.get("is_async_low_latency")) self.assertEqual(tick_rate, hydra_engine_options.get("hydra_tick_rate")) await self.__test_engine_creation_arguments(hydra_engine_options, verify_engine) finally: settings.set("/app/asyncRendering", False) settings.destroy_item("/app/asyncRenderingLowLatency")
36,413
Python
46.414062
141
0.649411
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_capture.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestCaptureAPI"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.ui.tests.compare_utils import OUTPUTS_DIR, compare, CompareError import omni.usd import omni.ui as ui from omni.kit.widget.viewport import ViewportWidget from omni.kit.widget.viewport.capture import * from omni.kit.test_helpers_gfx.compare_utils import compare as gfx_compare from omni.kit.test.teamcity import teamcity_publish_image_artifact import carb import traceback from pathlib import Path import os from pxr import Usd, UsdRender CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') TEST_WIDTH, TEST_HEIGHT = 360, 240 NUM_DEFAULT_WINDOWS = 0 # XXX: Make this more accessible in compare_utils # def compare_images(image_name, threshold = 10): image1 = OUTPUTS_DIR.joinpath(image_name) image2 = TEST_FILES_DIR.joinpath(image_name) image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image_name).stem}.diffmap.png") gfx_compare(image1, image2, image_diffmap) class TestByteCapture(ByteCapture): def __init__(self, test, *args, **kwargs): super().__init__(*args, **kwargs) self.__test = test self.__complete = False def on_capture_completed(self, buffer, buffer_size, width, height, format): self.__test.assertEqual(width, TEST_WIDTH) self.__test.assertEqual(height, TEST_HEIGHT) self.__test.assertEqual(format, ui.TextureFormat.RGBA8_UNORM) class TestCaptureAPI(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def merged_test_capture_file(self): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_path = str(TEST_FILES_DIR.joinpath('usd/sphere.usda')) image_name = f'sphere.png' image_path = str(OUTPUTS_DIR.joinpath(image_name)) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) vp_window = ui.Window('test_capture_file', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) capture = vp_widget.viewport_api.schedule_capture(FileCapture(image_path)) captured_aovs = await capture.wait_for_result() self.assertEqual(captured_aovs, ['LdrColor']) # Test the frame's metadata is available self.assertIsNotNone(capture.view) self.assertIsNotNone(capture.projection) self.assertEqual(capture.resolution, (TEST_WIDTH, TEST_HEIGHT)) # Test the viewport_handle is also available for usets that self.assertIsNotNone(capture.viewport_handle) compare_images(image_name) vp_widget.destroy() vp_window.destroy() del vp_window async def merged_test_capture_file_with_format(self): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_path = str(TEST_FILES_DIR.joinpath('usd/sphere.usda')) image_name = f'sphere_rle.exr' image_path = str(OUTPUTS_DIR.joinpath(image_name)) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) vp_window = ui.Window('test_capture_file_with_format', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) format_desc = {} format_desc["format"] = "exr" format_desc["compression"] = "rle" capture = vp_widget.viewport_api.schedule_capture(FileCapture(image_path, format_desc=format_desc)) captured_aovs = await capture.wait_for_result() self.assertEqual(captured_aovs, ['LdrColor']) # Test the frame's metadata is available self.assertIsNotNone(capture.view) self.assertIsNotNone(capture.projection) self.assertEqual(capture.resolution, (TEST_WIDTH, TEST_HEIGHT)) # Test the viewport_handle is also available for usets that self.assertIsNotNone(capture.viewport_handle) self.assertIsNotNone(capture.format_desc) # Cannot compare EXR images for testing yet # compare_images(image_name) vp_widget.destroy() vp_window.destroy() del vp_window async def merged_test_capture_bytes_free_func_hdr(self): # 1030: Doesn't have the ability to set render_product_path and this test will fail import omni.hydratexture if not hasattr(omni.hydratexture.IHydraTexture, 'set_render_product_path'): return await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) aov_name = 'HdrColor' image_name = f'cube_{aov_name}.exr' image_path = str(OUTPUTS_DIR.joinpath(image_name)) usd_path = str(TEST_FILES_DIR.joinpath('usd/cube.usda')) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) num_calls = 0 def on_capture_completed(buffer, buffer_size, width, height, format): nonlocal num_calls num_calls = num_calls + 1 self.assertEqual(width, TEST_WIDTH) self.assertEqual(height, TEST_HEIGHT) # Note the RGBA16_SFLOAT format! self.assertEqual(format, ui.TextureFormat.RGBA16_SFLOAT) vp_window = ui.Window('test_capture_bytes_free_func', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) # Edit the RenderProduct to output HdrColor render_product_path = vp_widget.viewport_api.render_product_path if render_product_path[0] != '/': render_product_path = f'/Render/RenderProduct_{render_product_path}' stage = usd_context.get_stage() with Usd.EditContext(stage, stage.GetSessionLayer()): prim = usd_context.get_stage().GetPrimAtPath(render_product_path) self.assertTrue(prim.IsValid()) self.assertTrue(prim.IsA(UsdRender.Product)) product = UsdRender.Product(prim) targets = product.GetOrderedVarsRel().GetForwardedTargets() self.assertEqual(1, len(targets)) prim = usd_context.get_stage().GetPrimAtPath(targets[0]) self.assertTrue(prim.IsValid()) self.assertTrue(prim.IsA(UsdRender.Var)) render_var = UsdRender.Var(prim) value_set = render_var.GetSourceNameAttr().Set(aov_name) self.assertTrue(value_set) # Trigger the texture to update the render, and wait for the change to funnel back to us vp_widget.viewport_api.render_product_path = render_product_path settings_changed = await vp_widget.viewport_api.wait_for_render_settings_change() self.assertTrue(settings_changed) # Now that the settings have changed, so the capture of 'HdrColor' captured_aovs = await vp_widget.viewport_api.schedule_capture(ByteCapture(on_capture_completed, aov_name=aov_name)).wait_for_result() self.assertTrue(aov_name in captured_aovs) # Since we requested one AOV, test that on_capture_completed was only called once # Currently RTX will deliver 'HdrColor' and 'LdrColor' when 'HdrColor' is requested # If that changes these two don't neccessarily need to be tested. self.assertEqual(len(captured_aovs), 1) self.assertEqual(num_calls, 1) captured_aovs = await vp_widget.viewport_api.schedule_capture(FileCapture(image_path, aov_name=aov_name)).wait_for_result() self.assertTrue(aov_name in captured_aovs) # XXX cannot compare EXR # compare_images(image_name) # So test it exists and publish the image self.assertTrue(os.path.exists(image_path)) teamcity_publish_image_artifact(image_path, "results") vp_widget.destroy() vp_window.destroy() del vp_window async def merged_test_capture_bytes_subclass(self): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) usd_path = str(TEST_FILES_DIR.joinpath('usd/cube.usda')) usd_context = omni.usd.get_context() await usd_context.open_stage_async(usd_path) self.assertIsNotNone(usd_context.get_stage()) capture = TestByteCapture(self) vp_window = ui.Window('test_capture_bytes_subclass', width=TEST_WIDTH, height=TEST_HEIGHT, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self.assertIsNotNone(vp_window) with vp_window.frame: vp_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) self.assertIsNotNone(vp_widget) vp_widget.viewport_api.schedule_capture(capture) captured_aovs = await capture.wait_for_result() self.assertEqual(captured_aovs, ['LdrColor']) vp_widget.destroy() vp_window.destroy() del vp_window async def test_3_capture_tests_merged_for_linux(self): try: await self.merged_test_capture_file() await self.wait_n_updates(10) await self.merged_test_capture_bytes_free_func_hdr() await self.wait_n_updates(10) await self.merged_test_capture_bytes_subclass() await self.wait_n_updates(10) await self.merged_test_capture_file_with_format() await self.wait_n_updates(10) finally: await self.finalize_test_no_image()
10,923
Python
41.177606
145
0.656596
omniverse-code/kit/exts/omni.kit.widget.viewport/omni/kit/widget/viewport/tests/test_ray_query.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestRayQuery"] from omni.kit.widget.viewport import ViewportWidget import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import omni.usd from pathlib import Path import carb CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.widget.viewport}/data")).absolute().resolve() TEST_FILES_DIR = CURRENT_PATH.joinpath('tests') USD_FILES_DIR = TEST_FILES_DIR.joinpath('usd') TEST_WIDTH, TEST_HEIGHT = 320, 180 class TestRayQuery(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() await self.linux_gpu_shutdown_workaround() async def linux_gpu_shutdown_workaround(self, usd_context_name : str = ''): await self.wait_n_updates(10) omni.usd.release_all_hydra_engines(omni.usd.get_context(usd_context_name)) await self.wait_n_updates(10) async def open_usd_file(self, filename: str, resolved: bool = False): usd_context = omni.usd.get_context() usd_path = str(USD_FILES_DIR.joinpath(filename) if not resolved else filename) await usd_context.open_stage_async(usd_path) return usd_context async def __test_ray_query(self, camera_path: str): await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) usd_context = await self.open_usd_file('ray_query.usda') self.assertIsNotNone(usd_context.get_stage()) usd_context_stage = usd_context.get_stage() window_flags = omni.ui.WINDOW_FLAGS_NO_COLLAPSE window_flags |= omni.ui.WINDOW_FLAGS_NO_RESIZE window_flags |= omni.ui.WINDOW_FLAGS_NO_CLOSE window_flags |= omni.ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= omni.ui.WINDOW_FLAGS_NO_TITLE_BAR vp_window, viewport_widget = None, None try: vp_window = omni.ui.Window("Viewport", width=TEST_WIDTH, height=TEST_HEIGHT, flags=window_flags) with vp_window.frame: viewport_widget = ViewportWidget(resolution=(TEST_WIDTH, TEST_HEIGHT)) results = [] def query_completed(*args): results.append(args) viewport_api = viewport_widget.viewport_api viewport_api.camera_path = camera_path # 1:1 conform of render and viewport await self.wait_n_updates(5) viewport_api.request_query((193, 123), query_completed) await self.wait_n_updates(15) # test with half height viewport_api.resolution = TEST_WIDTH, TEST_HEIGHT * 0.5 await self.wait_n_updates(5) viewport_api.request_query((193, 78), query_completed) await self.wait_n_updates(15) # test with half width viewport_api.resolution = TEST_WIDTH * 0.5, TEST_HEIGHT await self.wait_n_updates(5) viewport_api.request_query((96, 106), query_completed) await self.wait_n_updates(15) self.assertEqual(len(results), 3) for args in results: self.assertEqual(args[0], "/World/Xform/FG") # Compare integer in a sane range that must be toward the lower-right corner of the object iworld_pos = [int(v) for v in args[1]] self.assertTrue(iworld_pos[0] >= 46 and iworld_pos[0] <= 50) self.assertTrue(iworld_pos[1] >= -50 and iworld_pos[1] <= -46) self.assertTrue(iworld_pos[2] == 0) finally: if viewport_widget: viewport_widget.destroy() viewport_widget = None if vp_window: vp_window.destroy() vp_window = None await self.finalize_test_no_image() async def test_perspective_ray_query(self): '''Test request_query API with a perpective camera''' await self.__test_ray_query("/World/Xform/Camera") async def test_orthographic_ray_query(self): '''Test request_query API with an orthographic camera''' await self.__test_ray_query("/OmniverseKit_Front")
4,631
Python
39.99115
120
0.638523
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/drop_support.py
import os import asyncio import carb.events import carb.input import omni.appwindow import omni.ui as ui class ExternalDragDrop(): def __init__(self, window_name: str, drag_drop_fn: callable): self._window_name = window_name self._drag_drop_fn = drag_drop_fn # subscribe to external drag/drop events app_window = omni.appwindow.get_default_app_window() self._dropsub = app_window.get_window_drop_event_stream().create_subscription_to_pop( self._on_drag_drop_external, name="ExternalDragDrop event", order=0 ) def destroy(self): self._drag_drop_fn = None self._dropsub = None def get_current_mouse_coords(self): app_window = omni.appwindow.get_default_app_window() input = carb.input.acquire_input_interface() dpi_scale = ui.Workspace.get_dpi_scale() pos_x, pos_y = input.get_mouse_coords_pixel(app_window.get_mouse()) return pos_x / dpi_scale, pos_y / dpi_scale def is_window_hovered(self, pos_x, pos_y, window_name): window = ui.Workspace.get_window(window_name) # if window hasn't been drawn yet docked may not be valid, so check dock_id also if not window or not window.visible or ((window.docked or window.dock_id != 0) and not window.is_selected_in_dock()): return False if (pos_x > window.position_x and pos_y > window.position_y and pos_x < window.position_x + window.width and pos_y < window.position_y + window.height ): return True return False def _on_drag_drop_external(self, e: carb.events.IEvent): # need to wait until next frame as otherwise mouse coords can be wrong async def do_drag_drop(): await omni.kit.app.get_app().next_update_async() mouse_x, mouse_y = self.get_current_mouse_coords() if self.is_window_hovered(mouse_x, mouse_y, self._window_name): self._drag_drop_fn(self, list(e.payload['paths'])) asyncio.ensure_future(do_drag_drop()) def expand_payload(self, payload): new_payload = [] for file_path in payload: if os.path.isdir(file_path): for root, subdirs, files in os.walk(file_path): for file in files: new_payload.append(os.path.join(root, file)) else: new_payload.append(file_path) return new_payload
2,498
Python
37.446153
125
0.609287
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/__init__.py
from .drop_support import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/tests/test_drag_drop.py
import os import unittest import threading import carb import asyncio import omni.kit.test import omni.ui as ui import omni.appwindow import omni.client.utils as clientutils from pathlib import Path from omni.kit import ui_test class TestExternalDragDropUtils(omni.kit.test.AsyncTestCase): async def test_external_drag_drop(self): # new stage await omni.usd.get_context().new_stage_async() await ui_test.human_delay(50) # stage event future_test = asyncio.Future() def on_timeout(): nonlocal future_test future_test.set_result(False) carb.log_error(f"stage event omni.usd.StageEventType.OPENED hasn't been received") timeout_timer = threading.Timer(30.0, on_timeout) def on_stage_event(event): if event.type == int(omni.usd.StageEventType.OPENED): nonlocal timeout_timer timeout_timer.cancel() nonlocal future_test future_test.set_result(True) carb.log_info(f"stage event omni.usd.StageEventType.OPENED received") stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(on_stage_event, name="omni.kit.window.drop_support") timeout_timer.start() # get file path extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) file_path = str(Path(extension_path).joinpath("data/tests/4Lights.usda")).replace("\\", "/") # position mouse await ui_test.find("Viewport").click() await ui_test.human_delay() # simulate drag/drop omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [file_path]}) await ui_test.human_delay(50) # wait for stage event OPENED await future_test await ui_test.human_delay(50) # verify root_layer = omni.usd.get_context().get_stage().GetRootLayer() self.assertTrue(clientutils.equal_urls(root_layer.identifier, file_path))
2,103
Python
34.661016
153
0.646695
omniverse-code/kit/exts/omni.kit.window.drop_support/omni/kit/window/drop_support/tests/__init__.py
from .test_drag_drop import *
31
Python
9.666663
29
0.709677
omniverse-code/kit/exts/omni.kit.window.drop_support/docs/README.md
# omni.kit.window.drop_support ## Introduction Library functions to allow drag & drop from outside kit
107
Markdown
12.499998
55
0.757009
omniverse-code/kit/exts/omni.kit.numpy.common/config/extension.toml
[package] title = "Common Types Numpy Bindings" description = "Numpy type bindings for common vector types" readme ="docs/README.md" preview_image = "" version = "0.1.0" [dependencies] "omni.kit.pip_archive" = {} [[python.module]] name = "omni.kit.numpy.common" [python.pipapi] requirements = ["numpy"] [[test]] waiver = "Simple binding extension (carb types to numpy)"
373
TOML
19.777777
59
0.707775
omniverse-code/kit/exts/omni.kit.numpy.common/omni/kit/numpy/common/_numpy_dtypes.pyi
from __future__ import annotations import omni.kit.numpy.common._numpy_dtypes import typing __all__ = [ ]
114
unknown
10.499999
42
0.675439
omniverse-code/kit/exts/omni.kit.numpy.common/omni/kit/numpy/common/__init__.py
__name__ = "Carb Primitive Numpy DTypes" from ._numpy_dtypes import *
71
Python
16.999996
40
0.690141
omniverse-code/kit/exts/omni.kit.numpy.common/docs/README.md
# Usage This extension is used when creating Python Bindings that returns a numpy array of common Carb types (e.g `carb::Float3`). To use this extension, add `"omni.kit.numpy.common" = {}` to the `[dependencies]` section on the `config/extension.toml` file.
261
Markdown
42.66666
126
0.735632
omniverse-code/kit/exts/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from omni.kit.window.popup_dialog import MessageDialog, InputDialog, FormDialog, OptionsDialog, OptionsMenu class DemoApp: def __init__(self): self._window = None self._popups = [] self._cur_popup_index = 0 self._build_ui() def _build_ui(self): window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window("DemoPopup", width=600, height=80, flags=window_flags) with self._window.frame: builders = [ ("Message", self._build_message_popup), ("String Input", self._build_string_input), ("Form Dialog", self._build_form_dialog), ("Options Dialog", self._build_options_dialog), ("Options Menu", self._build_options_menu), ] with ui.VStack(spacing=10): with ui.HStack(height=30): collection = ui.RadioCollection() for i, builder in enumerate(builders): button = ui.RadioButton(text=builder[0], radio_collection=collection, width=120) self._popups.append(builder[1]()) button.set_clicked_fn(lambda i=i, parent=button: self._on_show_popup(i, parent)) ui.Spacer() ui.Spacer() def _build_message_popup(self) -> MessageDialog: #BEGIN-DOC-message-dialog message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." dialog = MessageDialog( title="Message", message=message, ok_handler=lambda dialog: print(f"Message acknowledged"), ) #END-DOC-message-dialog return dialog def _build_string_input(self) -> InputDialog: #BEGIN-DOC-input-dialog dialog = InputDialog( title="String Input", message="Please enter a string value:", pre_label="LDAP Name: ", post_label="@nvidia.com", ok_handler=lambda dialog: print(f"Input accepted: '{dialog.get_value()}'"), ) #END-DOC-input-dialog return dialog def _build_form_dialog(self) -> FormDialog: #BEGIN-DOC-form-dialog field_defs = [ FormDialog.FieldDef("string", "String: ", ui.StringField, "default"), FormDialog.FieldDef("int", "Integer: ", ui.IntField, 1), FormDialog.FieldDef("float", "Float: ", ui.FloatField, 2.0), FormDialog.FieldDef( "tuple", "Tuple: ", lambda **kwargs: ui.MultiFloatField(column_count=3, h_spacing=2, **kwargs), None ), FormDialog.FieldDef("slider", "Slider: ", lambda **kwargs: ui.FloatSlider(min=0, max=10, **kwargs), 3.5), FormDialog.FieldDef("bool", "Boolean: ", ui.CheckBox, True), ] dialog = FormDialog( title="Form Dialog", message="Please enter values for the following fields:", field_defs=field_defs, ok_handler=lambda dialog: print(f"Form accepted: '{dialog.get_values()}'"), ) #END-DOC-form-dialog return dialog def _build_options_dialog(self) -> OptionsDialog: #BEGIN-DOC-options-dialog field_defs = [ OptionsDialog.FieldDef("hard", "Hard place", False), OptionsDialog.FieldDef("harder", "Harder place", True), OptionsDialog.FieldDef("hardest", "Hardest place", False), ] dialog = OptionsDialog( title="Options Dialog", message="Please make your choice:", field_defs=field_defs, width=300, radio_group=True, ok_handler=lambda choice: print(f"Choice: '{dialog.get_choice()}'"), ) #END-DOC-options-dialog return dialog def _build_options_menu(self) -> OptionsMenu: #BEGIN-DOC-options-menu field_defs = [ OptionsMenu.FieldDef("audio", "Audio", None, False), OptionsMenu.FieldDef("materials", "Materials", None, True), OptionsMenu.FieldDef("scripts", "Scripts", None, False), OptionsMenu.FieldDef("textures", "Textures", None, False), OptionsMenu.FieldDef("usd", "USD", None, True), ] menu = OptionsMenu( title="Options Menu", field_defs=field_defs, width=150, value_changed_fn=lambda dialog, name: print(f"Value for '{name}' changed to {dialog.get_value(name)}"), ) #END-DOC-options-menu return menu def _on_show_popup(self, popup_index: int, parent: ui.Widget): self._popups[self._cur_popup_index].hide() self._popups[popup_index].show(offset_x=-1, offset_y=26, parent=parent) self._cur_popup_index = popup_index if __name__ == "__main__": app = DemoApp()
5,387
Python
40.767442
143
0.585112
omniverse-code/kit/exts/omni.kit.window.popup_dialog/config/extension.toml
[package] title = "Simple Popup Dialogs with Input Fields" version = "2.0.16" description = "A variety of simple Popup Dialogs for taking in user inputs" authors = ["NVIDIA"] slackids = ["UQY4RMR3N"] repository = "" keywords = ["kit", "ui"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.window.popup_dialog" [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ] [[python.scriptFolder]] path = "scripts" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", "--/renderer/multiGpu/maxGpuCount=1", "--no-window", ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ] pythonTests.unreliable = [ "*test_ui_layout", # OM-77232 "*test_one_button_layout", # OM-77232 ]
1,019
TOML
20.25
75
0.652601
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/input_dialog.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import omni.kit.app import asyncio from typing import Callable, Any, Optional from .dialog import AbstractDialog, PopupDialog, get_field_value from .style import get_style class InputDialog(PopupDialog): """ A simple popup dialog with an input field and two buttons, OK and Cancel Keyword Args: title (str): Title of popup window. Default None. message (str): Message to display. input_cls (omni.ui.AbstractField): Type of input field specified by class name, e.g. omni.ui.StringField, omni.ui.IntField, omni.ui.CheckBox. Default is omni.ui.StringField. pre_label (str): Text displayed before input field. Default None. post_label (str): Text displayed after input field. Default None. default_value (str): Default value of the input field. warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None. """ def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", input_cls: ui.AbstractField=None, pre_label: str=None, post_label: str=None, default_value: str=None, warning_message: Optional[str]=None ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, modal=True, warning_message=warning_message ) with self._window.frame: with ui.VStack(): self._build_warning_message() self._widget = InputWidget( message=message, input_cls=input_cls or ui.StringField, pre_label=pre_label, post_label=post_label, default_value=default_value) self._build_ok_cancel_buttons() self.hide() def get_value(self) -> Any: """ Returns field value. Returns: Any, e.g. one of [str, int, float, bool] """ if self._widget: return self._widget.get_value() return None def destroy(self): if self._widget: self._widget.destroy() self._widget = None super().destroy() class InputWidget: """ A simple widget with an input field. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): Message to display. input_cls (omni.ui.AbstractField): Class of the input field, e.g. omni.ui.StringField, omni.ui.IntField, omni.ui.CheckBox. Default is omni.ui.StringField. pre_label (str): Text displayed before input field. Default None. post_label (str): Text displayed after input field. Default None. default_value (str): Default value of the input field. """ def __init__(self, message: str = None, input_cls: ui.AbstractField = None, pre_label: str = None, post_label: str = None, default_value: Any = None ): self._input = None self._build_ui(message, input_cls or ui.StringField, pre_label, post_label, default_value) def _build_ui(self, message: str, input_cls: ui.AbstractField, pre_label: str, post_label: str, default_value: Any, ): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=6): if message: ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message") with ui.HStack(height=0): input_width = 100 if pre_label: ui.Label(pre_label, style_type_name_override="Field.Label", name="prefix") input_width -= 30 if post_label: input_width -= 30 self._input = input_cls( width=ui.Percent(input_width), height=20, style_type_name_override="Input" ) if default_value: self._input.model.set_value(default_value) # OM-95817: Wait a frame to make sure it focus correctly async def focus_field(): await omni.kit.app.get_app().next_update_async() if self._input: self._input.focus_keyboard() asyncio.ensure_future(focus_field()) if post_label: ui.Label(post_label, style_type_name_override="Field.Label", name="postfix") def get_value(self) -> Any: """ Returns value of input field. Returns: Any """ if self._input: return get_field_value(self._input) return None def destroy(self): self._input = None self._window = None
5,888
Python
35.80625
121
0.573709
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/message_dialog.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from typing import Callable, Optional from .dialog import AbstractDialog, PopupDialog from .style import get_style class MessageDialog(PopupDialog): """ This simplest of all popup dialogs displays a confirmation message before executing an action. Keyword Args: title (str): Title of popup window. Default None. message (str): The displayed message. Default ''. disable_cancel_button (bool): If True, then don't display 'Cancel' button. Default False. warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None. """ def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str="", title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", disable_okay_button: bool=False, disable_cancel_button: bool=False, warning_message: Optional[str]=None, ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, modal=True, warning_message=warning_message, ) with self._window.frame: with ui.VStack(): self._widget = MessageWidget(message) self._build_warning_message() self._build_ok_cancel_buttons(disable_okay_button=disable_okay_button, disable_cancel_button=disable_cancel_button) self.hide() def set_message(self, message: str): """ Updates the message string. Args: message (str): The message string. """ if self._widget: self._widget.set_message(message) def destroy(self): if self._widget: self._widget.destroy() self._widget = None super().destroy() class MessageWidget: """ This widget displays a custom message. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): The message string """ def __init__(self, message: str = ""): self._message_label = None self._build_ui(message) def _build_ui(self, message: str): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=6): with ui.HStack(height=0): self._message_label = ui.Label(message, word_wrap=True, style_type_name_override="Message") def set_message(self, message: str): """ Updates the message string. Args: message (str): The message string. """ self._message_label.text = message def destroy(self): self._message_label = None
3,552
Python
31.898148
131
0.619088
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/style.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from pathlib import Path try: THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") except Exception: THEME = None finally: THEME = THEME or "NvidiaDark" CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"icons/{THEME}") def get_style(): if THEME == "NvidiaLight": style = { "Button": {"background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF}, "Button.Label": {"color": 0xFF535354}, "Dialog": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin_width": 6}, "Label": {"background_color": 0xFFC9C9C9, "color": 0xFF535354}, "Input": { "background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF, "color": 0xFF535354, "alignment": ui.Alignment.LEFT_CENTER, }, "Rectangle": {"background_color": 0xFFC9C9C9, "border_radius": 3}, "Background": {"background_color": 0xFFE0E0E0, "border_radius": 2, "border_width": 0.5, "border_color": 0x55ADAC9F}, "Background::header": {"background_color": 0xFF535354, "corner_flag": ui.CornerFlag.TOP, "margin": 0}, "Dialog": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 10}, "Message": { "background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 0, "alignment": ui.Alignment.LEFT_CENTER, "margin": 0, }, "Button": {"background_color": 0xFFC9C9C9, "selected_color": 0xFFACACAF, "margin": 0}, "Button.Label": {"color": 0xFF535354}, "Field": {"background_color": 0xFF535354, "color": 0xFFD6D6D6}, "Field:pressed": {"background_color": 0xFF535354, "color": 0xFFD6D6D6}, "Field:selected": {"background_color": 0xFFBEBBAE, "color": 0xFFD6D6D6}, "Field.Label": {"background_color": 0xFFC9C9C9, "color": 0xFF535354, "margin": 0}, "Field.Label::title": {"color": 0xFFD6D6D6}, "Field.Label::prefix": {"alignment": ui.Alignment.RIGHT_CENTER}, "Field.Label::postfix": {"alignment": ui.Alignment.LEFT_CENTER}, "Field.Label::reset_all": {"color": 0xFFB0703B, "alignment": ui.Alignment.RIGHT_CENTER}, "Input": { "background_color": 0xFF535354, "color": 0xFFD6D6D6, "alignment": ui.Alignment.LEFT_CENTER, "margin_height": 0, }, "Menu.Item": {"margin_width": 6, "margin_height": 2}, "Menu.Header": {"margin": 6}, "Menu.CheckBox": {"background_color": 0xFF535354, "color": 0xFFD6D6D6}, "Menu.Separator": {"color": 0x889E9E9E}, "Options.Item": {"margin_width": 6, "margin_height": 0}, "Options.CheckBox": {"background_color": 0x0, "color": 0xFF23211F}, "Options.RadioButton": {"background_color": 0x0, "color": 0xFF9E9E9E}, "Rectangle.Warning": {"background_color": 0x440000FF, "border_radius": 3, "margin": 10}, } else: style = { "BorderedBackground": {"background_color": 0x0, "border_width": .5, "border_color": 0x55ADAC9F}, "Background": {"background_color": 0x0}, "Background::header": {"background_color": 0xFF23211F, "corner_flag": ui.CornerFlag.TOP, "margin": 0}, "Dialog": {"background_color": 0x0, "color": 0xFF9E9E9E, "margin": 10}, "Message": { "background_color": 0x0, "color": 0xFF9E9E9E, "margin": 0, "alignment": ui.Alignment.LEFT_CENTER, "margin": 0, }, "Button": {"background_color": 0xFF23211F, "selected_color": 0xFF8A8777, "margin": 0}, "Button.Label": {"color": 0xFF9E9E9E}, "Field.Label": {"background_color": 0x0, "color": 0xFF9E9E9E, "margin": 0}, "Field.Label::prefix": {"alignment": ui.Alignment.RIGHT_CENTER}, "Field.Label::postfix": {"alignment": ui.Alignment.LEFT_CENTER}, "Field.Label::reset_all": {"color": 0xFFB0703B, "alignment": ui.Alignment.RIGHT_CENTER}, "Input": { "background_color": 0xCC23211F, "color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER, "margin_height": 0, }, "Menu.Item": {"margin_width": 6, "margin_height": 2}, "Menu.Header": {"margin": 6}, "Menu.CheckBox": {"background_color": 0xDD9E9E9E, "color": 0xFF23211F}, "Menu.Separator": {"color": 0x889E9E9E}, "Options.Item": {"margin_width": 6, "margin_height": 0}, "Options.CheckBox": {"background_color": 0xDD9E9E9E, "color": 0xFF23211F}, "Options.RadioButton": {"background_color": 0x0, "color": 0xFF9E9E9E}, "Rectangle.Warning": {"background_color": 0x440000FF, "border_radius": 3, "margin": 10}, } return style
5,578
Python
51.140186
128
0.573682
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """ A set of simple popup dialogs with optional input fields and two buttons, OK and Cancel. Example: .. code-block:: python dialog = InputDialog( width=450, pre_label="prefix", post_label="postfix", ok_handler=on_okay, cancel_handler=on_cancel, ) """ __all__ = [ 'MessageDialog', 'MessageWidget', 'InputDialog', 'InputWidget', 'FormDialog', 'FormWidget', 'OptionsDialog', 'OptionsWidget', 'OptionsMenu', 'OptionsMenuWidget', 'PopupDialog' ] from .message_dialog import MessageDialog, MessageWidget from .input_dialog import InputDialog, InputWidget from .form_dialog import FormDialog, FormWidget from .options_dialog import OptionsDialog, OptionsWidget from .options_menu import OptionsMenu, OptionsMenuWidget from .dialog import PopupDialog
1,255
Python
30.399999
88
0.738645
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/dialog.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import carb.input import omni.ui as ui from typing import Callable, Union, Optional from .style import get_style class AbstractDialog: pass class PopupDialog(AbstractDialog): """ Base class for a simple popup dialog with two primary buttons, OK and Cancel.""" WINDOW_FLAGS = ui.WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS |= ui.WINDOW_FLAGS_POPUP WINDOW_FLAGS |= ui.WINDOW_FLAGS_NO_SCROLLBAR def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", hide_title_bar: bool=False, modal: bool=False, warning_message: Optional[str]=None, ): """ Inherited args from the base class. Keyword Args: width (int): Window width. Default 400. title (str): Title to display. Default None. ok_handler (Callable): Function to invoke when Ok button clicked. Function signature: void okay_handler(dialog: PopupDialog) cancel_handler (Callable): Function to invoke when Cancel button clicked. Function signature: void cancel_handler(dialog: PopupDialog) ok_label (str): Alternative text to display on 'Accept' button. Default 'Ok'. cancel_label (str): Alternative text to display on 'Cancel' button. Default 'Cancel'. warning_message (Optional[str]): Warning message that will displayed in red with the warning glyph. Default None. parent (omni.ui.Widget): OBSOLETE. """ super().__init__() self._title = title self._click_okay_handler = ok_handler self._click_cancel_handler = cancel_handler self._okay_label = ok_label self._okay_button = None self._cancel_label = cancel_label self._cancel_button = None self._warning_message = warning_message self._modal = modal self._width = width self._hide_title_bar = hide_title_bar self._key_functions = { int(carb.input.KeyboardInput.ENTER): self._on_okay, int(carb.input.KeyboardInput.ESCAPE): self._on_cancel } self._build_window() def __del__(self): self.destroy() def show(self, offset_x: int = 0, offset_y: int = 0, parent: ui.Widget = None, recreate_window: bool = False): """ Shows this dialog, optionally offset from the parent widget, if any. Keyword Args: offset_x (int): X offset. Default 0. offset_y (int): Y offset. Default 0. parent (ui.Widget): Offset from this parent widget. Default None. recreate_window (bool): Recreate popup window. Default False. """ if recreate_window: # OM-42020: Always recreate window. # Recreate to follow the parent window type (external window or main window) to make position right # TODO: Only recreate when parent window external status changed. But there is no such notification now. self._window = None self._build_window() if parent: self._window.position_x = parent.screen_position_x + offset_x self._window.position_y = parent.screen_position_y + offset_y elif offset_x != 0 or offset_y != 0: self._window.position_x = offset_x self._window.position_y = offset_y self._window.set_key_pressed_fn(self._on_key_pressed) self._window.visible = True def hide(self): """Hides this dialog.""" self._window.visible = False @property def position_x(self): return self._window.position_x @property def position_y(self): return self._window.position_y @property def window(self): return self._window def _build_window(self): window_flags = self.WINDOW_FLAGS if not self._title or self._hide_title_bar: window_flags |= ui.WINDOW_FLAGS_NO_TITLE_BAR if self._modal: window_flags |= ui.WINDOW_FLAGS_MODAL self._window = ui.Window(self._title or "", width=self._width, height=0, flags=window_flags) self._build_widgets() def _build_widgets(self): pass def _cancel_handler(self, dialog): self.hide() def _ok_handler(self, dialog): pass def _build_ok_cancel_buttons(self, disable_okay_button: bool = False, disable_cancel_button: bool = False): if disable_okay_button and disable_cancel_button: return with ui.HStack(height=20, spacing=4): ui.Spacer() if not disable_okay_button: self._okay_button = ui.Button(self._okay_label, width=100, clicked_fn=self._on_okay) if not disable_cancel_button: self._cancel_button = ui.Button(self._cancel_label, width=100, clicked_fn=self._on_cancel) ui.Spacer() def _build_warning_message(self, glyph_width=50, glyph_height=100): if not self._warning_message: return with ui.ZStack(style=get_style(), height=0): with ui.HStack(style={"margin": 15}): ui.Image( "resources/glyphs/Warning_Log.svg", width=glyph_width, height=glyph_height, alignment=ui.Alignment.CENTER ) ui.Label(self._warning_message, word_wrap=True, style_type_name_override="Message") ui.Rectangle(style_type_name_override="Rectangle.Warning") def _on_okay(self): if self._click_okay_handler: self._click_okay_handler(self) def _on_cancel(self): if self._click_cancel_handler: self._click_cancel_handler(self) else: self.hide() def _on_key_pressed(self, key, mod, pressed): if not pressed: return func = self._key_functions.get(key) if func and mod in (0, ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD): func() def set_okay_clicked_fn(self, ok_handler: Callable[[AbstractDialog], None]): """ Sets function to invoke when Okay button is clicked. Args: ok_handler (Callable): Callback with signature: void okay_handler(dialog: PopupDialog) """ self._click_okay_handler = ok_handler def set_cancel_clicked_fn(self, cancel_handler: Callable[[AbstractDialog], None]): """ Sets function to invoke when Cancel button is clicked. Args: cancel_handler (Callable): Callback with signature: void cancel_handler(dialog: PopupDialog) """ self._click_cancel_handler = cancel_handler def destroy(self): self._window = None self._click_okay_handler = None self._click_cancel_handler = None self._key_functions = None self._okay_button = None self._cancel_button = None def get_field_value(field: ui.AbstractField) -> Union[str, int, float, bool]: if not field: return None if isinstance(field, ui.StringField): return field.model.get_value_as_string() elif type(field) in [ui.IntField, ui.IntDrag, ui.IntSlider]: return field.model.get_value_as_int() elif type(field) in [ui.FloatField, ui.FloatDrag, ui.FloatSlider]: return field.model.get_value_as_float() elif isinstance(field, ui.CheckBox): return field.model.get_value_as_bool() else: # TODO: Retrieve values for MultiField return None
8,192
Python
34.777292
125
0.613403
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/options_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from typing import List, Dict, Callable from collections import namedtuple from .dialog import AbstractDialog, PopupDialog from .options_dialog import OptionsWidget from .style import get_style class OptionsMenu(PopupDialog): """ A simple checkbox menu with a set of options Keyword Args: title (str): Title of this menu. Default None. field_defs ([OptionsMenu.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. Note: OptionsMenu.FieldDef: A namedtuple of (name, label, glyph, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", None, True). """ FieldDef = namedtuple("OptionsMenuFieldDef", "name label glyph default") def __init__( self, width: int=400, parent: ui.Widget=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", field_defs: List[FieldDef]=None, value_changed_fn: Callable=None, ): self._widget = OptionsMenuWidget(title, field_defs, value_changed_fn, build_ui=False) super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, hide_title_bar=True, ) def get_values(self) -> dict: """ Returns all values in a dictionary. Returns: dict """ if self._widget: return self._widget.get_values() return {} def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if self._widget: return self._widget.get_value(name) return False def set_value(self, name: str, value: bool): """ Sets the value of the named field. Args: name (str): Name of the field. value (bool): New value """ if self._widget: self._widget.set_value(name, value) return None def reset_values(self): """Resets all values to their defaults.""" if self._widget: self._widget.reset_values() return None def destroy(self): """Destructor""" if self._widget: self._widget.destroy() self._widget = None super().destroy() def _build_widgets(self): with self._window.frame: with ui.VStack(): self._widget.build_ui() self.hide() class OptionsMenuWidget: """ A simple checkbox widget with a set of options. As opposed to the menu class, the widget can be combined with other widget types in the same window. Keyword Args: title (str): Title of this menu. Default None. field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. build_ui (bool): Build ui when created. Note: OptionsMenu.FieldDef: A namedtuple of (name, label, glyph, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", None, True). """ def __init__(self, title: str = None, field_defs: List[OptionsMenu.FieldDef] = [], value_changed_fn: Callable = None, build_ui: bool = True, ): self._field_defs = field_defs self._field_models: Dict[str, ui.AbstractValueModel] = {} for field in field_defs: self._field_models[field.name] = ui.SimpleBoolModel(field.default) self._fields: Dict[str, ui.Widget] = {} self._title = title self._value_changed_fn = value_changed_fn if build_ui: self.build_ui() def build_ui(self): with ui.ZStack(height=0, style=get_style()): ui.Rectangle(style_type_name_override="BorderedBackground") with ui.VStack(): with ui.ZStack(height=0): ui.Rectangle(name="header", style_type_name_override="Background") with ui.HStack(style_type_name_override="Menu.Header"): if self._title: ui.Label(self._title, width=0, name="title", style_type_name_override="Field.Label") ui.Spacer() label = ui.Label( "Reset All", width=0, name="reset_all", style_type_name_override="Field.Label" ) ui.Spacer(width=6) label.set_mouse_pressed_fn(lambda x, y, b, _: self.reset_values()) ui.Spacer(height=4) for field_def in self._field_defs: with ui.HStack(height=20, style_type_name_override="Menu.Item"): check_box = ui.CheckBox(model=self._field_models[field_def.name], width=20, style_type_name_override="Menu.CheckBox") # check_box.model.set_value(field_def.default) check_box.model.add_value_changed_fn( lambda _, name=field_def.name: self._value_changed_fn(self, name) ) ui.Spacer(width=2) ui.Label(field_def.label, width=0, style_type_name_override="Field.Label") self._fields[field_def.name] = check_box ui.Spacer(height=4) def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if name and name in self._field_models: model = self._field_models[name] return model.get_value_as_bool() return False def get_values(self) -> dict: """ Returns all values in a dictionary. Returns: dict """ options = {} for name, model in self._field_models.items(): options[name] = model.get_value_as_bool() return options def set_value(self, name: str, value: bool): """ Sets the value of the named field. Args: name (str): Name of the field. value (bool): New value """ if name and name in self._field_models: model = self._field_models[name] model.set_value(value) def reset_values(self): """Resets all values to their defaults.""" for field_def in self._field_defs: model = self._field_models[field_def.name] model.set_value(field_def.default) def destroy(self): self._field_defs = None self._fields.clear() self._field_models.clear()
7,633
Python
32.191304
141
0.562688
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/options_dialog.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from typing import List, Dict, Callable, Optional from collections import namedtuple from .dialog import AbstractDialog, PopupDialog from .style import get_style, ICON_PATH class OptionsDialog(PopupDialog): """ A simple checkbox dialog with a set options and two buttons, OK and Cancel Keyword Args: title (str): Title of popup window. Default None. message (str): Message string. field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. radio_group (bool): If True, then only one option can be selected at a time. Note: OptionsDialog.FieldDef: A namedtuple of (name, label, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", True). """ FieldDef = namedtuple("OptionsDialogFieldDef", "name label default") def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", field_defs: List[FieldDef]=None, value_changed_fn: Callable=None, radio_group: bool=False, ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, hide_title_bar=True, modal=True ) with self._window.frame: with ui.VStack(): self._widget = OptionsWidget(message, field_defs, value_changed_fn, radio_group) self._build_ok_cancel_buttons() self.hide() def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if self._widget: return self._widget.get_value(name) return None def get_values(self) -> Dict: """ Returns all values in a dictionary. Returns: Dict """ if self._widget: return self._widget.get_values() return {} def get_choice(self) -> str: """ Returns name of chosen option. Returns: str """ if self._widget: return self._widget.get_choice() return None def destroy(self): if self._widget: self._widget.destroy() self._widget = None super().destroy() class OptionsWidget: """ A simple checkbox widget with a set options. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): Message string. field_defs ([OptionsDialog.FieldDef]): List of FieldDefs. Default []. value_changed_fn (Callable): This callback is triggered on any value change. radio_group (bool): If True, then only one option can be selected at a time. Note: OptionsDialog.FieldDef: A namedtuple of (name, label, default) for describing the options field, e.g. OptionsDialog.FieldDef("option", "Option", True). """ def __init__(self, message: str = None, field_defs: List[OptionsDialog.FieldDef] = [], value_changed_fn: Callable = None, radio_group: bool = False ): self._field_defs = field_defs self._radio_group = ui.RadioCollection() if radio_group else None self._fields: Dict[str, ui.Widget] = {} self._build_ui(message, field_defs, value_changed_fn, self._radio_group) def _build_ui(self, message: str, field_defs: List[OptionsDialog.FieldDef], value_changed_fn: Callable, radio_group: Optional[ui.RadioCollection]): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=0): if message: ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message") for field_def in field_defs: with ui.HStack(): ui.Spacer(width=30) with ui.HStack(height=20, style_type_name_override="Options.Item"): if radio_group: icon_style = { "image_url": f"{ICON_PATH}/radio_off.svg", ":checked": {"image_url": f"{ICON_PATH}/radio_on.svg"}, } field = ui.RadioButton( radio_collection=radio_group, width=26, height=26, style=icon_style, style_type_name_override="Options.RadioButton", ) else: field = ui.CheckBox(width=20, style_type_name_override="Options.CheckBox") field.model.set_value(field_def.default) ui.Spacer(width=2) ui.Label(field_def.label, width=0, style_type_name_override="Field.Label") self._fields[field_def.name] = field ui.Spacer() #ui.Spacer(height=4) def get_values(self) -> dict: """ Returns all values in a dictionary. Returns: dict """ options = {} for name, field in self._fields.items(): options[name] = field.checked if isinstance(field, ui.RadioButton) else field.model.get_value_as_bool() return options def get_value(self, name: str) -> bool: """ Returns value of the named field. Args: name (str): Name of the field. Returns: bool """ if name and name in self._fields: field = self._fields[name] return field.checked if isinstance(field, ui.RadioButton) else field.model.get_value_as_bool() return None def get_choice(self) -> str: """ Returns name of chosen option. Returns: str """ if self._radio_group: choice = self._radio_group.model.get_value_as_int() return self._field_defs[choice].name return None def destroy(self): self._field_defs = None self._fields.clear() self._radio_group = None
7,428
Python
33.235023
151
0.551158
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/form_dialog.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['FormDialog', 'FormWidget'] from omni.kit.async_engine import run_coroutine import omni.ui as ui import asyncio from typing import List, Union, Callable from collections import namedtuple from .dialog import AbstractDialog, PopupDialog, get_field_value from .style import get_style class FormDialog(PopupDialog): """ A simple popup dialog with a set of input fields and two buttons, OK and Cancel Keyword Args: title (str): Title of popup window. Default None. message (str): Message string. field_defs ([FormDialog.FieldDef]): List of FieldDefs. Default []. input_width (int): OBSOLETE. Note: FormDialog.FieldDef: A namedtuple of (name, label, type, default value) for describing the input field, e.g. FormDialog.FieldDef("name", "Name: ", omni.ui.StringField, "Bob"). """ FieldDef = namedtuple("FormDialogFieldDef", "name label type default focused", defaults=[False]) def __init__( self, width: int=400, parent: ui.Widget=None, # OBSOLETE message: str=None, title: str=None, ok_handler: Callable[[AbstractDialog], None]=None, cancel_handler: Callable[[AbstractDialog], None]=None, ok_label: str="Ok", cancel_label: str="Cancel", field_defs: List[FieldDef]=None, input_width: int=250 # OBSOLETE ): super().__init__( width=width, title=title, ok_handler=ok_handler, cancel_handler=cancel_handler, ok_label=ok_label, cancel_label=cancel_label, modal=True ) with self._window.frame: with ui.VStack(style=get_style(), style_type_name_override="Dialog"): self._widget = FormWidget(message, field_defs) self._build_ok_cancel_buttons() self.hide() def show(self, offset_x: int = 0, offset_y: int = 0, parent: ui.Widget = None): """ Shows this dialog, optionally offset from the parent widget, if any. Keyword Args: offset_x (int): X offset. Default 0. offset_y (int): Y offset. Default 0. parent (ui.Widget): Offset from this parent widget. Default None. """ # focus on show self._widget.focus() super().show(offset_x=offset_x, offset_y=offset_y, parent=parent) def get_field(self, name: str) -> ui.AbstractField: """ Returns widget corresponding to named field. Args: name (str): Name of the field. Returns: omni.ui.AbstractField """ if self._widget: return self._widget.get_field(name) return None def get_value(self, name: str) -> Union[str, int, float, bool]: """ Returns value of the named field. Args: name (str): Name of the field. Returns: Union[str, int, float, bool] Note: Doesn't currently return MultiFields correctly. """ if self._widget: return self._widget.get_value(name) return None def get_values(self) -> dict: """ Returns all values in a dict. Args: name (str): Name of the field. Returns: dict Note: Doesn't currently return MultiFields correctly. """ if self._widget: return self._widget.get_values() return {} def reset_values(self): """Resets all values to their defaults.""" if self._widget: return self._widget.reset_values() def destroy(self): """Destructor""" if self._widget: self._widget.destroy() self._widget = None super().destroy() class FormWidget: """ A simple form widget with a set of input fields. As opposed to the dialog class, the widget can be combined with other widget types in the same window. Keyword Args: message (str): Message string. field_defs ([FormDialog.FieldDef]): List of FieldDefs. Default []. Note: FormDialog.FieldDef: A namedtuple of (name, label, type, default value) for describing the input field, e.g. FormDialog.FieldDef("name", "Name: ", omni.ui.StringField, "Bob"). """ def __init__(self, message: str = None, field_defs: List[FormDialog.FieldDef] = []): self._field_defs = field_defs self._fields = {} self._build_ui(message, field_defs) def _build_ui(self, message: str, field_defs: List[FormDialog.FieldDef]): with ui.ZStack(style=get_style()): ui.Rectangle(style_type_name_override="Background") with ui.VStack(style_type_name_override="Dialog", spacing=6): if message: ui.Label(message, height=20, word_wrap=True, style_type_name_override="Message") for field_def in field_defs: with ui.HStack(height=0): ui.Label(field_def.label, style_type_name_override="Field.Label", name="prefix") field = field_def.type(width=ui.Percent(70), height=20, style_type_name_override="Field") if "set_value" in dir(field.model): field.model.set_value(field_def.default) self._fields[field_def.name] = field def focus(self) -> None: """Focus fields for the current widget.""" # had to delay focus keyboard for one frame async def delay_focus(field): import omni.kit.app await omni.kit.app.get_app().next_update_async() field.focus_keyboard() # OM-80009: Add ability to focus an input field for form dialog; # When multiple fields are set to focused, then the last field will be the # actual focused field. for field_def in self._field_defs: if field_def.focused: field = self._fields[field_def.name] run_coroutine(delay_focus(field)) def get_field(self, name: str) -> ui.AbstractField: """ Returns widget corresponding to named field. Args: name (str): Name of the field. Returns: omni.ui.AbstractField """ if name and name in self._fields: return self._fields[name] return None def get_value(self, name: str) -> Union[str, int, float, bool]: """ Returns value of the named field. Args: name (str): Name of the field. Returns: Union[str, int, float, bool] Note: Doesn't currently return MultiFields correctly. """ if name and name in self._fields: field = self._fields[name] return get_field_value(field) return None def get_values(self) -> dict: """ Returns all values in a dict. Args: name (str): Name of the field. Returns: dict Note: Doesn't currently return MultiFields correctly. """ return {name: get_field_value(field) for name, field in self._fields.items()} def reset_values(self): """Resets all values to their defaults.""" for field_def in self._field_defs: if field_def.name in self._fields: field = self._fields[field_def.name] if "set_value" in dir(field.model): field.model.set_value(field_def.default) def destroy(self): self._field_defs = None self._fields.clear()
8,184
Python
30.972656
113
0.577713
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_input_dialog.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..input_dialog import InputDialog, InputWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestInputDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: InputWidget( message="Please enter a username:", pre_label="LDAP Name: ", post_label="@nvidia.com", default_value="user", ) await omni.kit.app.get_app().next_update_async() # Add a threshold for the focused field is not stable. await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="input_dialog.png", threshold=25) async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = InputDialog( message="Please enter a string value:", pre_label="LDAP Name: ", post_label="@nvidia.com", ok_handler=mock_okay_handler, ) under_test.show() under_test._on_okay() await omni.kit.app.get_app().next_update_async() mock_okay_handler.assert_called_once() async def test_get_field_value(self): """Test that get_value returns the value of the input field""" under_test = InputDialog( message="Please enter a string value:", pre_label="LDAP Name: ", post_label="@nvidia.com", default_value="user", ) self.assertEqual("user", under_test.get_value())
2,503
Python
36.373134
119
0.644826
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_menu.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import unittest import asyncio import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..options_menu import OptionsMenu, OptionsMenuWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestOptionsMenu(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ OptionsMenu.FieldDef("audio", "Audio", None, False), OptionsMenu.FieldDef("materials", "Materials", None, True), OptionsMenu.FieldDef("scripts", "Scripts", None, False), OptionsMenu.FieldDef("textures", "Textures", None, False), OptionsMenu.FieldDef("usd", "USD", None, True), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: OptionsMenuWidget( title="Options", field_defs=self._field_defs, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_menu.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_value_changed_fn = Mock() under_test = OptionsMenu( title="Options", field_defs=self._field_defs, value_changed_fn=mock_value_changed_fn, ) under_test.show() self.assertEqual(under_test.get_value('usd'), True) under_test.destroy()
2,415
Python
37.349206
105
0.662112
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_message_dialog.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..message_dialog import MessageWidget, MessageDialog CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestMessageDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_message_widget(self): """Testing the look of message widget""" window = await self.create_test_window() with window.frame: under_test = MessageWidget() under_test.set_message(self._message) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="message_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_messgae_dialog(self): """Testing the look of message dialog""" mock_cancel_handler = Mock() under_test = MessageDialog(title="Message", cancel_handler=mock_cancel_handler,) under_test.set_message("Hello World") under_test.show() await omni.kit.app.get_app().next_update_async() under_test._on_cancel() mock_cancel_handler.assert_called_once() under_test.destroy()
2,155
Python
41.274509
149
0.703016
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_form_dialog.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.ui as ui import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..form_dialog import FormDialog, FormWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestFormDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ FormDialog.FieldDef("string", "String: ", ui.StringField, "default"), FormDialog.FieldDef("int", "Integer: ", ui.IntField, 1), FormDialog.FieldDef("float", "Float: ", ui.FloatField, 2.0), FormDialog.FieldDef( "tuple", "Tuple: ", lambda **kwargs: ui.MultiFloatField(column_count=3, h_spacing=2, **kwargs), None ), FormDialog.FieldDef("slider", "Slider: ", lambda **kwargs: ui.FloatSlider(min=0, max=10, **kwargs), 3.5), FormDialog.FieldDef("bool", "Boolean: ", ui.CheckBox, True), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: FormWidget( message="Test fields:", field_defs=self._field_defs, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="form_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ok_handler=mock_okay_handler, ) under_test.show() under_test._on_okay() await omni.kit.app.get_app().next_update_async() mock_okay_handler.assert_called_once() under_test.destroy() async def test_get_field_value(self): """Test that get_value returns the value of the named field""" under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ) for field in self._field_defs: name, label, _, default_value, focused = field self.assertEqual(default_value, under_test.get_value(name)) under_test.destroy() async def test_reset_dialog_value(self): """Test reset dialog value""" under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ) string_field = under_test.get_field("string") string_field.model.set_value("test") self.assertEqual(under_test.get_value("string"), "test") under_test.reset_values() self.assertEqual(under_test.get_value("string"), "default") under_test.destroy()
3,641
Python
39.021978
118
0.629223
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_dialog.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import unittest import asyncio import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..options_dialog import OptionsDialog, OptionsWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestOptionsDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ OptionsDialog.FieldDef("hard", "Hard place", False), OptionsDialog.FieldDef("harder", "Harder place", True), OptionsDialog.FieldDef("hardest", "Hardest place", False), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: OptionsWidget( message="Please make your choice:", field_defs=self._field_defs, radio_group=False, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = OptionsDialog( message="Please make your choice:", field_defs=self._field_defs, width=300, radio_group=False, ok_handler=mock_okay_handler, ) under_test.show() await asyncio.sleep(1) under_test._on_okay() mock_okay_handler.assert_called_once() # TODO: # self.assertEqual(under_test.get_choice(), 'harder') under_test.destroy()
2,523
Python
36.117647
107
0.653983
omniverse-code/kit/exts/omni.kit.window.popup_dialog/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [2.0.16] - 2023-01-31 ### Fixed - OM-79359: Ensure imput dialog auto focus when it has default value ## [2.0.15] - 2022-12-12 ### Fixed - Reverts popup flag, otherwise cannot click away the dialog ## [2.0.14] - 2022-12-08 ### Fixed - Removes popup flag from core dialog, which causes drawing issues when dialogs collide ## [2.0.13] - 2022-11-30 ### Fixed - Centre the okay or cancel button when either or both are enabled. ## [2.0.12] - 2022-11-17 ### Changes - Updated doc. ## [2.0.11] - 2022-11-04 ### Changes - Added warning_message kwarg to base dialog class, and ui build for the warning message. ## [2.0.10] - 2022-08-23 ### Changes - Added set_cancel_clicked_fn to base dialog class. ## [2.0.9] - 2022-07-06 ### Changes - Added title bar. ## [2.0.8] - 2022-05-26 ### Changes - Updated styling ## [2.0.7] - 2022-04-06 ### Changes - Fixes Filepicker delete items dialog. ## [2.0.6] - 2022-03-31 ### Changes - Added unittests and created separate widgets and dialogs. ## [2.0.5] - 2021-11-01 ### Changes - Added set_value method to programmatically set an options menu value. ## [2.0.4] - 2021-11-01 ### Changes - Add method to MessageDialog for updating the message text. ## [2.0.3] - 2021-09-07 ### Changes - Makes all dialog windows modal. - Option to hide Okay button. - Better control of window placement when showing it. ## [2.0.2] - 2021-06-29 ### Changes - Binds ENTER key to Okay button, and ESC key to Cancel button. ## [2.0.1] - 2021-06-07 ### Changes - More thorough destruction of class instances upon shutdown. ## [2.0.0] - 2021-05-05 ### Changes - Update `__init__` of the popup dialog to be explicit in supported arguments - Renamed click_okay_handler and click_cancel_handler to ok_handler and cancel_handler - Added support for `Enter` and `Esc` keys. - Renamed okay_label to ok_label ## [1.0.1] - 2021-02-10 ### Changes - Updated StyleUI handling ## [1.0.0] - 2020-10-29 ### Added - Ported OptionsMenu from content browser - New OptionsDialog derived from OptionsMenu ## [0.1.0] - 2020-09-24 ### Added - Initial commit to master.
2,172
Markdown
23.41573
89
0.680018
omniverse-code/kit/exts/omni.kit.window.popup_dialog/docs/Overview.md
# Overview A set of simple Popup Dialogs for passing user inputs. All of these dialogs subclass from the base PopupDialog, which provides OK and Cancel buttons. The user is able to re-label these buttons as well as associate callbacks that execute upon being clicked. Why you should use the dialogs in this extension: * Avoid duplicating UI code that you then have to maintain. * Re-use dialogs that have standard look and feel to keep a consistent experience across the app. * Inherit future improvements. ## Form Dialog A form dialog can display a mixed set of input types. ![](form_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-form-dialog end-before: END-DOC-form-dialog dedent: 8 --- ``` ## Input Dialog An input dialog allows one input field. ![](input_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-input-dialog end-before: END-DOC-input-dialog dedent: 8 --- ``` ## Message Dialog A message dialog is the simplest of all popup dialogs; it displays a confirmation message before executing some action. ![](message_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-message-dialog end-before: END-DOC-message-dialog dedent: 8 --- ``` ## Options Dialog An options dialog displays a set of checkboxes; the choices optionally belong to a radio group - meaning only one choice is active at a given time. ![](options_dialog.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-options-dialog end-before: END-DOC-options-dialog dedent: 8 --- ``` ## Options Menu Similar to the options dialog, but displayed in menu form. ![](options_menu.png) Code for above: ```{literalinclude} ../../../../source/extensions/omni.kit.window.popup_dialog/scripts/demo_popup_dialog.py --- language: python start-after: BEGIN-DOC-options-menu end-before: END-DOC-options-menu dedent: 8 --- ``` ## Demo app A complete demo, that includes the code snippets above, is included with this extension at "scripts/demo_popup_dialog.py".
2,456
Markdown
23.326732
122
0.739821
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/config/extension.toml
[package] title = "Channel Manager" description = "The channel manager provides universal way to create/manage Omniverse Channel without caring about the state management but only message exchange between clients." version = "1.0.9" changelog = "docs/CHANGELOG.md" readme = "docs/README.md" category = "Utility" feature = true # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] [dependencies] "omni.client" = {} [[python.module]] name = "omni.kit.collaboration.channel_manager" [[test]] args = [ "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] pyCoverageOmit = [ "omni/kit/collaboration/channel_manager/tests/channel_manager_tests.py", "omni/kit/collaboration/channel_manager/tests/test_base.py", "omni/kit/collaboration/channel_manager/manager.py", "omni/kit/collaboration/channel_manager/extension.py", ] dependencies = [] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = [] [settings] exts."omni.kit.collaboration.channel_manager".enable_server_tests = false exts."omni.kit.collaboration.channel_manager".from_app = "Kit"
1,577
TOML
29.346153
178
0.740013
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ChannelManagerExtension", "join_channel_async"] import carb import omni.ext from .manager import Channel, ChannelManager _global_instance = None class ChannelManagerExtension(omni.ext.IExt): # pragma: no cover def on_startup(self): global _global_instance _global_instance = self self._channel_manager = ChannelManager() self._channel_manager.on_startup() def on_shutdown(self): global _global_instance _global_instance = None self._channel_manager.on_shutdown() self._channel_manager = None async def join_channel_async(self, url, get_users_only) -> Channel: channel = await self._channel_manager.join_channel_async(url, get_users_only) return channel def _has_channel(self, url) -> bool: """Internal for testing.""" return self._channel_manager.has_channel(url) @staticmethod def _get_instance(): global _global_instance return _global_instance async def join_channel_async(url: str, get_users_only=False) -> Channel: """ Joins a channel and starts listening. The typical life cycle is as follows of a channel session if get_users_only is False: 1. User joins and sends a JOIN message to the channel. 2. Other clients receive JOIN message will respond with HELLO to broadcast its existence. 3. Clients communicate with each other by sending MESSAGE to each other. 4. Clients send LEFT before quit this channel. Args: url (str): The channel url to join. The url could be stage url or url with `.__omni_channel__` or `.channel` suffix. If the suffix is not provided, it will be appended internally with `.__omni_channel__` to be compatible with old version. get_users_only (bool): It will join channel without sending JOIN/HELLO/LEFT message but only receives message from other clients. For example, it can be used to fetch user list without broadcasting its existence. After joining, all users inside the channel will respond HELLO message. Returns: omni.kit.collaboration.channel_manager.Channel. The instance of channel that could be used to publish/subscribe channel messages. Examples: >>> import omni.kit.collaboration.channel_manager as nm >>> >>> async join_channel_async(url): >>> channel = await nm.join_channel_async(url) >>> if channel: >>> channel.add_subscriber(...) >>> await channel.send_message_async(...) >>> else: >>> # Failed to join >>> pass """ if not url.startswith("omniverse:"): carb.log_warn(f"Only Omniverse URL supports to create channel: {url}.") return None if not ChannelManagerExtension._get_instance(): carb.log_warn(f"Channel Manager Extension is not enabled.") return None channel = await ChannelManagerExtension._get_instance().join_channel_async(url, get_users_only=get_users_only) return channel
3,571
Python
38.252747
131
0.66508
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/manager.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["Channel", "ChannelSubscriber"] import asyncio import concurrent.futures import weakref import json import carb import carb.settings import omni.client import omni.kit.app import time import omni.kit.collaboration.telemetry import zlib from typing import Callable, Dict, List from .types import Message, MessageType, PeerUser CHANNEL_PING_TIME_IN_SECONDS = 60 # Period to ping. KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER = b'__OVUM__' KIT_CHANNEL_MESSAGE_VERSION = "3.0" OMNIVERSE_CHANNEL_URL_SUFFIX = ".__omni_channel__" OMNIVERSE_CHANNEL_NEW_URL_SUFFIX = ".channel" MESSAGE_VERSION_KEY = "version" MESSAGE_FROM_USER_NAME_KEY = "from_user_name" MESSAGE_CONTENT_KEY = "content" MESSAGE_TYPE_KEY = "message_type" MESSAGE_APP_KEY = "app" def _get_app(): # pragma: no cover settings = carb.settings.get_settings() app_name = settings.get("/app/name") or "Kit" if app_name.lower().endswith(".next"): # FIXME: OM-55917: temp hack for Create. return app_name[:-5] return app_name def _build_message_in_bytes(from_user, message_type, content): # pragma: no cover content = { MESSAGE_VERSION_KEY: KIT_CHANNEL_MESSAGE_VERSION, MESSAGE_TYPE_KEY: message_type, MESSAGE_FROM_USER_NAME_KEY: from_user, MESSAGE_CONTENT_KEY: content, MESSAGE_APP_KEY: _get_app(), } content_bytes = json.dumps(content).encode() return KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER + content_bytes class ChannelSubscriber: # pragma: no cover """Handler of subscription to a channel.""" def __init__(self, message_handler: Callable[[Message], None], channel: weakref) -> None: """ Constructor. Internal only. Args: message_handler (Callable[[Message], None]): Message handler to handle message. channel (weakref): Weak holder of channel. """ self._channel = channel self._message_handler = message_handler def __del__(self): self.unsubscribe() def unsubscribe(self): """Stop subscribe.""" self._message_handler = None if self._channel and self._channel(): self._channel()._remove_subscriber(self) def _on_message(self, message: Message): if self._message_handler: self._message_handler(message) class NativeChannelWrapper: # pragma: no cover """ Channel is the manager that manages message receive and distribution to MessageSubscriber. It works in subscribe/publish pattern. """ def __init__(self, url: str, get_users_only): """ Constructor. Internal only. """ self._url = url self._logged_user_name = "" self._logged_user_id = "" self._peer_users: Dict[str, PeerUser] = {} self._channel_handler = None self._subscribers = [] self._message_queue = [] self._stopped = False self._get_users_only = get_users_only self._stopping = False self._last_ping_time = time.time() self._last_user_response_time = {} self._all_pending_tasks = [] self._joining = False self._telemetry = omni.kit.collaboration.telemetry.Schema_omni_kit_collaboration_1_0() def _track_asyncio_task(self, task): self._all_pending_tasks.append(task) def _remove_asyncio_task(self, task): if task in self._all_pending_tasks: self._all_pending_tasks.remove(task) def _run_asyncio_task(self, func, *args): task = asyncio.ensure_future(func(*args)) self._track_asyncio_task(task) task.add_done_callback(lambda task: self._remove_asyncio_task(task)) return task def _remove_all_tasks(self): for task in self._all_pending_tasks: task.cancel() self._all_pending_tasks = [] def destroy(self): self._remove_all_tasks() self._telemetry = None @property def url(self) -> str: """Property. The channel url in Omniverse.""" return self._url @property def stopped(self) -> bool: """Property. If this channel is stopped already.""" return self._stopped or not self._channel_handler or self._channel_handler.is_finished() @property def stopping(self) -> bool: return self._stopping @property def logged_user_name(self) -> str: """Property. The logged user name for this channel.""" return self._logged_user_name @property def logged_user_id(self) -> str: """Property. The unique logged user id.""" return self._logged_user_id @property def peer_users(self) -> Dict[str, PeerUser]: """Property. All the peer clients that joined to this channel.""" return self._peer_users def _emit_channel_event(self, event_name:str): """ Generates a structured log event noting that a join or leave event has occurred. This event is sent through the 'omni.kit.collaboration.telemetry' extension. Args: event_name: the name of the event to send. This must be either 'join' or 'leave'. """ # build up the event data to emit. Note that the live-edit session's URL will be hashed # instead of exposed directly. This is because the URL contains both the USD stage name # and potential PII in the session's name tag itself (ie: "Bob_session". Both of these # are potentially considered either personal information or intellectual property and # should not be exposed in telemetry events. The hashed value will at least be stable # for any given URL. event = omni.kit.collaboration.telemetry.Struct_liveEdit_liveEdit() event.id = str(zlib.crc32(bytes(self.url, "utf-8"))) event.action = event_name settings = carb.settings.get_settings() cloud_link_id = settings.get("/cloud/cloudLinkId") or "" self._telemetry.liveEdit_sendEvent(cloud_link_id, event) async def join_channel_async(self): """ Async function. Join Omniverse Channel. Args: url: The url to create/join a channel. get_users_only: Johns channel as a monitor only or not. """ if self._get_users_only: carb.log_info(f"Getting users from channel: {self.url}") else: carb.log_info(f"Starting to join channel: {self.url}") if self._channel_handler: self._channel_handler.stop() self._channel_handler = None # Gets the logged user information. try: result, server_info = await omni.client.get_server_info_async(self.url) if result != omni.client.Result.OK: return False self._logged_user_name = server_info.username self._logged_user_id = server_info.connection_id except Exception as e: carb.log_error(f"Failed to join channel {self.url} since user token cannot be got: {str(e)}.") return False channel_connect_future = concurrent.futures.Future() # TODO: Should this function be guarded with mutex? # since it's called in another native thread. def on_channel_message( result: omni.client.Result, event_type: omni.client.ChannelEvent, from_user: str, content ): if not channel_connect_future.done(): if not self._get_users_only: carb.log_info(f"Join channel {self.url} successfully.") self._emit_channel_event("join") channel_connect_future.set_result(result == omni.client.Result.OK) if result != omni.client.Result.OK: carb.log_warn(f"Stop channel since it has errors: {result}.") self._stopped = True return self._on_message(event_type, from_user, content) self._joining = True self._channel_handler = omni.client.join_channel_with_callback(self.url, on_channel_message) result = channel_connect_future.result() if result: if self._get_users_only: await self._send_message_internal_async(MessageType.GET_USERS, {}) else: await self._send_message_internal_async(MessageType.JOIN, {}) self._joining = False return result def stop(self): """Stop this channel.""" if self._stopping or self.stopped: return if not self._get_users_only: carb.log_info(f"Stopping channel {self.url}") self._emit_channel_event("leave") self._stopping = True return self._run_asyncio_task(self._stop_async) async def _stop_async(self): if self._channel_handler and not self._channel_handler.is_finished(): if not self._get_users_only and not self._joining: await self._send_message_internal_async(MessageType.LEFT, {}) self._channel_handler.stop() self._channel_handler = None self._stopped = True self._stopping = False self._subscribers.clear() self._peer_users.clear() self._last_user_response_time.clear() def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber: subscriber = ChannelSubscriber(on_message, weakref.ref(self)) self._subscribers.append(weakref.ref(subscriber)) return subscriber def _remove_subscriber(self, subscriber: ChannelSubscriber): to_be_removed = [] for item in self._subscribers: if not item() or item() == subscriber: to_be_removed.append(item) for item in to_be_removed: self._subscribers.remove(item) async def send_message_async(self, content: dict) -> omni.client.Request: if self.stopped or self.stopping: return return await self._send_message_internal_async(MessageType.MESSAGE, content) async def _send_message_internal_async(self, message_type: MessageType, content: dict): carb.log_verbose(f"Send {message_type} message to channel {self.url}, content: {content}") message = _build_message_in_bytes(self._logged_user_name, message_type, content) return await omni.client.send_message_async(self._channel_handler.id, message) def _update(self): if self.stopped or self._stopping: return # FIXME: Is this a must? pending_messages, self._message_queue = self._message_queue, [] for message in pending_messages: self._handle_message(message[0], message[1], message[2]) current_time = time.time() duration_in_seconds = current_time - self._last_ping_time if duration_in_seconds > CHANNEL_PING_TIME_IN_SECONDS: self._last_ping_time = current_time carb.log_verbose("Ping all users...") self._run_asyncio_task(self._send_message_internal_async, MessageType.GET_USERS, {}) dropped_users = [] for user_id, last_response_time in self._last_user_response_time.items(): duration = current_time - last_response_time if duration > CHANNEL_PING_TIME_IN_SECONDS: dropped_users.append(user_id) for user_id in dropped_users: peer_user = self._peer_users.pop(user_id, None) if not peer_user: continue message = Message(peer_user, MessageType.LEFT, {}) self._broadcast_message(message) def _broadcast_message(self, message: Message): for subscriber in self._subscribers: if subscriber(): subscriber()._on_message(message) def _on_message(self, event_type: omni.client.ChannelEvent, from_user: str, content): # Queue message handling to main looper. self._message_queue.append((event_type, from_user, content)) def _handle_message(self, event_type: omni.client.ChannelEvent, from_user: str, content): # Sent from me, skip them if not from_user: return self._last_user_response_time[from_user] = time.time() peer_user = None payload = {} message_type = None new_user = False if event_type == omni.client.ChannelEvent.JOIN: # We don't use JOIN from server pass elif event_type == omni.client.ChannelEvent.LEFT: peer_user = self._peer_users.pop(from_user, None) if peer_user: message_type = MessageType.LEFT elif event_type == omni.client.ChannelEvent.DELETED: self._channel_handler.stop() self._channel_handler = None elif event_type == omni.client.ChannelEvent.MESSAGE: carb.log_verbose(f"Message received from user with id {from_user}.") try: header_len = len(KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER) bytes = memoryview(content).tobytes() if len(bytes) < header_len: carb.log_error(f"Unsupported message received from user {from_user}.") else: bytes = bytes[header_len:] message = json.loads(bytes) except Exception: carb.log_error(f"Failed to decode message sent from user {from_user}.") return version = message.get(MESSAGE_VERSION_KEY, None) if not version or version != KIT_CHANNEL_MESSAGE_VERSION: carb.log_warn(f"Message version sent from user {from_user} does not match expected one: {message}.") return from_user_name = message.get(MESSAGE_FROM_USER_NAME_KEY, None) if not from_user_name: carb.log_warn(f"Message sent from unknown user: {message}") return message_type = message.get(MESSAGE_TYPE_KEY, None) if not message_type: carb.log_warn(f"Message sent from user {from_user} does not include message type.") return if message_type == MessageType.GET_USERS: carb.log_verbose(f"Fetch message from user with id {from_user}, name {from_user_name}.") if not self._get_users_only: self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {}) return peer_user = self._peer_users.get(from_user, None) if not peer_user: # Don't handle non-recorded user's left. if message_type == MessageType.LEFT: carb.log_verbose(f"User {from_user}, name {from_user_name} left channel.") return else: from_app = message.get(MESSAGE_APP_KEY, "Unknown") peer_user = PeerUser(from_user, from_user_name, from_app) self._peer_users[from_user] = peer_user new_user = True else: new_user = False if message_type == MessageType.HELLO: carb.log_verbose(f"Hello message from user with id {from_user}, name {from_user_name}.") if not new_user: return elif message_type == MessageType.JOIN: carb.log_verbose(f"Join message from user with id {from_user}, name {from_user_name}.") if not new_user: return if not self._get_users_only: self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {}) elif message_type == MessageType.LEFT: carb.log_verbose(f"Left message from user with id {from_user}, name {from_user_name}.") self._peer_users.pop(from_user, None) else: message_content = message.get(MESSAGE_CONTENT_KEY, None) if not message_content or not isinstance(message_content, dict): carb.log_warn(f"Message content sent from user {from_user} is empty or invalid format: {message}.") return carb.log_verbose(f"Message received from user with id {from_user}: {message}.") payload = message_content message_type = MessageType.MESSAGE if message_type and peer_user: # It's possible that user blocks its main thread and hang over the duration time to reponse ping command. # This is to notify user is back again. if new_user and message_type != MessageType.HELLO and message_type != MessageType.JOIN: message = Message(peer_user, MessageType.HELLO, {}) self._broadcast_message(message) message = Message(peer_user, message_type, payload) self._broadcast_message(message) class Channel: # pragma: no cover def __init__(self, handler: weakref, channel_manager: weakref) -> None: self._handler = handler self._channel_manager = channel_manager if self._handler and self._handler(): self._url = self._handler().url self._logged_user_name = self._handler().logged_user_name self._logged_user_id = self._handler().logged_user_id else: self._url = "" @property def stopped(self): return not self._handler or not self._handler() or self._handler().stopped @property def logged_user_name(self): return self._logged_user_name @property def logged_user_id(self): return self._logged_user_id @property def peer_users(self) -> Dict[str, PeerUser]: """Property. All the peer clients that joined to this channel.""" if self._handler and self._handler(): return self._handler().peer_users return None @property def url(self): return self._url def stop(self) -> asyncio.Future: if not self.stopped and self._channel_manager and self._channel_manager(): task = self._channel_manager()._stop_channel(self._handler()) else: task = None self._handler = None return task def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber: """ Add subscriber. Args: on_message (Callable[[Message], None]): The message handler. Returns: Instance of ChannelSubscriber. The channel will be stopped if instance is release. So it needs to hold the instance before it's stopped. You can manually call `stop` to stop this channel, or set the returned instance to None. """ if not self.stopped: return self._handler().add_subscriber(on_message) return None async def send_message_async(self, content: dict) -> omni.client.Request: """ Async function. Send message to all peer clients. Args: content (dict): The message composed in dictionary. Return: omni.client.Request. """ if not self.stopped: return await self._handler().send_message_async(content) return None class ChannelManager: # pragma: no cover def __init__(self) -> None: self._all_channels: List[NativeChannelWrapper] = [] self._update_subscription = None def on_startup(self): carb.log_info("Starting Omniverse Channel Manager...") self._all_channels.clear() app = omni.kit.app.get_app() self._update_subscription = app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.kit.collaboration.channel_manager update" ) def on_shutdown(self): carb.log_info("Shutting down Omniverse Channel Manager...") self._update_subscription = None for channel in self._all_channels: self._stop_channel(channel) channel.destroy() self._all_channels.clear() def _stop_channel(self, channel: NativeChannelWrapper): if channel and not channel.stopping: task = channel.stop() return task return None def _on_update(self, dt): to_be_removed = [] for channel in self._all_channels: if channel.stopped: to_be_removed.append(channel) else: channel._update() for channel in to_be_removed: channel.destroy() self._all_channels.remove(channel) # Internal interface def has_channel(self, url: str): for channel in self._all_channels: if url == channel: return True return False async def join_channel_async(self, url: str, get_users_only: bool): """ Async function. Join Omniverse Channel. Args: url: The url to create/join a channel. get_users_only: Joins channel as a monitor only or not. """ channel_wrapper = NativeChannelWrapper(url, get_users_only) success = await channel_wrapper.join_channel_async() if success: self._all_channels.append(channel_wrapper) channel = Channel(weakref.ref(channel_wrapper), weakref.ref(self)) else: channel = None return channel
21,927
Python
35.304636
119
0.602727
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/types.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # class PeerUser: """Information of peer user that's joined to the same channel.""" def __init__(self, user_id: str, user_name: str, from_app: str) -> None: """ Constructor. Internal only. Args: user_id (str): Unique user id. user_name (str): Readable user name. from_app (str): Which app this users join from. """ self._user_id = user_id self._user_name = user_name self._from_app = from_app @property def user_id(self): """Property. Unique user id.""" return self._user_id @property def user_name(self): """Property. Readable user name.""" return self._user_name @property def from_app(self): """Property. Readable app name, like 'Kit', 'Maya', etc.""" return self._from_app class MessageType: JOIN = "JOIN" # User is joined. Client should respond HELLO if it receives JOIN from new user. HELLO = "HELLO" # Someone said hello to me. Normally, client sends HELLO when it receives GET_USERS = "GET_USERS" # User does not join this channel, but wants to find who are inside this channel. # Clients receive this message should respond with HELLO to broadcast its existence. # Clients implement this command does not need to send JOIN firstly, and no LEFT sent # also before quitting channel. LEFT = "LEFT" # User left this channel. MESSAGE = "MESSAGE" # Normal message after JOIN. class Message: def __init__(self, from_user: PeerUser, message_type: MessageType, content: dict) -> None: """ Constructor. Internal only. Args: from_user (PeerUser): User that message sent from. message_type (MessageType): Message type. content (dict): Message content in dict. """ self._from_user = from_user self._message_type = message_type self._content = content @property def from_user(self) -> PeerUser: """Property. User that message sent from.""" return self._from_user @property def message_type(self) -> MessageType: """Property. Message type.""" return self._message_type @property def content(self) -> dict: """Property. Message content in dictionary.""" return self._content def __str__(self) -> str: return f"from: {self.from_user.user_name}, message_type: {self.message_type}, content: {self.content}"
3,048
Python
32.505494
113
0.613517
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/__init__.py
from .channel_manager_tests import TestChannelManager
54
Python
26.499987
53
0.87037
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/channel_manager_tests.py
import unittest import omni.client import omni.kit.test import omni.kit.app import omni.kit.collaboration.channel_manager as cm from omni.kit.collaboration.channel_manager.manager import _build_message_in_bytes from .test_base import enable_server_tests class TestChannelManager(omni.kit.test.AsyncTestCase): # pragma: no cover BASE_URL = "omniverse://localhost/Projects/tests/omni.kit.collaboration.channel_manger/" # Before running each test async def setUp(self): self.app = omni.kit.app.get_app() self.current_message = None async def tearDown(self): pass async def _wait(self, frames=10): for i in range(frames): await self.app.next_update_async() async def test_join_invalid_omniverse_url(self): channel = await cm.join_channel_async("file://c/invalid_url.channel") self.assertFalse(channel) channel = await cm.join_channel_async("omniverse://invalid-server/invalid_url.channel") self.assertFalse(channel) async def test_peer_user_and_message_api(self): peer_user = cm.PeerUser("test_id", "test", "Create") self.assertEqual(peer_user.user_id, "test_id") self.assertEqual(peer_user.user_name, "test") self.assertEqual(peer_user.from_app, "Create") content = {"key" : "value"} message = cm.Message(peer_user, cm.MessageType.HELLO, content=content) self.assertEqual(message.from_user, peer_user) self.assertEqual(message.message_type, cm.MessageType.HELLO) self.assertEqual(message.content, content) @unittest.skipIf(not enable_server_tests(), "") async def test_api(self): test_url = self.BASE_URL + "test.channel" def subscriber(message: cm.Message): self.current_message = message channel = await cm.join_channel_async(test_url) handle = channel.add_subscriber(subscriber) self.assertTrue(channel is not None, f"Failed to connect channel.") self.assertTrue(channel.url is not None) self.assertTrue(channel.logged_user_name is not None) self.assertTrue(channel.logged_user_id is not None) self.assertTrue(channel.stopped is False) # Send empty message result = await channel.send_message_async({}) self.assertTrue(result == omni.client.Result.OK) # Send more result = await channel.send_message_async({"test": "message_content"}) self.assertTrue(result == omni.client.Result.OK) # Simulates multi-users user_id = 0 for message_type in [cm.MessageType.JOIN, cm.MessageType.HELLO, cm.MessageType.LEFT]: self.current_message = None content = _build_message_in_bytes("test", message_type, {}) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), content) self.assertTrue(self.current_message is not None) self.assertEqual(self.current_message.message_type, message_type) self.assertEqual(self.current_message.from_user.user_id, str(user_id)) self.assertEqual(self.current_message.from_user.user_name, "test") # Don't increment user id for LEFT message as LEFT message will not be handled if user is not logged. if message_type == cm.MessageType.JOIN: user_id += 1 # Simulates customized message self.current_message = None content = {"test_key": "content"} message = _build_message_in_bytes("test", cm.MessageType.MESSAGE, content) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), message) self.assertTrue(self.current_message) self.assertEqual(self.current_message.message_type, cm.MessageType.MESSAGE) self.assertEqual(self.current_message.content, content) # Channel's LEFT message will be treated as left too. self.current_message = None channel._handler()._handle_message(omni.client.ChannelEvent.LEFT, str(user_id), None) self.assertEqual(self.current_message.message_type, cm.MessageType.LEFT) handle.unsubscribe() @unittest.skipIf(not enable_server_tests(), "") async def test_synchronization(self): test_url = self.BASE_URL + "test.channel" for i in range(20): channel = await cm.join_channel_async(test_url) self.assertTrue(not not channel)
4,456
Python
40.654205
113
0.665619
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/test_base.py
import carb.settings def enable_server_tests(): settings = carb.settings.get_settings() enabled = settings.get_as_bool("/exts/omni.kit.collaboration.channel_manager/enable_server_tests") return enabled
218
Python
20.899998
102
0.738532
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/CHANGELOG.md
# Changelog ## [1.0.9] - 2021-11-02 ### Changed - Support to fetch connection id for logged user. ## [1.0.8] - 2021-09-22 ### Changed - More tests coverage. ## [1.0.7] - 2021-08-21 ### Changed - More tests coverage. ## [1.0.6] - 2021-08-08 ### Changed - Exclude code to improve test coverage. ## [1.0.5] - 2021-07-25 ### Changed - Don't send LEFT message for getting users only. ## [1.0.4] - 2021-07-08 ### Changed - Use real app name for live session. ## [1.0.3] - 2021-06-07 ### Changed - Don't send hello if user is joined already. ## [1.0.2] - 2021-03-15 ### Changed - Improve extension and add tests. ## [1.0.0] - 2021-03-09 ### Changed - Initial extension.
681
Markdown
16.947368
49
0.615272
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/README.md
# Channel Manager [omni.kit.collaboration.channel_manager] This extension provides interfaces create/manage Omniverse Channel without caring about state management but only message exchange between clients.
207
Markdown
68.333311
147
0.850242
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/docs/index.rst
omni.kit.collaboration.channel_manager ###################################### Channel Manager Introduction ============ This extension provides interfaces create/manage Omniverse Channel without caring about state management but only message exchange between clients.
270
reStructuredText
26.099997
121
0.696296
omniverse-code/kit/exts/omni.debugdraw/config/extension.toml
[package] title = "debug draw" category = "Rendering" version = "0.1.1" [dependencies] "omni.usd" = {} "omni.hydra.rtx" = {optional=true} [[python.module]] name = "omni.debugdraw" [[native.plugin]] path = "bin/*.plugin" [[test]] timeout = 600 args = [ "--/app/asyncRendering=false", # OM-49867 random test crashes without this flag "--/renderer/enabled=rtx", "--/renderer/active=rtx", "--/rtx/post/aa/op=0", "--/rtx/post/tonemap/op=1", "--/app/file/ignoreUnsavedOnExit=true", "--/persistent/app/viewport/displayOptions=0", "--/app/viewport/forceHideFps=true", "--/app/viewport/grid/enabled=false", "--/app/viewport/show/lights=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/width=800", "--/app/window/height=600", "--no-window" ] dependencies = [ "omni.ui", "omni.kit.ui_test", "omni.hydra.rtx", "omni.kit.test_helpers_gfx", "omni.kit.viewport.utility", "omni.kit.window.viewport" ]
1,025
TOML
21.8
83
0.623415
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/_debugDraw.pyi
"""pybind11 omni.debugdraw bindings""" from __future__ import annotations import omni.debugdraw._debugDraw import typing import carb._carb __all__ = [ "IDebugDraw", "SimplexPoint", "acquire_debug_draw_interface", "release_debug_draw_interface" ] class IDebugDraw(): def draw_box(self, box_pos: carb._carb.Float3, box_rotation: carb._carb.Float4, box_size: carb._carb.Float3, color: int, line_width: float = 1.0) -> None: ... @typing.overload def draw_line(self, start_pos: carb._carb.Float3, start_color: int, start_width: float, end_pos: carb._carb.Float3, end_color: int, end_width: float) -> None: ... @typing.overload def draw_line(self, start_pos: carb._carb.Float3, start_color: int, end_pos: carb._carb.Float3, end_color: int) -> None: ... def draw_lines(self, lines_list: list) -> None: ... def draw_point(self, pos: carb._carb.Float3, color: int, width: float = 1.0) -> None: ... def draw_points(self, points_list: list) -> None: ... def draw_sphere(self, sphere_pos: carb._carb.Float3, sphere_radius: float, color: int, line_width: float = 1.0, tesselation: int = 32) -> None: ... pass class SimplexPoint(): """ SimplexPoint structure. """ def __init__(self) -> None: ... @property def color(self) -> int: """ :type: int """ @color.setter def color(self, arg0: int) -> None: pass @property def position(self) -> carb._carb.Float3: """ :type: carb._carb.Float3 """ @position.setter def position(self, arg0: carb._carb.Float3) -> None: pass @property def width(self) -> float: """ :type: float """ @width.setter def width(self, arg0: float) -> None: pass pass def acquire_debug_draw_interface(plugin_name: str = None, library_path: str = None) -> IDebugDraw: pass def release_debug_draw_interface(arg0: IDebugDraw) -> None: pass
1,968
unknown
31.816666
166
0.609756