file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/templates/header_context_menu.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 typing import Any import omni.kit.commands import omni.kit.undo import omni.usd class GroupHeaderContextMenuEvent: def __init__(self, group_id: str, payload: Any): self.group_id = group_id self.payload = payload self.type = 0 class GroupHeaderContextMenu: _instance = None def __init__(self): GroupHeaderContextMenu._instance = self def __del__(self): self.destroy() def destroy(self): GroupHeaderContextMenu._instance = None @classmethod def on_mouse_event(cls, event: GroupHeaderContextMenuEvent): if cls._instance: cls._instance._on_mouse_event(event) def _on_mouse_event(self, event: GroupHeaderContextMenuEvent): import omni.kit.context_menu # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): return # setup objects, this is passed to all functions objects = { "payload": event.payload, } menu_list = omni.kit.context_menu.get_menu_dict( "group_context_menu." + event.group_id, "omni.kit.window.property" ) omni.kit.context_menu.get_instance().show_context_menu( "group_context_menu." + event.group_id, objects, menu_list )
1,737
Python
28.965517
78
0.668969
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/tests/property_test.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest async def wait_for_update(usd_context=omni.usd.get_context(), wait_frames=10): max_loops = 0 while max_loops < wait_frames: _, files_loaded, total_files = usd_context.get_stage_loading_status() await omni.kit.app.get_app().next_update_async() if files_loaded or total_files: continue max_loops = max_loops + 1 class TestPropertyWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.window.property.extension import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute() import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): await super().tearDown() # test scheme async def test_property_window_scheme(self): from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate from omni.kit.window.property.templates import LABEL_HEIGHT, SimplePropertyWidget class SchemeTestWidget(SimplePropertyWidget): def __init__(self, name: str): super().__init__(title="SchemeTestWidget", collapsable=False) self._name = name nonlocal init_called init_called = True def on_new_payload(self, payload): nonlocal new_payload_called new_payload_called = True return True def build_items(self): nonlocal build_items_called build_items_called = True ui.Separator() with ui.HStack(height=0): ui.Spacer(width=8) ui.Button(self._name, width=52, height=LABEL_HEIGHT, name="add") ui.Spacer(width=88 - 52) widget = ui.StringField(name="scheme_name", height=LABEL_HEIGHT, enabled=False) widget.model.set_value(f"{self._name}-" * 100) ui.Separator() class TestPropertySchemeDelegate(PropertySchemeDelegate): def get_widgets(self, payload): widgets_to_build = [] if len(payload): # should still only appear once widgets_to_build.append("test_property_window_scheme_test") widgets_to_build.append("test_property_window_scheme_test") return widgets_to_build # enable custom widget/scheme w = self._w init_called = False w.register_widget("test_scheme_1", "test_property_window_scheme_test", SchemeTestWidget("TEST1")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_2", "test_property_window_scheme_test", SchemeTestWidget("TEST2")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_3", "test_property_window_scheme_test", SchemeTestWidget("TEST3")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_4", "test_property_window_scheme_test", SchemeTestWidget("TEST4")) self.assertTrue(init_called) w.register_scheme_delegate( "test_scheme_delegate", "test_property_window_scheme_test_scheme", TestPropertySchemeDelegate() ) w.set_scheme_delegate_layout("test_scheme_delegate", ["test_property_window_scheme_test_scheme"]) self.assertEqual(w.get_scheme(), "") # draw (should draw SchemeTestWidget item "TEST1") for scheme in ["test_scheme_1", "test_scheme_2", "test_scheme_3", "test_scheme_4"]: new_payload_called = False build_items_called = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify(scheme, {"payload": ["Items..."]}) await wait_for_update() self.assertTrue(w.get_scheme() == scheme) self.assertTrue(new_payload_called) self.assertTrue(build_items_called) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name=f"property_window_{scheme}.png" ) # disable custom widget/scheme await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.reset_scheme_delegate_layout("test_scheme_delegate") w.unregister_widget("test_scheme_4", "test_property_window_scheme_test") w.unregister_widget("test_scheme_3", "test_property_window_scheme_test") w.unregister_widget("test_scheme_2", "test_property_window_scheme_test") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test") w.unregister_scheme_delegate("test_scheme_delegate", "test_property_window_scheme_test_scheme") # draw (should draw nothing) for scheme in ["test_scheme_1", "test_scheme_2", "test_scheme_3", "test_scheme_4"]: new_payload_called = False build_items_called = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify(scheme, {"payload": ["Items..."]}) await wait_for_update() self.assertTrue(w.get_scheme() == scheme) self.assertFalse(new_payload_called) self.assertFalse(build_items_called) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"property_window_empty.png") await wait_for_update() async def test_pause_resume_property_window(self): from omni.kit.window.property.templates import LABEL_HEIGHT, SimplePropertyWidget class SchemeTestWidget(SimplePropertyWidget): def __init__(self, name: str): super().__init__(title="SchemeTestWidget", collapsable=False) self._name = name def on_new_payload(self, payload): if not super().on_new_payload(payload): return False return self._payload == self._name def build_items(self): ui.Separator() with ui.HStack(height=0): ui.Spacer(width=8) ui.Button(self._name, width=52, height=LABEL_HEIGHT, name="add") ui.Spacer(width=88 - 52) widget = ui.StringField(name="scheme_name", height=LABEL_HEIGHT, enabled=False) widget.model.set_value(f"{self._name}-" * 100) ui.Separator() # enable custom widget/scheme w = self._w w.register_widget("test_scheme_1", "test_property_window_scheme_test", SchemeTestWidget("TEST1")) w.register_widget("test_scheme_1", "test_property_window_scheme_test2", SchemeTestWidget("TEST2")) w.register_widget("test_scheme_2", "test_property_window_scheme_test3", SchemeTestWidget("TEST3")) # Not paused, refresh normally, show TEST1 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST1") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_paused.png") # Pause property window w.paused = True # Paused, property window stops updating, show TEST1 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST2") await wait_for_update() w.notify("test_scheme_2", "TEST3") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_paused.png") # Resume property window, refresh to last scheme/payload, show TEST3 w.paused = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_resumed.png") # Not paused, refresh normally, show TEST2 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST2") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_resumed2.png") w.unregister_widget("test_scheme_2", "test_property_window_scheme_test3") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test2") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test") # clear the schema - notify("", "") is ignored w.notify("", "payload") await wait_for_update()
10,878
Python
40.522901
119
0.607189
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/tests/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .property_test import *
463
Python
41.181814
76
0.803456
omniverse-code/kit/exts/omni.kit.window.property/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.8.2] - 2022-08-08 ### Added - Added style for `Grab` color. ## [1.8.1] - 2021-04-26 ### Changed - Added `identifier` parameter to `add_item_with_model` to set StringField identifier ## [1.8.0] - 2021-03-17 ### Changed - Changed builder function to a class member to enable polymorphism ## [1.7.0] - 2022-02-14 ### Added - Added context menu for collaspeable header - Added `request_rebuild` ## [1.6.3] - 2021-06-29 ### Changed - Added Field::url style ## [1.6.2] - 2021-06-21 ### Changed - Fixed issue with layer metadata not showing sometimes ## [1.6.1] - 2021-05-18 ### Added - Updated Checkbox style ## [1.6.0] - 2021-04-28 ### Added - Added `paused` property to Property Window API to pause/resume handling `notify` function. ## [1.5.5] - 2021-04-23 ### Changed - Fixed exception when using different payload class ## [1.5.4] - 2021-04-21 ### Changed - Added warning if build_items takes too long to process ## [1.5.3] - 2021-02-02 ### Changed - Used PrimCompositionQuery to query references. - Fixed removing reference from a layer that's under different directory than introducing layer. - Fixed finding referenced assets in Content Window with relative paths. ## [1.5.2] - 2020-12-09 ### Changed - Added extension icon - Added readme - Updated preview image ## [1.5.1] - 2020-11-20 ### Changed - Prevented exception on shutdown in simple_property_widget function `_delayed_rebuild` ## [1.5.0] - 2020-11-18 ### Added - Added `top_stack` parameter to `PropertyWindow.register_widget` and `PropertyWindow.unregister_widget`. Set True to register the widget to "Top" stack which layouts widgets from top down. False to register the widget to "Button" stack which layouts widgets from bottom up and always below the "Top" stack. Default is True. Order only matters when no `PropertySchemeDelegate` applies on the widget. ## [1.4.0] - 2020-11-16 ### Added - Added `reset` function to `PropertyWidget`. It will be called when a widget is no longer applicable to build under new scheme/payload. ## [1.3.1] - 2020-10-22 ### Added - Changed style label text color ## [1.3.0] - 2020-10-19 ### Added - Added "request_rebuild" function to "SimplePropertyWidget". It collects rebuild requests and rebuild on next frame. ## [1.2.0] - 2020-10-19 ### Added - Added get_scheme to PropertyWindow class. ## [1.1.0] - 2020-10-02 ### Changed - Update to CollapsableFrame open by default setting. ## [1.0.0] - 2020-09-17 ### Added - Created.
2,547
Markdown
27.311111
399
0.702788
omniverse-code/kit/exts/omni.kit.window.property/docs/README.md
# omni.kit.window.property ## Introduction Property window extensions are for viewing and editing Usd Prim Attributes ## This extension enables all other property windows and is the controlling API
201
Markdown
24.249997
79
0.80597
omniverse-code/kit/exts/omni.kit.window.property/docs/index.rst
omni.kit.window.property: Property Window Extension #################################################### .. toctree:: :maxdepth: 1 Overview.md CHANGELOG Property Window ========================== .. automodule:: omni.kit.window.property :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: PropertyExtension, partial :noindex: omni.kit.window.property.templates Property Widget ========================== .. automodule:: omni.kit.window.property.property_widget :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: abstractmethod Property Scheme Delegate ========================== .. automodule:: omni.kit.window.property.property_scheme_delegate :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: List, abstractmethod Property Widgets Templates ========================== .. automodule:: omni.kit.window.property.templates :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: build_frame_header
1,296
reStructuredText
24.431372
65
0.619599
omniverse-code/kit/exts/omni.kit.window.property/docs/Overview.md
# Overview
11
Markdown
4.999998
10
0.727273
omniverse-code/kit/exts/omni.videoencoding/video_encoding/__init__.py
from .impl import *
20
Python
9.499995
19
0.7
omniverse-code/kit/exts/omni.videoencoding/video_encoding/_video_encoding.pyi
""" Bindings for the omni::IVideoEncoding interface. """ from __future__ import annotations import video_encoding._video_encoding import typing __all__ = [ "IVideoEncoding", "acquire_video_encoding_interface", "release_video_encoding_interface" ] class IVideoEncoding(): def encode_next_frame_from_buffer(self, buffer_rgba8: buffer, width: int = 0, height: int = 0) -> bool: """ Encode a frame and write the result to disk. Args: buffer_rgba8 raw frame image data; format: R8G8B8A8; size: width * height * 4 width frame width; can be inferred from shape of buffer_rgba8 if set appropriately height frame height; can be inferred from shape of buffer_rgba8 if set appropriately Returns: True if successful, else False. """ def encode_next_frame_from_file(self, frame_filename: str) -> None: """ Read a frame from an image file, encode, and write to disk. Warning: pixel formats other than RGBA8 will probably not work (yet). Args: frame_filename name of the file to read. Supported file formats: see carb::imaging """ def finalize_encoding(self) -> None: """ Indicate that all frames have been encoded. This will ensure that writing to the output video file is done, and close it. """ def start_encoding(self, video_filename: str, framerate: float, nframes: int, overwrite_video: bool) -> bool: """ Prepare the encoding plugin to process frames. Args: video_filename name of the MP4 file where the encoded video will be written framerate number of frames per second nframes total number of frames; if unknown, set to 0 overwrite_video if set, overwrite existing MP4 file; otherwise, refuse to do anything if the file specified in video_filename exists. Returns: True if preparation succeeded and the encoding plugin is ready; False otherwise. """ pass def acquire_video_encoding_interface(plugin_name: str = None, library_path: str = None) -> IVideoEncoding: pass def release_video_encoding_interface(arg0: IVideoEncoding) -> None: pass
2,254
unknown
39.267856
145
0.656167
omniverse-code/kit/exts/omni.videoencoding/video_encoding/tests/test_encoding.py
import omni.kit.test import carb.settings import os import tempfile import numpy as np from video_encoding import get_video_encoding_interface VIDEO_FULL_RANGE_PATH = "/exts/omni.videoencoding/vui/videoFullRangeFlag" class Test(omni.kit.test.AsyncTestCase): def get_next_frame(self, shape=(480,640,4)): values = self._rng.random(shape) result = (values * 255.).astype(np.uint8) return result async def setUp(self): print('setUp called') self._rng = np.random.default_rng(seed=1234) self._settings = carb.settings.acquire_settings_interface() self._encoding_interface = get_video_encoding_interface() async def tearDown(self): self._rng = None def _encode_test_sequence(self, n_frames=10): n_frames = 10 with tempfile.TemporaryDirectory() as tmpdirname: video_filename = os.path.join(tmpdirname,'output.mp4') self.assertTrue(self._encoding_interface.start_encoding(video_filename, 24, n_frames, True), msg="Failed to initialize encoding interface.") for i_frame in range(n_frames): frame_data = self.get_next_frame() self._encoding_interface.encode_next_frame_from_buffer(frame_data) self._encoding_interface.finalize_encoding() encoded_size = os.path.getsize(video_filename) return encoded_size async def test_encoding_interface(self): self._settings.set(VIDEO_FULL_RANGE_PATH, False) encoded_size = self._encode_test_sequence(n_frames=10) expected_encoded_size = 721879 self.assertAlmostEqual(encoded_size / expected_encoded_size, 1., places=1, msg=f"Expected encoded video size {expected_encoded_size}; got: {encoded_size}") async def test_encoding_interface_with_full_range(self): self._settings.set(VIDEO_FULL_RANGE_PATH, True) encoded_size = self._encode_test_sequence(n_frames=10) expected_encoded_size = 1081165 self.assertAlmostEqual(encoded_size / expected_encoded_size, 1., places=1, msg=f"Expected encoded video size {expected_encoded_size}; got: {encoded_size}")
2,201
Python
34.516128
104
0.663789
omniverse-code/kit/exts/omni.videoencoding/video_encoding/tests/__init__.py
from .test_encoding import *
28
Python
27.999972
28
0.785714
omniverse-code/kit/exts/omni.videoencoding/video_encoding/impl/__init__.py
from .video_encoding import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.videoencoding/video_encoding/impl/video_encoding.py
import os import carb import omni.ext from .._video_encoding import * # Put interface object publicly to use in our API. _video_encoding_api = None def get_video_encoding_interface() -> IVideoEncoding: return _video_encoding_api def encode_image_file_sequence(filename_pattern, start_number, frame_rate, output_file, overwrite_existing) -> bool: video_encoding_api = get_video_encoding_interface() if video_encoding_api is None: carb.log_warn("Video encoding api not available; cannot encode video.") return False # acquire list of available frame image files, based on start_number and filename_pattern next_frame = start_number frame_filenames = [] while True: frame_filename = filename_pattern % (next_frame) if os.path.isfile(frame_filename) and os.access(frame_filename, os.R_OK): frame_filenames.append(frame_filename) next_frame += 1 else: break carb.log_warn(f"Found {len(frame_filenames)} frames to encode.") if len(frame_filenames) == 0: carb.log_warn(f"No frames to encode.") return False if not video_encoding_api.start_encoding(output_file, frame_rate, len(frame_filenames), overwrite_existing): return try: for frame_filename in frame_filenames: video_encoding_api.encode_next_frame_from_file(frame_filename) except: raise finally: video_encoding_api.finalize_encoding() return True # Use extension entry points to acquire and release interface. class Extension(omni.ext.IExt): def __init__(self): pass def on_startup(self, ext_id): global _video_encoding_api _video_encoding_api = acquire_video_encoding_interface() # print(f"[video encoding] _video_encoding interface: {_video_encoding_api}") def on_shutdown(self): global _video_encoding_api release_video_encoding_interface(_video_encoding_api) _video_encoding_api = None
2,016
Python
29.560606
116
0.669147
omniverse-code/kit/exts/omni.videoencoding/PACKAGE-LICENSES/omni.videoencoding-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.videoencoding/config/extension.toml
[package] version = "0.1.0" title = "Video Encoding Extension" category = "Internal" [dependencies] "omni.assets.plugins" = {} [[python.module]] name = "video_encoding" [[native.plugin]] path = "bin/*.plugin" recursive = false [settings] # Video encoding bitrate. exts."omni.videoencoding".bitrate = 16777216 # Video encoding framerate. Can be overridden by setting the framerate argument of start_encoding() exts."omni.videoencoding".framerate = 60.0 # I-Frame interval (every nth frame is an I-Frame) exts."omni.videoencoding".iframeinterval = 60 # Largest expected frame width exts."omni.videoencoding".maxEncodeWidth = 4096 # Largest expected frame height exts."omni.videoencoding".maxEncodeHeight = 4096 # Video encoding preset. Choices are: # "PRESET_DEFAULT" # "PRESET_HP" # "PRESET_HQ" # "PRESET_BD" # "PRESET_LOW_LATENCY_DEFAULT" # "PRESET_LOW_LATENCY_HQ" # "PRESET_LOW_LATENCY_HP" # "PRESET_LOSSLESS_DEFAULT" # "PRESET_LOSSLESS_HP" exts."omni.videoencoding".preset = "PRESET_DEFAULT" # Video encoding profile. Choices are: # "H264_PROFILE_BASELINE" # "H264_PROFILE_MAIN" # "H264_PROFILE_HIGH" # "H264_PROFILE_HIGH_444" # "H264_PROFILE_STEREO" # "H264_PROFILE_SVC_TEMPORAL_SCALABILITY" # "H264_PROFILE_PROGRESSIVE_HIGH" # "H264_PROFILE_CONSTRAINED_HIGH" # "HEVC_PROFILE_MAIN" # "HEVC_PROFILE_MAIN10" # "HEVC_PROFILE_FREXT" exts."omni.videoencoding".profile = "H264_PROFILE_HIGH" # Rate control mode. Choices are: # "RC_CONSTQP" # "RC_VBR" # "RC_CBR" # "RC_CBR_LOWDELAY_HQ" # "RC_CBR_HQ" # "RC_VBR_HQ" exts."omni.videoencoding".rcMode = "RC_VBR" # Rate control target quality. Range: 0-51, with 0-automatic exts."omni.videoencoding".rcTargetQuality = 0 [[test]] dependencies = [ ] args = [ "--no-window", ]
1,737
TOML
22.173333
99
0.717904
omniverse-code/kit/exts/omni.kit.test_suite.browser/omni/kit/test_suite/browser/__init__.py
from .scripts import *
23
Python
10.999995
22
0.73913
omniverse-code/kit/exts/omni.kit.test_suite.browser/omni/kit/test_suite/browser/tests/__init__.py
from .test_content_browser_settings import * from .test_file_picker_settings import *
86
Python
27.999991
44
0.790698
omniverse-code/kit/exts/omni.kit.test_suite.browser/omni/kit/test_suite/browser/tests/test_content_browser_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.test.async_unittest import AsyncTestCase from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class TestContentBrowserSettings(AsyncTestCase): # Before running each test async def setUp(self): super().setUp() await arrange_windows() async def test_content_browser_settings(self): async with ContentBrowserTestHelper() as content_browser_helper: path = get_test_data_path(__name__, "folder1/") async def get_files(): return sorted([c.name for c in await content_browser_helper.select_items_async(path, "*")]) # all off await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': False, 'show_udim_sequence': False, 'show_details': False}) menu_state = await content_browser_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_unknown': False, 'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': False}) self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg']) # unknown enabled await content_browser_helper.set_config_menu_settings({'hide_unknown': True, 'hide_thumbnails': False, 'show_udim_sequence': False, 'show_details': False}) menu_state = await content_browser_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_unknown': True, 'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': False}) self.assertEqual(await get_files(), ['.thumbs', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg']) # thumbs enabled await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': True, 'show_udim_sequence': False, 'show_details': False}) menu_state = await content_browser_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_unknown': False, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': False}) self.assertEqual(await get_files(), ['badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg']) # udim enabled await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': False, 'show_udim_sequence': True, 'show_details': False}) menu_state = await content_browser_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_unknown': False, 'hide_thumbnails': False, 'show_details': False, 'show_udim_sequence': True}) self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg']) # all enabled await content_browser_helper.set_config_menu_settings({'hide_unknown': True, 'hide_thumbnails': True, 'show_udim_sequence': True, 'show_details': False}) menu_state = await content_browser_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_unknown': True, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': True}) self.assertEqual(await get_files(), ['cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg'])
4,051
Python
72.672726
186
0.676129
omniverse-code/kit/exts/omni.kit.test_suite.browser/omni/kit/test_suite/browser/tests/test_file_picker_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.test.async_unittest import AsyncTestCase from omni.kit.window.file_importer import get_file_importer from omni.kit.window.file_importer.test_helper import FileImporterTestHelper from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows from omni.kit import ui_test class TestFilePickerSettings(AsyncTestCase): # Before running each test async def setUp(self): super().setUp() await arrange_windows() async def test_file_picker_settings(self): async with FileImporterTestHelper() as file_import_helper: path = get_test_data_path(__name__, "folder1/") async def get_files(): return sorted([c.name for c in await file_import_helper.select_items_async(path, "*")]) file_importer = get_file_importer() file_importer.show_window( title="File Picker Test", import_button_label="Ok", file_extension_types=[('*.*', 'All Files')], filename_url=path, ) await ui_test.human_delay(50) # all off await file_import_helper.set_config_menu_settings({'hide_thumbnails': False, 'show_udim_sequence': False, 'show_details': False}) menu_state = await file_import_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_thumbnails': False, 'hide_unknown': True, 'show_details': False, 'show_udim_sequence': False}) self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg']) # thumbs enabled await file_import_helper.set_config_menu_settings({'hide_thumbnails': True, 'show_udim_sequence': False, 'show_details': False}) menu_state = await file_import_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_thumbnails': True, 'hide_unknown': True, 'show_details': False, 'show_udim_sequence': False}) self.assertEqual(await get_files(), ['badfile.cheese', 'cheese.1041.png', 'file.9999.xxx.png', 'tile.1001.png', 'tile.1200.png', 'udim.1001.jpg', 'udim.1200.jpg']) # udim enabled await file_import_helper.set_config_menu_settings({'hide_thumbnails': False, 'show_udim_sequence': True, 'show_details': False}) menu_state = await file_import_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_thumbnails': False, 'hide_unknown': True, 'show_details': False, 'show_udim_sequence': True}) self.assertEqual(await get_files(), ['.thumbs', 'badfile.cheese', 'cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg']) # all enabled await file_import_helper.set_config_menu_settings({'hide_thumbnails': True, 'show_udim_sequence': True, 'show_details': False}) menu_state = await file_import_helper.get_config_menu_settings() menu_state = await file_import_helper.get_config_menu_settings() self.assertEqual(menu_state, {'hide_thumbnails': True, 'hide_unknown': True, 'show_details': False, 'show_udim_sequence': True}) self.assertEqual(await get_files(), ['badfile.cheese', 'cheese.<UDIM>.png', 'file.9999.xxx.png', 'tile.<UDIM>.png', 'udim.<UDIM>.jpg']) file_importer.hide_window() await ui_test.human_delay(50)
3,903
Python
59.061538
186
0.657443
omniverse-code/kit/exts/omni.kit.test_suite.browser/docs/index.rst
omni.kit.test_suite.browser ################################### viewport tests .. toctree:: :maxdepth: 1 CHANGELOG
124
reStructuredText
11.499999
35
0.491935
omniverse-code/kit/exts/omni.kit.window.content_browser/PACKAGE-LICENSES/omni.kit.window.content_browser-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.content_browser/scripts/demo_content_browser.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import weakref from omni.kit.window.content_browser import get_content_window from omni.kit.window.filepicker import FilePickerDialog class DemoContentBrowserClient: """ Example that demonstrates how to add custom actions to the content browser. """ def __init__(self): # Get the Content extension object. Same as: omni.kit.window.content_browser.get_extension() # Keep as weakref to guard against the extension being removed at any time. If it is removed, # then invoke appropriate handler; in this case the destroy method. self._content_browser_ref = weakref.ref(get_content_window(), lambda ref: self.destroy()) self._init_context_menu() def _init_context_menu(self): def file_extension_of(path: str, exts: [str]): _, ext = os.path.splitext(path) return ext in exts content_browser = self._content_browser_ref() if not content_browser: return # Add these items to the context menu and target to USD file types. content_browser.add_context_menu( "Collect Asset", "spinner.svg", lambda menu, path: self._collect_asset(path), lambda path: file_extension_of(path, [".usd"]), ) content_browser.add_context_menu( "Convert Asset", "menu_insert_sublayer.svg", lambda menu, path: self._convert_asset(path), lambda path: file_extension_of(path, [".usd"]), ) # Add these items to the list view menu and target to USD file types. content_browser.add_listview_menu( "Echo Selected", "spinner.svg", lambda menu, path: self._echo_selected(path), None ) # Add these items to the list view menu and target to USD file types. content_browser.add_import_menu( "My Custom Import", "spinner.svg", lambda menu, path: self._import_stuff(path), None ) def _collect_asset(self, path: str): print(f"Collecting asset {path}.") def _convert_asset(self, path: str): print(f"Converting asset {path}.") def _echo_selected(self, path: str): content_browser = self._content_browser_ref() if content_browser: print(f"Current directory is {path}.") selections = content_browser.get_current_selections(pane=1) print(f"TreeView selections = {selections}") selections = content_browser.get_current_selections(pane=2) print(f"ListView selections = {selections}") def _import_stuff(self, path: str): def on_apply(dialog: FilePickerDialog, filename: str, dirname: str): dialog.hide() print(f"Importing: {dirname}/{filename}") dialog = FilePickerDialog( "Download Files", width=800, height=400, splitter_offset=260, enable_filename_input=False, current_directory="Downloads", grid_view_scale=1, apply_button_label="Import", click_apply_handler=lambda filename, dirname: on_apply(dialog, filename, dirname), click_cancel_handler=lambda filename, dirname: dialog.hide(), ) dialog.show() def destroy(self): content_browser = self._content_browser_ref() if content_browser: content_browser.delete_context_menu("Collect Asset") content_browser.delete_context_menu("Convert Asset") content_browser.delete_listview_menu("Echo Selected") content_browser.delete_import_menu("My Custom Import") self._content_browser_ref = None if __name__ == "__main__": DemoContentBrowserClient()
4,188
Python
38.518868
101
0.63467
omniverse-code/kit/exts/omni.kit.window.content_browser/config/extension.toml
[package] title = "Content" version = "2.6.8" category = "core" feature = true description = "A window for browsing Omniverse content" authors = ["NVIDIA"] slackids = ["UQY4RMR3N"] repository = "" keywords = ["kit", "ui"] readme = "docs/README.md" changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.ui" = {} "omni.client" = {} "omni.kit.clipboard" = {} "omni.kit.window.filepicker" = {} "omni.kit.widget.filebrowser" = {} "omni.kit.window.popup_dialog" = {} "omni.kit.widget.versioning" = {} "omni.kit.window.file_exporter" = {} "omni.kit.window.file" = { optional=true } "omni.kit.pip_archive" = {} "omni.kit.window.drop_support" = {} "omni.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.window.content_browser_registry" = {} "omni.kit.ui_test" = {} [[python.module]] name = "omni.kit.window.content_browser" [[python.scriptFolder]] path = "scripts" [python.pipapi] requirements = ["psutil"] [settings] exts."omni.kit.window.content_browser".timeout = 10.0 exts."omni.kit.window.content_browser".show_grid_view = true exts."omni.kit.window.content_browser".enable_checkpoints = true exts."omni.kit.window.content_browser".show_only_collections = ["bookmarks", "omniverse", "my-computer"] # Uncomment and modify the following setting to add default server connections # exts."omni.kit.window.content_browser".mounted_servers = {"my-server" = "omniverse://my-server", "another-server" = "omniverse://another-server"} [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/file/ignoreUnsavedOnExit=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--/persistent/app/stage/dragDropImport='reference'", "--no-window", ] dependencies = [ "omni.kit.window.viewport", "omni.kit.window.stage", "omni.kit.ui_test", "omni.kit.test_suite.helpers", "omni.kit.renderer.core", ] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
2,309
TOML
28.240506
147
0.680381
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/external_drag_drop_helper.py
import os import asyncio import carb import omni.client import omni.appwindow import omni.ui as ui from typing import List, Tuple from omni.kit.window.drop_support import ExternalDragDrop external_drag_drop = None def setup_external_drag_drop(window_name: str, browser_widget, window_frame: ui.Frame): global external_drag_drop destroy_external_drag_drop() external_drag_drop = ExternalDragDrop(window_name=window_name, drag_drop_fn=lambda e, p, a=browser_widget.api, f=window_frame: _on_ext_drag_drop(e, p, a, f)) def destroy_external_drag_drop(): global external_drag_drop if external_drag_drop: external_drag_drop.destroy() external_drag_drop = None def _cleanup_slashes(path: str, is_directory: bool = False) -> str: """ Makes path/slashes uniform Args: path: path is_directory is path a directory, so final slash can be added Returns: path """ path = os.path.normpath(path) path = path.replace("\\", "/") if is_directory: if path[-1] != "/": path += "/" return path def _on_ext_drag_drop(edd: ExternalDragDrop, payload: List[str], api, frame: ui.Frame): import omni.kit.notification_manager def get_current_mouse_coords() -> Tuple[float, float]: 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 search_frame = api.tool_bar._search_frame search_delegate = api.tool_bar._search_delegate if search_delegate and search_frame and search_frame.visible: pos_x, pos_y = get_current_mouse_coords() if (pos_x > search_frame.screen_position_x and pos_y > search_frame.screen_position_y and pos_x < search_frame.screen_position_x + search_frame.computed_width and pos_y < search_frame.screen_position_y + search_frame.computed_height): if hasattr(search_delegate, "handle_drag_drop"): if search_delegate.handle_drag_drop(payload): return target_dir = api.get_current_directory() if not target_dir: omni.kit.notification_manager.post_notification("No target directory", hide_after_timeout=False) return # get common source path common_path = "" if len(payload) > 1: common_path = os.path.commonpath(payload) if not common_path: common_path = os.path.dirname(payload[0]) common_path = _cleanup_slashes(common_path, True) # get payload payload = edd.expand_payload(payload) # copy files async def do_copy(): from .progress_popup import ProgressPopup from .file_ops import copy_item_async copy_cancelled = False def do_cancel_copy(): nonlocal copy_cancelled copy_cancelled = True # show progress... waiting_popup = ProgressPopup("Copying...", status_text="Copying...") waiting_popup.status_text = "Copying..." waiting_popup.progress = 0.0 waiting_popup.centre_in_window(frame) waiting_popup.set_cancel_fn(do_cancel_copy) waiting_popup.show() try: await omni.kit.app.get_app().next_update_async() current_file = 0 total_files = len(payload) for file_path in payload: if copy_cancelled: break file_path = _cleanup_slashes(file_path) target_path = target_dir.rstrip("/") + "/" + file_path.replace(common_path, "") # update progress waiting_popup.progress = float(current_file) / total_files waiting_popup.status_text = f"Copying {os.path.basename(target_path)}..." waiting_popup.centre_in_window(frame) # copy file # OM-90753: Route through same code path as normal copy item await copy_item_async(file_path, target_path) current_file += 1 except Exception as exc: carb.log_error(f"error {exc}") await omni.kit.app.get_app().next_update_async() api.refresh_current_directory() waiting_popup.hide() del waiting_popup asyncio.ensure_future(do_copy())
4,475
Python
32.654135
136
0.612291
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/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 = { "Rectangle": {"background_color": 0xFF535354}, "Splitter": {"background_color": 0x0, "margin_width": 0}, "Splitter:hovered": {"background_color": 0xFFB0703B}, "Splitter:pressed": {"background_color": 0xFFB0703B}, "ToolBar": {"alignment": ui.Alignment.CENTER, "margin_height": 2}, "ToolBar.Button": {"background_color": 0xFF535354, "color": 0xFF9E9E9E}, "ToolBar.Button::filter": {"background_color": 0x0, "color": 0xFF9E9E9E}, "ToolBar.Button::import": { "background_color": 0xFFD6D6D6, "color": 0xFF535354, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "border_radius": 3, }, "ToolBar.Button.Label": {"color": 0xFF535354, "alignment": ui.Alignment.LEFT_CENTER}, "ToolBar.Button.Image": {"background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "ToolBar.Button:hovered": {"background_color": 0xFFB8B8B8}, "Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg", "background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "Recycle.Button:hovered": {"background_color": 0xFF3A3A3A}, } else: style = { "Splitter": {"background_color": 0x0, "margin_width": 0}, "Splitter:hovered": {"background_color": 0xFFB0703B}, "Splitter:pressed": {"background_color": 0xFFB0703B}, "ToolBar": {"alignment": ui.Alignment.CENTER, "margin_height": 2}, "ToolBar.Button": {"background_color": 0x0, "color": 0xFF9E9E9E}, "ToolBar.Button::import": { "background_color": 0xFF23211F, "color": 0xFF9E9E9E, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "border_radius": 3, }, "ToolBar.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "ToolBar.Button.Image": {"background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "ToolBar.Button:hovered": {"background_color": 0xFF3A3A3A}, "Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg", "background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "Recycle.Button:hovered": {"background_color": 0xFF3A3A3A}, } return style
3,527
Python
49.399999
160
0.620357
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import asyncio import carb import omni.ext import omni.kit.ui import omni.ui as ui import omni.kit.window.content_browser_registry as registry from functools import partial from typing import Union, Callable, List from omni.kit.helper.file_utils import FILE_OPENED_EVENT from omni.kit.window.filepicker import SearchDelegate, UI_READY_EVENT from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem from omni.kit.menu.utils import MenuItemDescription from .window import ContentBrowserWindow from .api import ContentBrowserAPI g_singleton = None # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class ContentBrowserExtension(omni.ext.IExt): """The Content Browser extension""" WINDOW_NAME = "Content" MENU_GROUP = "Window" def __init__(self): super().__init__() self._window = None def on_startup(self, ext_id): # Save away this instance as singleton for the editor window global g_singleton g_singleton = self ui.Workspace.set_show_window_fn(ContentBrowserExtension.WINDOW_NAME, partial(self.show_window, None)) self._menu = [MenuItemDescription( name=ContentBrowserExtension.WINDOW_NAME, ticked=True, # menu item is ticked ticked_fn=self._is_visible, # gets called when the menu needs to get the state of the ticked menu onclick_fn=self._toggle_window )] omni.kit.menu.utils.add_menu_items(self._menu, name=ContentBrowserExtension.MENU_GROUP) ui.Workspace.show_window(ContentBrowserExtension.WINDOW_NAME, True) # Listen for relevant event stream events event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._stage_event_subscription = event_stream.create_subscription_to_pop_by_type( FILE_OPENED_EVENT, self._on_stage_event) self._content_browser_inited_subscription = event_stream.create_subscription_to_pop_by_type( UI_READY_EVENT, self.decorate_from_registry) def _on_stage_event(self, stage_event): if not stage_event: return if "url" in stage_event.payload: stage_url = stage_event.payload["url"] default_folder = os.path.dirname(stage_url) self.navigate_to(default_folder) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visibility_changed_fn(self, visible): if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): """Shows this window. Inputs are for backwards compatibility only and not used.""" if value: self._window = ContentBrowserWindow() self._window.set_visibility_changed_listener(self._visibility_changed_fn) elif self._window: self._window.set_visible(value) # this only tags test menu to update when menu is opening, so it # doesn't matter that is called before window has been destroyed omni.kit.menu.utils.refresh_menu_items(ContentBrowserExtension.MENU_GROUP) def _is_visible(self) -> bool: return False if self._window is None else self._window.get_visible() def _toggle_window(self): if self._is_visible(): self.show_window(None, False) else: self.show_window(None, True) def on_shutdown(self): # pragma: no cover omni.kit.menu.utils.remove_menu_items(self._menu, name=ContentBrowserExtension.MENU_GROUP) self._stage_event_subscription = None if self._window: self._window.destroy() self._window = None ui.Workspace.set_show_window_fn(ContentBrowserExtension.WINDOW_NAME, None) global g_singleton g_singleton = None @property def window(self) -> ui.Window: """ui.Window: Main dialog window for this extension.""" return self._window @property def api(self) -> ContentBrowserAPI: if self._window: return self._window.widget.api return None def add_connections(self, connections: dict): """ Adds specified server connections to the tree browser. Args: connections (dict): A dictionary of name, path pairs. For example: {"C:": "C:", "ov-content": "omniverse://ov-content"}. Paths to Omniverse servers should be prefixed with "omniverse://". """ if self.api: self.api.add_connections(connections) def set_current_directory(self, path: str): """ Procedurally sets the current directory path. Args: path (str): The full path name of the folder, e.g. "omniverse://ov-content/Users/me. Raises: RuntimeWarning: If path doesn't exist or is unreachable. """ if self.api: try: self.api.set_current_directory(path) except Exception: raise def get_current_directory(self) -> str: """ Returns the current directory fom the browser bar. Returns: str: The system path, which may be different from the displayed path. """ if self.api: return self.api.get_current_directory() return None def get_current_selections(self, pane: int = 2) -> List[str]: """ Returns current selected as list of system path names. Args: pane (int): Specifies pane to retrieve selections from, one of {TREEVIEW_PANE = 1, LISTVIEW_PANE = 2, BOTH = None}. Default LISTVIEW_PANE. Returns: List[str]: List of system paths (which may be different from displayed paths, e.g. bookmarks) """ if self.api: return self.api.get_current_selections(pane) return [] def subscribe_selection_changed(self, fn: Callable): """ Subscribes to file selection changes. Args: fn (Callable): callback function when file selection changed. """ if self.api: registry.register_selection_handler(fn) self.api.subscribe_selection_changed(fn) def unsubscribe_selection_changed(self, fn: Callable): """ Unsubscribes this callback from selection changes. Args: fn (Callable): callback function when file selection changed. """ if self.api: registry.deregister_selection_handler(fn) self.api.unsubscribe_selection_changed(fn) def navigate_to(self, url: str): """ Navigates to the given url, expanding all parent directories along the path. Args: url (str): The path to navigate to. """ if self.api: self.api.navigate_to(url) async def navigate_to_async(self, url: str): """ Asynchronously navigates to the given url, expanding all parent directories along the path. Args: url (str): The url to navigate to. """ if self.api: await self.api.navigate_to_async(url) async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]: """ Asynchronously selects display items by their names. Args: url (str): Url of the parent folder. filenames (str): Names of items to select. Returns: List[FileBrowserItem]: List of selected items. """ if self.api: return await self.api.select_items_async(url, filenames=filenames) return [] def add_context_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable, index: int = 0, separator_name="_add_on_end_separator_") -> str: """ Add menu item, with corresponding callbacks, to the context menu. Args: name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature is void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature - bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. index (int): The position that this menu item will be inserted to. separator_name (str): The separator name of the separator menu item. Default to '_placeholder_'. When the index is not explicitly set, or if the index is out of range, this will be used to locate where to add the menu item; if specified, the index passed in will be counted from the saparator with the provided name. This is for OM-86768 as part of the effort to match Navigator and Kit UX for Filepicker/Content Browser for context menus. Returns: str: Name of menu item if successful, None otherwise. """ if self.api: registry.register_context_menu(name, glyph, click_fn, show_fn, index) return self.api.add_context_menu(name, glyph, click_fn, show_fn, index, separator_name=separator_name) return None def delete_context_menu(self, name: str): """ Delete the menu item, with the given name, from the context menu. Args: name (str): Name of the menu item (e.g. 'Open'). """ try: registry.deregister_context_menu(name) self.api.delete_context_menu(name) except AttributeError: # it can happen when content_browser is unloaded early. This way we don't need to unsubscribe pass def add_listview_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable, index: int = -1) -> str: """ Add menu item, with corresponding callbacks, to the list view menu. Args: name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the list view menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature: void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. index (int): The position that this menu item will be inserted to. Returns: str: Name of menu item if successful, None otherwise. """ if self.api: registry.register_listview_menu(name, glyph, click_fn, show_fn, index) return self.api.add_listview_menu(name, glyph, click_fn, show_fn, index) return None def delete_listview_menu(self, name: str): """ Delete the menu item, with the given name, from the list view menu. Args: name (str) - Name of the menu item (e.g. 'Open'). """ if self.api: registry.deregister_listview_menu(name) self.api.delete_listview_menu(name) def add_import_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable) -> str: """ Add menu item, with corresponding callbacks, to the Import combo box. Args: name (str): Name of the menu item, this name must be unique across the menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature: void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. Returns: str: Name of menu item if successful, None otherwise. """ if self.api: registry.register_import_menu(name, glyph, click_fn, show_fn) self.api.add_import_menu(name, glyph, click_fn, show_fn) def delete_import_menu(self, name: str): """ Delete the menu item, with the given name, from the Import combo box. Args: name (str): Name of the menu item. """ if self.api: registry.deregister_import_menu(name) self.api.delete_import_menu(name) def add_file_open_handler(self, name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or path submitted to browser bar. Function signature: void open_fn(full_path: str), full_path is the file's system path. file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(full_path: str). Returns: str - Name if successful, None otherwise. """ if self.api: registry.register_file_open_handler(name, open_fn, file_type) return self.api.add_file_open_handler(name, open_fn, file_type) return None def delete_file_open_handler(self, name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ if self._window: registry.deregister_file_open_handler(name) self.api.delete_file_open_handler(name) def get_file_open_handler(self, url: str) -> Callable: """ Returns the matching file open handler for the given file path. Args: url str: The url of the file to open. """ if self.api: return self.api.get_file_open_handler(url) def set_search_delegate(self, delegate: SearchDelegate): """ Sets a custom search delegate for the tool bar. Args: delegate (SearchDelegate): Object that creates the search widget. """ if self.api: registry.register_search_delegate(delegate) self.api.set_search_delegate(delegate) def unset_search_delegate(self, delegate: SearchDelegate): """ Clears the custom search delegate for the tool bar. Args: delegate (:obj:`SearchDelegate`): Object that creates the search widget. """ if self.api: registry.deregister_search_delegate(delegate) self.api.set_search_delegate(None) def decorate_from_registry(self, event: carb.events.IEvent): if not self.api: return try: # Ensure event is for the content window payload = event.payload.get_dict() if payload.get('title') != "Content": return except Exception as e: return # Add custom menu functions for id, args in registry.custom_menus().items(): context, name = id.split('::') if not context or not name: continue if context == "context": self.api.add_context_menu(args['name'], args['glyph'], args['click_fn'], args['show_fn'], args['index']) elif context == "listview": self.api.add_listview_menu(args['name'], args['glyph'], args['click_fn'], args['show_fn'], args['index']) elif context == "import": self.api.add_import_menu(args['name'], args['glyph'], args['click_fn'], args['show_fn']) elif context == "file_open": self.api.add_file_open_handler(args['name'], args['click_fn'], args['show_fn']) else: pass # Add custom selection handlers for handler in registry.selection_handlers(): self.api.subscribe_selection_changed(handler) # Set search delegate if any if registry.search_delegate(): self.api.set_search_delegate(registry.search_delegate()) def show_model(self, model: FileBrowserModel): """ Displays the given model in the list view, overriding the default model. For example, this model might be the result of a search. Args: model (FileBrowserModel): Model to display. """ if self.api: self.api.show_model(model) def toggle_grid_view(self, show_grid_view: bool): """ Toggles file picker between grid and list view. Args: show_grid_view (bool): True to show grid view, False to show list view. """ if self._window: self._window.widget._view.toggle_grid_view(show_grid_view) def toggle_bookmark_from_path(self, name: str, path: str, is_bookmark: bool, is_folder: bool = True) -> bool: """ Adds/deletes the given bookmark with the specified path. If deleting, then the path argument is optional. Args: name (str): Name to call the bookmark or existing name if delete. path (str): Path to the bookmark. is_bookmark (bool): True to add, False to delete. is_folder (bool): Whether the item to be bookmarked is a folder. Returns: bool: True if successful. """ if self.api: self.api.toggle_bookmark_from_path(name, path, is_bookmark, is_folder=is_folder) def refresh_current_directory(self): """Refreshes the current directory set in the browser bar.""" if self.api: self.api.refresh_current_directory() def get_checkpoint_widget(self) -> 'CheckpointWidget': """Returns the checkpoint widget""" if self._window: return self._window.widget._checkpoint_widget return None def get_timestamp_widget(self) -> 'TimestampWidget': """Returns the timestamp widget""" if self._window: return self._window.widget._timestamp_widget return None def get_instance(): global g_singleton return g_singleton
20,089
Python
37.413002
157
0.616258
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/__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 window extension for browsing filesystem, including Nucleus, content""" __all__ = ['ContentBrowserExtension', 'get_content_window'] FILE_TYPE_USD = 1 FILE_TYPE_IMAGE = 2 FILE_TYPE_SOUND = 3 FILE_TYPE_TEXT = 4 FILE_TYPE_VOLUME = 5 SETTING_ROOT = "/exts/omni.kit.window.content_browser/" SETTING_PERSISTENT_ROOT = "/persistent" + SETTING_ROOT SETTING_PERSISTENT_CURRENT_DIRECTORY = SETTING_PERSISTENT_ROOT + "current_directory" from .extension import ContentBrowserExtension, get_instance from .window import ContentBrowserWindow from .widget import ContentBrowserWidget def get_content_window() -> ContentBrowserExtension: """Returns the singleton content_browser extension instance""" return get_instance()
1,158
Python
37.633332
84
0.784111
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/progress_popup.py
from omni import ui class CustomProgressModel(ui.AbstractValueModel): def __init__(self): super().__init__() self._value = 0.0 def set_value(self, value): """Reimplemented set""" try: value = float(value) except ValueError: value = None if value != self._value: # Tell the widget that the model is changed self._value = value self._value_changed() def get_value_as_float(self): return self._value def get_value_as_string(self): return str(int(self._value * 100)) + "%" class ProgressPopup: """Creates a modal window with a status label and a progress bar inside. Args: title (str): Title of this window. cancel_button_text (str): It will have a cancel button by default. This is the title of it. cancel_button_fn (function): The callback after cancel button is clicked. status_text (str): The status text. min_value: The min value of the progress bar. It's 0 by default. max_value: The max value of the progress bar. It's 100 by default. dark_style: If it's to use dark style or light style. It's dark stye by default. """ def __init__(self, title, cancel_button_text="Cancel", cancel_button_fn=None, status_text="", modal=True): self._status_text = status_text self._title = title self._cancel_button_text = cancel_button_text self._cancel_button_fn = cancel_button_fn self._modal = False self._build_ui() def __del__(self): self._cancel_button_fn = None def __enter__(self): self._popup.visible = True return self def __exit__(self, type, value, trace): self._popup.visible = False def set_cancel_fn(self, on_cancel_button_clicked): self._cancel_button_fn = on_cancel_button_clicked def set_progress(self, progress): self._progress_bar.model.set_value(progress) def get_progress(self): return self._progress_bar.model.get_value_as_float() progress = property(get_progress, set_progress) def set_status_text(self, status_text): self._status_label.text = status_text def get_status_text(self): return self._status_label.text status_text = property(get_status_text, set_status_text) def show(self): self._popup.visible = True def hide(self): self._popup.visible = False def is_visible(self): return self._popup.visible def centre_in_window(self, widget): width = self._popup.frame.computed_width or 392 height = self._popup.frame.computed_height or 95 self._popup.position_x = ((widget.computed_width - width)/2) + widget.screen_position_x self._popup.position_y = ((widget.computed_height - height)/2) + widget.screen_position_y def _on_cancel_button_fn(self): self.hide() if self._cancel_button_fn: self._cancel_button_fn() def _build_ui(self): self._popup = ui.Window(self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED) self._popup.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_CLOSE ) if self._modal: self._popup.flags = self._popup.flags | ui.WINDOW_FLAGS_MODAL with self._popup.frame: with ui.VStack(height=0): ui.Spacer(height=10) with ui.HStack(height=0): ui.Spacer() self._status_label = ui.Label(self._status_text, width=0, height=0) ui.Spacer() ui.Spacer(height=10) with ui.HStack(height=0): ui.Spacer() self._progress_bar_model = CustomProgressModel() self._progress_bar = ui.ProgressBar( self._progress_bar_model, width=300, style={"color": 0xFFFF9E3D} ) ui.Spacer() ui.Spacer(height=5) with ui.HStack(height=0): ui.Spacer(height=0) cancel_button = ui.Button(self._cancel_button_text, width=0, height=0) cancel_button.set_clicked_fn(self._on_cancel_button_fn) ui.Spacer(height=0) ui.Spacer(width=0, height=10)
4,600
Python
33.593985
112
0.574783
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/test_helper.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.ui_test as ui_test import omni.ui as ui import omni.kit.app from typing import List, Dict from omni.kit.widget.filebrowser import FileBrowserItem from .extension import get_instance class ContentBrowserTestHelper: """Test helper for the content browser window""" async def __aenter__(self): return self async def __aexit__(self, *args): pass async def toggle_grid_view_async(self, show_grid_view: bool): """ Toggles the list view between the grid and tree layouts. Args: show_grid_view (bool): If True, set the layout to grid, otherwise tree. """ content_browser = get_instance() if content_browser: content_browser.toggle_grid_view(show_grid_view) await ui_test.human_delay(10) async def navigate_to_async(self, url: str): """ Navigates to the given url, expanding all parent directories along the path. Args: url (str): The url to navigate to. """ content_browser = get_instance() if content_browser: await content_browser.navigate_to_async(url) async def get_item_async(self, url: str) -> FileBrowserItem: """ Retrieves an item by its url. Args: url (str): Url of the item. Returns: FileBrowserItem """ content_browser = get_instance() if content_browser: return await content_browser.api.model.find_item_async(url) return None async def select_items_async(self, dir_url: str, names: List[str]) -> List[FileBrowserItem]: """ Selects display items by their names. Args: dir_url (str): Url of the parent folder. names (List[str]): Names of items to select. Returns: List[FileBrowserItem]: List of selected items. """ content_browser = get_instance() selections = [] if content_browser: selections = await content_browser.select_items_async(dir_url, names) await ui_test.human_delay(10) return selections async def get_treeview_item_async(self, name: str) -> ui_test.query.WidgetRef: """ Retrieves the ui_test widget of the tree view item by name. Args: name (str): Label name of the widget. Returns: ui_test.query.WidgetRef """ if name: tree_view = ui_test.find("Content//Frame/**/TreeView[*].identifier=='content_browser_treeview'") widget = tree_view.find(f"**/Label[*].text=='{name}'") if widget: widget.widget.scroll_here(0.5, 0.5) await ui_test.human_delay(10) return widget return None async def get_gridview_item_async(self, name: str): # get content window widget ref in grid view if name: grid_view = ui_test.find("Content//Frame/**/VGrid[*].identifier=='content_browser_treeview_grid_view'") widget = grid_view.find(f"**/Label[*].text=='{name}'") if widget: widget.widget.scroll_here(0.5, 0.5) await ui_test.human_delay(10) return widget return None async def drag_and_drop_tree_view(self, url: str, names: List[str] = [], drag_target: ui_test.Vec2 = (0,0)): """ Drag and drop items from the tree view. Args: url (str): Url of the parent folder. names (List[str]): Names of items to drag. drag_target (ui_test.Vec2): Screen location to drop the item. """ await self.toggle_grid_view_async(False) selections = await self.select_items_async(url, names) if selections: item = selections[-1] widget = await self.get_treeview_item_async(item.name) if widget: await widget.drag_and_drop(drag_target) for i in range(10): await omni.kit.app.get_app().next_update_async() async def refresh_current_directory(self): content_browser = get_instance() if content_browser: content_browser.refresh_current_directory() async def get_config_menu_settings(self) -> Dict: """ Returns settings from the config menu as a dictionary. Returns: Dict """ content_browser = get_instance() if content_browser: widget = content_browser._window._widget config_menu = widget._tool_bar._config_menu return config_menu.get_values() return {} async def set_config_menu_settings(self, settings: Dict): """ Writes to settings of the config menu. """ content_browser = get_instance() if content_browser: widget = content_browser._window._widget config_menu = widget._tool_bar._config_menu for setting, value in settings.items(): config_menu.set_value(setting, value) # wait for window to update await ui_test.human_delay(50)
5,643
Python
31.813953
115
0.591707
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/context_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 carb.settings from omni.kit.window.filepicker.context_menu import UdimContextMenu, CollectionContextMenu, BookmarkContextMenu, ConnectionContextMenu from omni.kit.window.filepicker.context_menu import ContextMenu as FilePickerContextMenu from .file_ops import * from omni.kit.widget.filebrowser import save_items_to_clipboard, get_clipboard_items class ContextMenu(FilePickerContextMenu): """ Creates popup menu for the hovered FileBrowserItem. In addition to the set of default actions below, users can add more via the add_menu_item API. """ def __init__(self, **kwargs): super().__init__(**kwargs) try: import omni.usd omni_usd_supported = True except Exception: omni_usd_supported = False if omni_usd_supported: self.add_menu_item( "Open", "show.svg", lambda menu, url: open_file(url), lambda url: get_file_open_handler(url) != None, index=0, ) self.add_menu_item( "Open With Payloads Disabled", "show.svg", lambda menu, url: open_file(url, load_all=False), lambda url: get_file_open_handler(url) != None, index=1, ) self.add_menu_item( "Open With New Edit Layer", "external_link.svg", lambda menu, url: open_stage_with_new_edit_layer(url), lambda url: omni.usd.is_usd_writable_filetype(url), index=2, ) self.add_menu_item( "Copy", "copy.svg", lambda menu, _: save_items_to_clipboard(self._context["selected"]), # OM-94626: can't copy when select nothing lambda url: len(self._context["selected"]) >= 1, index=-2, ) self.add_menu_item( "Cut", "none.svg", lambda menu, _: cut_items(self._context["selected"], self._view), lambda url: self._context["item"].writeable and len(self._context["selected"]) >= 1, ) self.add_menu_item( "Paste", "copy.svg", lambda menu, url: paste_items(self._context["item"], get_clipboard_items(), view=self._view), lambda url: self._context["item"].is_folder and self._context["item"].writeable and\ len(self._context["selected"]) <= 1 and len(get_clipboard_items()) > 0, index=-2, ) self.add_menu_item( "Download", "cloud_download.svg", lambda menu, _: download_items(self._context["selected"]), # OM-94626: can't download when select nothing lambda url: len(self._context["selected"]) >= 1 and \ carb.settings.get_settings().get_as_bool("exts/omni.kit.window.content_browser/show_download_menuitem"), index=3, separator_name="_placeholder_" )
3,480
Python
39.476744
134
0.582759
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.client import asyncio from typing import Union, Callable, List, Optional from carb import log_error, log_info from collections import OrderedDict, namedtuple from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerModel, asset_types from . import FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME FileOpenAction = namedtuple("FileOpenAction", "name open_fn matching_type") class ContentBrowserModel(FilePickerModel): """The model class for :obj:`ContentBrowserWidget`.""" def __init__(self, item_filter_fn=None, timeout=3.0): super().__init__(timeout=timeout) self._file_open_dict = OrderedDict() self._on_selection_changed_subs = set() self._item_filter_fn = item_filter_fn def add_file_open_handler(self, name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or url submitted to browser bar. Function signature: void open_fn(url: str). file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(url: str). Returns: str: Name if successful, None otherwise. """ if name: self._file_open_dict[name] = FileOpenAction(name, open_fn, file_type) return name else: return None def delete_file_open_handler(self, name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ if name and name in self._file_open_dict: self._file_open_dict.pop(name) def get_file_open_handler(self, url: str) -> Callable: """ Returns the matching file open handler for the given item. Args: url str: The url of the item to open. """ if not url: return None broken_url = omni.client.break_url(url) # Note: It's important that we use an ordered dict so that we can search by order # of insertion. for _, tup in self._file_open_dict.items(): _, open_fn, file_type = tup if isinstance(file_type, Callable): if file_type(broken_url.path): return open_fn else: asset_type = { FILE_TYPE_USD: asset_types.ASSET_TYPE_USD, FILE_TYPE_IMAGE: asset_types.ASSET_TYPE_IMAGE, FILE_TYPE_SOUND: asset_types.ASSET_TYPE_SOUND, FILE_TYPE_TEXT: asset_types.ASSET_TYPE_SCRIPT, FILE_TYPE_VOLUME: asset_types.ASSET_TYPE_VOLUME, }.get(file_type, None) if asset_type and asset_types.is_asset_type(broken_url.path, asset_type): return open_fn return None async def open_stage_async(self, url: str, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): """ Async function for opening a USD file. Args: url (str): Url to file. """ try: import omni.kit.window.file omni.kit.window.file.open_stage(url, open_loadset) except Exception as e: log_error(str(e)) else: log_info(f"Success! Opened '{url}'.\n") async def open_with_new_edit_layer(self, url: str, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): """ Async function for opening a USD file, then creating a new layer. Args: url (str): Url to file. """ try: import omni.kit.window.file omni.kit.window.file.open_with_new_edit_layer(url, open_loadset) except Exception as e: log_error(str(e)) else: log_info(f"Success! Opened '{url}' with new edit layer.\n") def download_items_with_callback(self, src_urls: List[str], dst_urls: List[str], callback: Optional[Callable] = None): """ Downloads specified items. Upon success, executes the given callback. Args: src_urls (List[str]): Paths of items to download. dst_urls (List[str]): Destination paths. callback (Callable): Callback to execute upon success. Function signature is void callback([str]). Raises: :obj:`Exception` """ try: self.copy_items_with_callback(src_urls, dst_urls, callback=callback) except Exception: raise def subscribe_selection_changed(self, fn: Callable): """ Subscribes to file selection changes. Args: fn (Callable): callback function when file selection changed. """ self._on_selection_changed_subs.add(fn) def unsubscribe_selection_changed(self, fn: Callable): """ Unsubscribes this callback from selection changes. Args: fn (Callable): callback function when file selection changed. """ if fn in self._on_selection_changed_subs: self._on_selection_changed_subs.remove(fn) def notify_selection_subs(self, pane: int, selected: [FileBrowserItem]): for fn in self._on_selection_changed_subs or []: async def async_cb(pane: int, selected: [FileBrowserItem]): # Making sure callback was not removed between async schedule/execute if fn in self._on_selection_changed_subs: fn(pane, selected) asyncio.ensure_future(async_cb(pane, selected)) def destroy(self): super().destroy() if self._file_open_dict: self._file_open_dict.clear() self._file_open_dict = None if self._on_selection_changed_subs: self._on_selection_changed_subs.clear() self._on_selection_changed_subs = None
6,889
Python
35.455026
122
0.608797
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/prompt.py
import omni import omni.ui as ui from .style import ICON_PATH class Prompt: def __init__( self, title, text, content_buttons, modal=False, ): self._title = title self._text = text self._content_buttons = content_buttons self._modal = modal self._buttons = [] self._build_ui() def __del__(self): for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() def show(self): self._window.visible = True def hide(self): self._window.visible = False def is_visible(self): return self._window.visible def _build_ui(self): import carb.settings self._window = ui.Window( self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED ) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) if self._modal: self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" button_style = { "Button": {"stack_direction": ui.Direction.LEFT_TO_RIGHT}, "Button.Image": {"alignment": ui.Alignment.CENTER}, "Button.Label": {"alignment": ui.Alignment.LEFT_CENTER} } def button_cliked_fn(button_fn): if button_fn: button_fn() self.hide() with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=10) if self._text: with ui.HStack(height=0): ui.Spacer() self._text_label = ui.Label(self._text, word_wrap=True, width=self._window.width - 80, height=0) ui.Spacer() ui.Spacer(width=0, height=10) with ui.VStack(height=0): ui.Spacer(height=0) for button in self._content_buttons: (button_text, button_icon, button_fn) = button with ui.HStack(): ui.Spacer(width=40) ui_button = ui.Button( " " + button_text, image_url=f"{ICON_PATH}/{button_icon}", image_width=24, height=40, clicked_fn=lambda a=button_fn: button_cliked_fn(a), style=button_style ) ui.Spacer(width=40) ui.Spacer(height=5) self._buttons.append(ui_button) ui.Spacer(height=5) with ui.HStack(): ui.Spacer() cancel_button = ui.Button("Cancel", width=80, height=0) cancel_button.set_clicked_fn(lambda: self.hide()) self._buttons.append(cancel_button) ui.Spacer(width=40) ui.Spacer(height=0) ui.Spacer(width=0, height=10)
3,461
Python
33.969697
120
0.469806
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/api.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio from typing import List, Callable, Union from omni.kit.window.filepicker import FilePickerAPI from omni.kit.widget.filebrowser import FileBrowserItem from .file_ops import add_file_open_handler, delete_file_open_handler, get_file_open_handler class ContentBrowserAPI(FilePickerAPI): """This class defines the API methods for :obj:`ContentBrowserWidget`.""" def __init__(self): super().__init__() self._on_selection_changed_subs = set() def add_import_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable) -> str: """ Adds menu item, with corresponding callbacks, to the Import combo box. Args: name (str): Name of the menu item, this name must be unique across the menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature: void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. Returns: str: Name of menu item if successful, None otherwise. """ if self.tool_bar: import_menu = self.tool_bar.import_menu if import_menu: return import_menu.add_menu_item(name, glyph, click_fn, show_fn) return None def delete_import_menu(self, name: str): """ Deletes the menu item, with the given name, from the Import combo box. Args: name (str): Name of the menu item. """ if self.tool_bar: import_menu = self.tool_bar.import_menu if import_menu: import_menu.delete_menu_item(name) def add_file_open_handler(self, name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or path submitted to browser bar. Function signature: void open_fn(full_path: str), full_path is the file's system path. file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(full_path: str). Returns: str: Name if successful, None otherwise. """ return add_file_open_handler(name, open_fn, file_type) def delete_file_open_handler(self, name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ delete_file_open_handler(name) def get_file_open_handler(self, url: str) -> Callable: """ Returns the matching file open handler for the given file path. Args: url str: The url of the file to open. """ return get_file_open_handler(url) def subscribe_selection_changed(self, fn: Callable): """ Subscribes to file selection changes. Args: fn (Callable): callback function when file selection changed. """ self._on_selection_changed_subs.add(fn) def unsubscribe_selection_changed(self, fn: Callable): """ Unsubscribe this callback from selection changes. Args: fn (Callable): callback function when file selection changed. """ if fn in self._on_selection_changed_subs: self._on_selection_changed_subs.remove(fn) def _notify_selection_subs(self, pane: int, selected: List[FileBrowserItem]): for fn in self._on_selection_changed_subs or []: async def async_cb(pane: int, selected: List[FileBrowserItem]): # Making sure callback was not removed between async schedule/execute if fn in self._on_selection_changed_subs: fn(pane, selected) asyncio.ensure_future(async_cb(pane, selected)) def destroy(self): super().destroy() if self._on_selection_changed_subs: self._on_selection_changed_subs.clear()
5,183
Python
37.977443
121
0.634382
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tool_bar.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Optional import omni.ui as ui from omni.kit.window.filepicker import ToolBar as FilePickerToolBar, BaseContextMenu from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.widget.options_menu import OptionsModel, OptionItem from omni.kit.widget.filter import FilterButton from .style import get_style, ICON_PATH class ImportMenu(BaseContextMenu): def __init__(self, **kwargs): super().__init__(title="Import menu", **kwargs) self._menu_dict = [] self._offset_x = kwargs.get("offset_x", -1) self._offset_y = kwargs.get("offset_y", 1) def show_relative(self, parent: ui.Widget, item: Optional[FileBrowserItem] = None): if item and len(self._menu_dict) > 0: self.show(item) if parent: self.menu.show_at( parent.screen_position_x + self._offset_x, parent.screen_position_y + parent.computed_height + self._offset_y, ) def destroy(self): super().destroy() self._menu_dict = [] class ToolBar(FilePickerToolBar): def __init__(self, **kwargs): self._import_button = None self._import_menu = None self._filter_button = None self._filter_values_changed_handler = kwargs.get("filter_values_changed_handler", None) self._import_menu = kwargs.pop("import_menu", ImportMenu()) super().__init__(**kwargs) def _build_ui(self): with ui.HStack(height=0, style=get_style(), style_type_name_override="ToolBar"): with ui.VStack(width=0): ui.Spacer() self._import_button = ui.Button( "Import ", image_url=f"{ICON_PATH}/plus.svg", image_width=12, height=24, spacing=4, style_type_name_override="ToolBar.Button", name="import", ) self._import_button.set_clicked_fn( lambda: self._import_menu and self._import_menu.show_relative(self._import_button, self._current_directory_provider()) ) ui.Spacer() super()._build_ui() def _build_widgets(self): ui.Spacer(width=2) self._build_filter_button() def _build_filter_button(self): filter_items = [ OptionItem("audio", text="Audio"), OptionItem("materials", text="Materials"), OptionItem("scripts", text="Scripts"), OptionItem("textures", text="Textures"), OptionItem("usd", text="USD"), OptionItem("volumes", text="Volumes"), ] with ui.VStack(width=0): ui.Spacer() self._filter_button = FilterButton(filter_items, menu_width=150) ui.Spacer() def on_filter_changed(model: OptionsModel, _): if self._filter_values_changed_handler: values = {} for item in self._filter_button.model.get_item_children(): values[item.name] = item.value self._filter_values_changed_handler(values) self.__sub_filter = self._filter_button.model.subscribe_item_changed_fn(on_filter_changed) @property def import_menu(self): return self._import_menu @property def filter_values(self): if self._filter_button: values = {} for item in self._filter_button.model.get_item_children(): values[item.name] = item.value return values return {} def destroy(self): super().destroy() self._import_button = None if self._filter_button: self.__sub_filter = None self._filter_button.destroy() self._filter_button = None self._filter_values_changed_handler = None
4,393
Python
35.616666
112
0.581152
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/widget.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import omni.kit.app import carb import carb.settings import omni.client from typing import List, Dict from omni.kit.helper.file_utils import asset_types from omni.kit.window.filepicker import FilePickerWidget from omni.kit.widget.filebrowser import FileBrowserItem, LISTVIEW_PANE from omni.kit.widget.versioning import CheckpointModel, CheckpointItem from .api import ContentBrowserAPI from .context_menu import ContextMenu, UdimContextMenu, CollectionContextMenu, BookmarkContextMenu, ConnectionContextMenu from .tool_bar import ToolBar from .file_ops import get_file_open_handler, open_file, open_stage, drop_items from . import FILE_TYPE_USD, SETTING_ROOT, SETTING_PERSISTENT_CURRENT_DIRECTORY # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class ContentBrowserWidget(FilePickerWidget): """The Content Browser widget""" def __init__(self, **kwargs): # Retrieve settings settings = carb.settings.get_settings() # OM-75244: Remember the last browsed directory upon Content Browser open kwargs["treeview_identifier"] = kwargs.get('treeview_identifier', None) kwargs["settings_root"] = SETTING_ROOT kwargs["enable_checkpoints"] = settings.get_as_bool("exts/omni.kit.window.content_browser/enable_checkpoints") kwargs["enable_timestamp"] = settings.get_as_bool("exts/omni.kit.window.content_browser/enable_timestamp") kwargs["show_only_collections"] = settings.get("exts/omni.kit.window.content_browser/show_only_collections") # Hard-coded configs kwargs["allow_multi_selection"] = True kwargs["enable_file_bar"] = False kwargs["drop_handler"] = lambda dst, src: drop_items(dst, [src]) kwargs["item_filter_fn"] = self._item_filter_fn # OM-77963: Make use of environment variable to disable check for soft-delete features in Content Browser kwargs["enable_soft_delete"] = True if os.getenv("OMNI_FEATURE_SOFT_DELETE", "0") == "1" else False # Additional fields self._visible_asset_types = [] # Inject cusdtomized API kwargs["api"] = ContentBrowserAPI() # Initialize and build the widget super().__init__("Content", **kwargs) def destroy(self): super().destroy() if self._visible_asset_types: self._visible_asset_types.clear() self._visible_asset_types = None def _build_tool_bar(self): """Overrides base builder, injects custom tool bar""" self._tool_bar = ToolBar( visited_history_size=20, current_directory_provider=lambda: self._view.get_root(LISTVIEW_PANE), branching_options_handler=self._api.find_subdirs_with_callback, apply_path_handler=self._open_and_navigate_to, toggle_bookmark_handler=self._api.toggle_bookmark_from_path, config_values_changed_handler=lambda _: self._apply_config_options(), filter_values_changed_handler=lambda _: self._apply_filter_options(), begin_edit_handler=self._on_begin_edit, prefix_separator="://", search_delegate=self._default_search_delegate, enable_soft_delete=self._enable_soft_delete, ) def _build_checkpoint_widget(self): """Overrides base builder, adds items to context menu""" super()._build_checkpoint_widget() # Add context menu to checkpoints def on_restore_checkpoint(cp: CheckpointItem, model: CheckpointModel): path = model.get_url() restore_path = path + "?" + cp.entry.relative_path model.restore_checkpoint(path, restore_path) # Create checkpoints context menu self._checkpoint_widget.add_context_menu( "Open", "show.svg", lambda menu, cp: (open_file(cp.get_full_url()) if cp else None), None, index=0, ) self._checkpoint_widget.add_context_menu( "Open With Payloads Disabled", "show.svg", lambda menu, cp: (open_file(cp.get_full_url(), load_all=False) if cp else None), None, index=1, ) self._checkpoint_widget.add_context_menu( "", "", None, None, index=98, ) self._checkpoint_widget.add_context_menu( "Restore Checkpoint", "restore.svg", lambda menu, cp: on_restore_checkpoint(cp, self._checkpoint_widget._model), lambda menu, cp: 1 if (cp and cp.get_relative_path()) else 0, index=99, ) # Open checkpoint file on double click self._checkpoint_widget.set_mouse_double_clicked_fn( lambda b, k, cp: (open_file(cp.get_full_url()) if cp else None)) def _build_context_menus(self): """Overrides base builder, injects custom context menus""" self._context_menus = dict() self._context_menus['item'] = ContextMenu(view=self._view, checkpoint=self._checkpoint_widget) self._context_menus['list_view'] = ContextMenu(view=self._view, checkpoint=self._checkpoint_widget) self._context_menus['collection'] = CollectionContextMenu(view=self._view) self._context_menus['connection'] = ConnectionContextMenu(view=self._view) self._context_menus['bookmark'] = BookmarkContextMenu(view=self._view) self._context_menus['udim'] = UdimContextMenu(view=self._view) # Register open handler for usd files if self._api: self._api.add_file_open_handler("usd", open_stage, FILE_TYPE_USD) def _get_mounted_servers(self) -> Dict: """Overrides base getter, returns mounted server dict from settings""" # OM-85963 Fixes flaky unittest: test_mount_default_servers. Purposely made this a function in order to inject test data. settings = carb.settings.get_settings() mounted_servers = {} try: mounted_servers = settings.get_settings_dictionary("exts/omni.kit.window.content_browser/mounted_servers").get_dict() except Exception: pass # OM-71835: Auto-connect server specified in the setting. We normally don't make the connection on startup # due to possible delays; however, we make this exception to facilitate the streaming workflows. return mounted_servers, True def _on_mouse_double_clicked(self, pane: int, button: int, key_mod: int, item: FileBrowserItem): if not item: return if button == 0 and not item.is_folder: if self._timestamp_widget: url = self._timestamp_widget.get_timestamp_url(item.path) else: url = item.path open_file(url) def _on_selection_changed(self, pane: int, selected: List[FileBrowserItem] = []): super()._on_selection_changed(pane, selected) if self._api: self._api._notify_selection_subs(pane, selected) # OM-75244: record the last browsed directory settings = carb.settings.get_settings() settings.set(SETTING_PERSISTENT_CURRENT_DIRECTORY, self._current_directory) def _open_and_navigate_to(self, url: str): if not url: return # Make sure url is normalized before trying to open as file. url = omni.client.normalize_url(url.strip()) if get_file_open_handler(url): # If there's a suitable file open handler then execute in a separate thread open_file(url) # Navigate to the file location self._api.navigate_to(url) def _apply_filter_options(self): map_filter_options = { "audio": asset_types.ASSET_TYPE_SOUND, "materials": asset_types.ASSET_TYPE_MATERIAL, "scripts": asset_types.ASSET_TYPE_SCRIPT, "textures": asset_types.ASSET_TYPE_IMAGE, "usd": asset_types.ASSET_TYPE_USD, "volumes": asset_types.ASSET_TYPE_VOLUME, } visible_types = [] settings = self._tool_bar.filter_values for label, visible in settings.items(): if visible: visible_types.append(map_filter_options[label]) self._visible_asset_types = visible_types self._refresh_ui() def _item_filter_fn(self, item: FileBrowserItem) -> bool: """ Default item filter callback. Returning True means the item is visible. Args: item (:obj:`FileBrowseritem`): Item in question. Returns: bool """ # Show items of unknown asset types? asset_type = asset_types.get_asset_type(item.path) if not self._visible_asset_types: # Visible asset types not specified if asset_type == asset_types.ASSET_TYPE_UNKNOWN: return self._show_unknown_asset_types else: return True return asset_type in self._visible_asset_types
9,631
Python
42.192825
130
0.643028
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/file_ops.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import asyncio import omni.client import carb.settings import omni.kit.notification_manager import omni.kit.app from typing import Callable, List, Union from datetime import datetime from functools import lru_cache, partial from collections import OrderedDict, namedtuple from carb import log_warn, log_info from typing import Callable, List from omni.kit.helper.file_utils import asset_types from omni.kit.widget.filebrowser import FileBrowserItem, is_clipboard_cut, save_items_to_clipboard, clear_clipboard from omni.kit.widget.filebrowser.model import FileBrowserItemFields from omni.kit.window.file_exporter import get_file_exporter from omni.kit.window.filepicker.item_deletion_dialog import ConfirmItemDeletionDialog from omni.kit.window.filepicker.utils import get_user_folders_dict from omni.kit.window.filepicker.view import FilePickerView from omni.kit.window.filepicker.file_ops import * from .prompt import Prompt from . import FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME FileOpenAction = namedtuple("FileOpenAction", "name open_fn matching_type") _file_open_dict = OrderedDict() @lru_cache() def __get_input() -> carb.input.IInput: return carb.input.acquire_input_interface() def _is_ctrl_down() -> bool: input = __get_input() return ( input.get_keyboard_value(None, carb.input.KeyboardInput.LEFT_CONTROL) + input.get_keyboard_value(None, carb.input.KeyboardInput.RIGHT_CONTROL) > 0 ) def add_file_open_handler(name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or url submitted to browser bar. Function signature: void open_fn(url: str). file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(url: str). Returns: str: Name if successful, None otherwise. """ global _file_open_dict if name: _file_open_dict[name] = FileOpenAction(name, open_fn, file_type) return name else: return None def delete_file_open_handler(name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ global _file_open_dict if name and name in _file_open_dict: _file_open_dict.pop(name) def get_file_open_handler(url: str) -> Callable: """ Returns the matching file open handler for the given item. Args: url str: The url of the item to open. """ if not url: return None broken_url = omni.client.break_url(url) # Note: It's important that we use an ordered dict so that we can search by order # of insertion. global _file_open_dict for _, tup in _file_open_dict.items(): _, open_fn, file_type = tup if isinstance(file_type, Callable): if file_type(broken_url.path): return open_fn else: asset_type = { FILE_TYPE_USD: asset_types.ASSET_TYPE_USD, FILE_TYPE_IMAGE: asset_types.ASSET_TYPE_IMAGE, FILE_TYPE_SOUND: asset_types.ASSET_TYPE_SOUND, FILE_TYPE_TEXT: asset_types.ASSET_TYPE_SCRIPT, FILE_TYPE_VOLUME: asset_types.ASSET_TYPE_VOLUME, }.get(file_type, None) if asset_type and asset_types.is_asset_type(broken_url.path, asset_type): return open_fn return None def copy_items(dst_item: FileBrowserItem, src_paths: List[str]): try: from omni.kit.notification_manager import post_notification except Exception: post_notification = log_warn if dst_item and src_paths: try: def on_copied(results): for result in results: if isinstance(result, Exception): post_notification(str(result)) # prepare src_paths and dst_paths for copy items dst_paths = [] dst_root = dst_item.path for src_path in src_paths: rel_path = os.path.basename(src_path) dst_paths.append(f"{dst_root}/{rel_path}") copy_items_with_callback(src_paths, dst_paths, on_copied) except Exception as e: log_warn(f"Error encountered during copy: {str(e)}") def copy_items_with_callback(src_paths: List[str], dst_paths: List[str], callback: Callable = None, copy_callback: Callable[[str, str, omni.client.Result], None] = None): """ Copies items. Upon success, executes the given callback. Args: src_pathss ([str]): Paths of items to download. dst_paths ([str]): Destination paths. callback (func): Callback to execute upon success. Function signature is void callback(List[Union[Exception, str]). copy_callback (func): Callback per every copy. Function signature is void callback([str, str, omni.client.Result]). Raises: :obj:`Exception` """ if not (dst_paths and src_paths): return tasks = [] # should not get here, but just to be safe, if src_paths and dst_paths are not of the same length, don't copy if len(src_paths) != len(dst_paths): carb.log_warn( f"Cannot copy items from {src_paths} to {dst_paths}, source and destination paths should match in number.") return for src_path, dst_path in zip(src_paths, dst_paths): tasks.append(copy_item_async(src_path, dst_path, callback=copy_callback)) try: asyncio.ensure_future(exec_tasks_async(tasks, callback=callback)) except Exception: raise async def copy_item_async(src_path: str, dst_path: str, timeout: float = 300.0, callback: Callable[[str, str, omni.client.Result], None] = None) -> str: """ Async function. Copies item (recursively) from one path to another. Note: this function simply uses the copy function from omni.client and makes no attempt to optimize for copying from one Omniverse server to another. For that, use the Copy Service. Example usage: await copy_item_async("my_file.usd", "C:/tmp", "omniverse://ov-content/Users/me") Args: src_path (str): Source path to item being copied. dst_path (str): Destination path to copy the item. timeout (float): Number of seconds to try before erroring out. Default 10. callback (func): Callback to copy result. Returns: str: Destination path name Raises: :obj:`RuntimeWarning`: If error or timeout. """ if isinstance(timeout, (float, int)): timeout = max(300, timeout) try: # OM-67900: add source url in copied item checkpoint src_checkpoint = None result, entries = await omni.client.list_checkpoints_async(src_path) if result == omni.client.Result.OK and entries: src_checkpoint = entries[-1].relative_path checkpoint_msg = f"Copied from {src_path}" if src_checkpoint: checkpoint_msg = f"{checkpoint_msg}?{src_checkpoint}" result, _ = await omni.client.stat_async(dst_path) if result == omni.client.Result.OK: dst_name = os.path.basename(dst_path) async def on_overwrite(dialog): result = await asyncio.wait_for( omni.client.copy_async( src_path, dst_path, behavior=omni.client.CopyBehavior.OVERWRITE, message=checkpoint_msg), timeout=timeout) if callback: callback(src_path, dst_path, result) dialog.hide() def on_cancel(dialog): dialog.hide() dialog = ConfirmItemDeletionDialog( title="Confirm File Overwrite", message="You are about to overwrite", items=[FileBrowserItem(dst_path, FileBrowserItemFields(dst_name, datetime.now(), 0, 0), is_folder=False)], ok_handler=lambda dialog: asyncio.ensure_future(on_overwrite(dialog)), cancel_handler=lambda dialog: on_cancel(dialog), ) dialog.show() else: result = await asyncio.wait_for(omni.client.copy_async(src_path, dst_path, message=checkpoint_msg), timeout=timeout) if callback: callback(src_path, dst_path, result) except asyncio.TimeoutError: raise RuntimeWarning(f"Error unable to copy '{src_path}' to '{dst_path}': Timed out after {timeout} secs.") except Exception as e: raise RuntimeWarning(f"Error copying '{src_path}' to '{dst_path}': {e}") if result != omni.client.Result.OK: raise RuntimeWarning(f"Error copying '{src_path}' to '{dst_path}': {result}") return dst_path def drop_items(dst_item: FileBrowserItem, src_paths: List[str], callback: Callable = None): # src_paths is a list of str but when multiple items are selected, the str was a \n joined path string, so # we need to re-construct the src_paths paths = src_paths[0].split("\n") # remove any udim_sequence as that are not real files for path in paths.copy(): if asset_types.is_udim_sequence(path): paths.remove(path) if not paths: return # OM-52387: drag and drop is now move instead of copy; # Additionally, drag with ctrl down would be copy similar to windows file explorer if _is_ctrl_down(): copy_items(dst_item, paths) else: # warn user for move operation since it will overwrite items with the same name in the dst folder from omni.kit.window.popup_dialog import MessageDialog def on_okay(dialog: MessageDialog, dst_item: FileBrowserItem, paths: List[str], callback: Callable=None): move_items(dst_item, paths, callback=callback) dialog.hide() warning_msg = f"This will replace any file with the same name in {dst_item.path}." dialog = MessageDialog( title="MOVE", message="Do you really want to move these files?", warning_message=warning_msg, ok_handler=lambda dialog, dst_item=dst_item, paths=paths, callback=callback: on_okay( dialog, dst_item, paths, callback), ok_label="Confirm", ) dialog.show() def cut_items(src_items: List[FileBrowserItem], view: FilePickerView): if not src_items: return save_items_to_clipboard(src_items, is_cut=True) # to maintain the left treeview pane selection, only update listview for filebrowser view._filebrowser.refresh_ui(listview_only=True) def paste_items(dst_item: FileBrowserItem, src_items: List[FileBrowserItem], view: FilePickerView): src_paths = [item.path for item in src_items] # if currently the clipboard is for cut operation, then use move if is_clipboard_cut(): def _on_cut_pasted(dst_item, src_items, view): # sync up item changes for src and dst items to_update = set([dst_item]) for item in src_items: to_update.add(item.parent) for item in to_update: view._filebrowser._models.sync_up_item_changes(item) # clear clipboard and update item style clear_clipboard() view._filebrowser.refresh_ui(listview_only=True) drop_items(dst_item, ["\n".join(src_paths)], callback=lambda: _on_cut_pasted(dst_item, src_items, view)) # else use normal copy else: copy_items(dst_item, src_paths) def open_file(url: str, load_all=True): async def open_file_async(open_fn: Callable, url: str, load_all=True): result, entry = await omni.client.stat_async(url) if result == omni.client.Result.OK: # OM-57423: Make sure this is not a folder is_folder = (entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) > 0 if is_folder: return if open_fn: import inspect sig = inspect.signature(open_fn) if sig and "load_all" in sig.parameters: if asyncio.iscoroutinefunction(open_fn): await open_fn(url, load_all) else: open_fn(url, load_all) return if asyncio.iscoroutinefunction(open_fn): await open_fn(url) else: open_fn(url) open_fn = get_file_open_handler(url) if open_fn: asyncio.ensure_future(open_file_async(open_fn, url, load_all)) # Register file open handler for USD's def open_stage(url, load_all=True): result, entry = omni.client.stat(url) if result == omni.client.Result.OK: read_only = entry.access & omni.client.AccessFlags.WRITE == 0 else: read_only = False if read_only: def _open_with_edit_layer(): open_stage_with_new_edit_layer(url, load_all) def _open_original_stage(): asyncio.ensure_future(open_stage_async(url, load_all)) _show_readonly_usd_prompt(_open_with_edit_layer, _open_original_stage) else: asyncio.ensure_future(open_stage_async(url, load_all)) async def open_stage_async(url: str, load_all=True): """ Async function for opening a USD file. Args: url (str): Url to file. """ try: import omni.kit.window.file if load_all: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_ALL else: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE omni.kit.window.file.open_stage(url, open_loadset) except Exception as e: log_warn(str(e)) else: log_info(f"Success! Opened '{url}'.\n") def open_stage_with_new_edit_layer(url: str, load_all=True): """ Async function for opening a USD file, then creating a new layer. Args: url (str): Url to file. """ try: import omni.usd import omni.kit.window.file if load_all: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_ALL else: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE omni.kit.window.file.open_with_new_edit_layer(url, open_loadset) except Exception as e: log_warn(str(e)) else: log_info(f"Success! Opened '{url}' with new edit layer.\n") def download_items(selections: List[FileBrowserItem]): if not selections: return def on_download(src_items: List[FileBrowserItem], filename: str, dirname: str): if ':/' in filename or filename.startswith('\\\\'): # Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://'; # the second finds MS network paths that start like '\\analogfs\VENDORS\...' dst_root = os.path.dirname(filename) else: dst_root = os.path.dirname(f"{(dirname or '').rstrip('/')}/{filename}") # OM-65721: When downloading a single item, should use the filename provided dst_name = None # for single item, rename by user input if len(src_items) == 1: dst_name = os.path.basename(filename) _, src_ext = os.path.splitext(src_items[0].path) # make sure ext is included if user didn't input it # TODO: here the assumption is that we don't want to download a file as another file format, so # appending if the filename input didn't end with the current ext if not dst_name.endswith(src_ext): dst_name = dst_name + src_ext if src_items and dst_root: # prepare src_paths and dst_paths for download items src_paths = [] dst_paths = [] for src_item in src_items: src_paths.append(src_item.path) dst_root = dst_root.rstrip("/") if dst_name: dst_path = f"{dst_root}/{dst_name}" # if not specified, or user typed in an empty name, use the source path basename instead else: dst_path = f"{dst_root}/{os.path.basename(src_item.path)}" dst_paths.append(dst_path) try: # Callback to handle exceptions def __notify(results: List[Union[Exception, str]]): for result in results: if isinstance(result, Exception): omni.kit.notification_manager.post_notification(str(result)) # Callback to handle copy result def __copy_notify(src: str, dst: str, result: omni.client.Result): if result == omni.client.Result.OK: omni.kit.notification_manager.post_notification(f"{src} downloaded") else: omni.kit.notification_manager.post_notification(f"Error copying '{src}' to '{dst}': {result}") copy_items_with_callback(src_paths, dst_paths, callback=__notify, copy_callback=__copy_notify) except Exception as e: log_warn(f"Error encountered during download: {str(e)}") file_exporter = get_file_exporter() if file_exporter: # OM-65721: Pre-populate the filename field for download; use original file/folder name for single selection # and "<multiple selected>" to indicate multiple items are selected (in this case downloaded item will use) # their source names # TODO: Is it worth creating a constant (either on this class or in this module) for this? selected_filename = "<multiple selected>" is_single_selection = len(selections) == 1 if is_single_selection: _, selected_filename = os.path.split(selections[0].path) # OM-73142: Resolve to the actual download directory download_dir = get_user_folders_dict().get("Downloads", "") file_exporter.show_window( title="Download Files", show_only_collections=["my-computer"], file_postfix_options=[None], file_extension_types=[("*", "All files")], export_button_label="Save", export_handler=lambda filename, dirname, **kwargs: on_download(selections, filename, dirname), filename_url=f"{download_dir}/{selected_filename}", enable_filename_input=is_single_selection, # OM-99158: Fix issue with apply button disabled when multiple items are selected for download show_only_folders=True, ) _open_readonly_usd_prompt = None def _show_readonly_usd_prompt(ok_fn, middle_fn): global _open_readonly_usd_prompt _open_readonly_usd_prompt = Prompt( "Opening a Read Only File", "", [ ("Open With New Edit Layer", "open_edit_layer.svg", ok_fn), ("Open Original File", "pencil.svg", middle_fn), ], modal=False ) _open_readonly_usd_prompt.show()
19,991
Python
37.819417
170
0.62148
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/window.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 weakref from .widget import ContentBrowserWidget from .external_drag_drop_helper import setup_external_drag_drop, destroy_external_drag_drop class ContentBrowserWindow: """The Content Browser window""" def __init__(self): self._title = "Content" self._window = None self._widget = None self._visiblity_changed_listener = None self._build_ui(self._title, 1000, 600) def _build_ui(self, title, width, height): window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window( title, width=width, height=height, flags=window_flags, dockPreference=ui.DockPreference.LEFT_BOTTOM ) self._window.set_visibility_changed_fn(self._visibility_changed_fn) # Dock it to the same space where Console is docked, make it the first tab and the active tab. self._window.deferred_dock_in("Console", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self._window.dock_order = 2 with self._window.frame: # We are using `weakref.proxy` to avoid circular reference. The # circular reference is made when calling `set_width_changed_fn`. # `self._widget` is captured to the callable, and since the window # keeps the callable, it keeps self._widget. At the same time, # `self._widget` keeps the window because we pass it to the # constructor. To break circular referencing, we use # `weakref.proxy`. self._widget = ContentBrowserWidget( window=weakref.proxy(self._window), treeview_identifier="content_browser_treeview", ) self._window.set_width_changed_fn(self._widget._on_window_width_changed) # External Drag & Drop setup_external_drag_drop(title, self._widget, self._window.frame) def _visibility_changed_fn(self, visible): if self._visiblity_changed_listener: self._visiblity_changed_listener(visible) @property def widget(self) -> ContentBrowserWidget: return self._widget def set_visibility_changed_listener(self, listener): self._visiblity_changed_listener = listener def destroy(self): if self._widget: self._widget.destroy() self._widget = None if self._window: self._window.destroy() self._window = None self._visiblity_changed_listener = None destroy_external_drag_drop() def set_visible(self, value): self._window.visible = value def get_visible(self): if self._window: return self._window.visible return False
3,143
Python
37.814814
111
0.655743
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_drag_drop.py
import omni.kit.test import os import random import shutil import tempfile from unittest.mock import patch from pathlib import Path import omni.appwindow from omni import ui from carb.input import KeyboardInput from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from ..test_helper import ContentBrowserTestHelper from ..extension import get_instance class TestDragDrog(AsyncTestCase): """Testing ContentBrowser drag and drop behavior""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass def _prepare_test_dir(self, temp_dir): # make sure we start off clean if os.path.exists(temp_dir): os.rmdir(temp_dir) os.mkdir(temp_dir) src_paths = [] # create a file under test dir, and a folder containg a file; with open(os.path.join(temp_dir, "test.mdl"), "w") as _: pass src_paths.append("test.mdl") test_folder_path = os.path.join(temp_dir, "src_folder") os.mkdir(test_folder_path) with open(os.path.join(test_folder_path, "test_infolder.usd"), "w") as _: pass src_paths.extend(["src_folder", "src_folder/test_infolder.usd"]) # create the destination folder dst_folder_path = os.path.join(temp_dir, "dst_folder") os.mkdir(dst_folder_path) return src_paths, dst_folder_path def _get_child_paths(self, root_dir): paths = [] def _iter_listdir(root): for p in os.listdir(root): full_path = os.path.join(root, p) if os.path.isdir(full_path): yield full_path for child in _iter_listdir(full_path): yield child else: yield full_path for p in _iter_listdir(root_dir): paths.append(p.replace(root_dir, "").replace("\\", "/").lstrip("/")) return paths async def test_drop_to_move(self): """Testing drop items would move items inside the destination.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) src_paths, dst_path = self._prepare_test_dir(temp_dir) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.toggle_grid_view_async(False) await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(dst_path) await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(temp_dir) await ui_test.human_delay(100) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) target_item = await content_browser_helper.get_treeview_item_async("dst_folder") if not target_item: return await content_browser_helper.drag_and_drop_tree_view( temp_dir, src_paths[:-1], drag_target=target_item.position) await ui_test.human_delay(20) window = ui_test.find("MOVE") self.assertIsNotNone(window) await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay(20) # files should be moved inside dst folder self.assertTrue(len(os.listdir(temp_dir)) == 1) self.assertTrue(os.path.exists(dst_path)) results = self._get_child_paths(os.path.join(temp_dir, dst_path)) self.assertEqual(set(results), set(src_paths)) # Cleanup shutil.rmtree(temp_dir) async def test_drop_to_copy(self): """Testing drop with CTRL pressed copies items.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) src_paths, dst_path = self._prepare_test_dir(temp_dir) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.toggle_grid_view_async(False) await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(dst_path) await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(temp_dir) await ui_test.human_delay(100) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) target_item = await content_browser_helper.get_treeview_item_async("dst_folder") if not target_item: return async with ui_test.KeyDownScope(KeyboardInput.LEFT_CONTROL): await content_browser_helper.drag_and_drop_tree_view( temp_dir, src_paths[:-1], drag_target=target_item.position) await ui_test.human_delay(10) # files should be copied inside dst folder self.assertTrue(len(os.listdir(temp_dir)) == 3) # source paths should still exist for src_path in src_paths: self.assertTrue(os.path.exists(os.path.join(temp_dir, src_path))) # source paths should also be copied in dst folder self.assertTrue(os.path.exists(dst_path)) results = self._get_child_paths(os.path.join(temp_dir, dst_path)) self.assertEqual(set(results), set(src_paths)) # Cleanup shutil.rmtree(temp_dir) class TestExternalDragDrog(AsyncTestCase): """Testing ContentBrowser external drag and drop behavior""" async def setUp(self): await ui_test.find("Content").focus() # hide viewport to avoid drop fn triggered for viewport ui.Workspace.show_window("Viewport", False) window = ui_test.find("Content") await ui_test.emulate_mouse_move(window.center) content_browser = get_instance() content_browser.set_current_directory("/test/target") async def tearDown(self): pass async def test_external_drop_copy(self): """Testing external drop triggers copy.""" with patch.object(omni.client, "copy_async", return_value=omni.client.Result.OK) as mock_client_copy: # simulate drag/drop omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': ["dummy"]}) await ui_test.human_delay(20) mock_client_copy.assert_called_once() async def test_external_drop_existing_item(self): """Testing external drop with existing item prompts user for deletion.""" with patch.object(omni.client, "stat_async", return_value=(omni.client.Result.OK, None)) as mock_client_stat: # simulate drag/drop omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': ["dummy"]}) await ui_test.human_delay(20) mock_client_stat.assert_called_once() confirm_deletion = ui_test.find("Confirm File Overwrite") self.assertTrue(confirm_deletion.window.visible)
7,427
Python
39.590164
117
0.620035
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_registry.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 from unittest.mock import patch, Mock from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from ..api import ContentBrowserAPI from .. import get_instance class TestRegistry(AsyncTestCase): """Testing Content Browser Registry""" async def setUp(self): pass async def tearDown(self): pass async def test_custom_menus(self): """Test persisting custom menus""" test_menus = { "context": { "name": "my context menu", "glyph": "my glyph", "click_fn": Mock(), "show_fn": Mock(), }, "listview": { "name": "my listview menu", "glyph": "my glyph", "click_fn": Mock(), "show_fn": Mock(), }, "import": { "name": "my import menu", "glyph": None, "click_fn": Mock(), "show_fn": Mock(), }, "file_open": { "context": "file_open", "name": "my file_open handler", "glyph": None, "click_fn": Mock(), "show_fn": Mock(), } } # Register menus under_test = get_instance() for context, test_menu in test_menus.items(): if context == "context": under_test.add_context_menu(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "listview": under_test.add_listview_menu(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "import": under_test.add_import_menu(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "file_open": under_test.add_file_open_handler(test_menu["name"], test_menu["click_fn"], test_menu["show_fn"]) else: pass with patch.object(ContentBrowserAPI, "add_context_menu") as mock_add_context_menu,\ patch.object(ContentBrowserAPI, "add_listview_menu") as mock_add_listview_menu,\ patch.object(ContentBrowserAPI, "add_import_menu") as mock_add_import_menu,\ patch.object(ContentBrowserAPI, "add_file_open_handler") as mock_add_file_open_handler: # Hide then show window again under_test.show_window(None, False) await ui_test.human_delay(4) under_test.show_window(None, True) await ui_test.human_delay(4) # Confirm all mocks got called with appropriate inputs for context, test_menu in test_menus.items(): if context == "context": mock_add_context_menu.assert_called_with(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"], 0) elif context == "listview": mock_add_listview_menu.assert_called_with(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"], -1) elif context == "import": mock_add_import_menu.assert_called_with(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "file_open": mock_add_file_open_handler.assert_called_with(test_menu["name"], test_menu["click_fn"], test_menu["show_fn"]) else: pass async def test_selection_handlers(self): """Test persisting selection handlers""" test_handler_1 = Mock() test_handler_2 = Mock() test_handlers = [test_handler_1, test_handler_2, test_handler_1] under_test = get_instance() for test_handler in test_handlers: under_test.subscribe_selection_changed(test_handler) with patch.object(ContentBrowserAPI, "subscribe_selection_changed") as mock_subscribe_selection_changed: # Hide then show window again under_test.show_window(None, False) await ui_test.human_delay(4) under_test.show_window(None, True) await ui_test.human_delay(4) self.assertEqual(mock_subscribe_selection_changed.call_count, 2) async def test_search_delegate(self): """Test persisting search delegate""" test_search_delegate = Mock() under_test = get_instance() under_test.set_search_delegate(test_search_delegate) # Confirm search delegate restored from registry with patch.object(ContentBrowserAPI, "set_search_delegate") as mock_set_search_delegate: # Hide then show window again under_test.show_window(None, False) await ui_test.human_delay(4) under_test.show_window(None, True) await ui_test.human_delay(4) mock_set_search_delegate.assert_called_with(test_search_delegate)
5,454
Python
42.29365
145
0.585075
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_widget.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 carb import omni.kit.test import omni.client from omni.kit import ui_test from unittest.mock import patch from ..widget import ContentBrowserWidget from ..api import ContentBrowserAPI from .. import get_content_window, SETTING_PERSISTENT_CURRENT_DIRECTORY class TestContentBrowserWidget(omni.kit.test.AsyncTestCase): async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): # Clear all bookmarks saved by omni.client, as a result of mounting test servers pass async def wait_for_update(self, wait_frames=20): for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() async def test_mount_default_servers(self): """Testing that the widget mounts the server specified from the settings""" content_browser = get_content_window() under_test = content_browser.window.widget test_servers = {"my-server": "omniverse://my-server", "her-server": "omniverse://her-server"} # Re-run init_view to confirm that the the widget adds the servers specified in # the settings. OM-85963: Mock out all the actual calls to connect the servers because # they trigger a host of other actions, incl. callbacks on bookmarks changed, that make # this test unreliable. with patch.object(ContentBrowserWidget, "_get_mounted_servers", return_value=(test_servers, True)),\ patch.object(ContentBrowserAPI, "add_connections") as mock_add_connections,\ patch.object(ContentBrowserAPI, "connect_server") as mock_connect_server,\ patch.object(ContentBrowserAPI, "subscribe_client_bookmarks_changed"): # Initialize the view and expect to mount servers under_test._init_view(None, None) # Check that widget attempted to add list of servers specified in settings mock_add_connections.assert_called_once_with(test_servers) # Check that widget attempted to connect to first server in list mock_connect_server.assert_called_once_with(test_servers['my-server'])
2,552
Python
46.277777
108
0.716301
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/__init__.py
## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .test_extension import * from .test_navigate import * from .test_test_helper import * from .test_registry import * from .test_widget import * from .test_download import * from .test_drag_drop import * from .test_rename import * from .test_cut_paste import * from .test_prompt import *
731
Python
37.526314
77
0.77565
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_prompt.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 from omni.kit import ui_test from ..prompt import Prompt class TestPrompt(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_prompt(self): """Testing Prompt window""" prompt = Prompt( "TestPrompt", "TestLabel", [ ("test_button", "pencil.svg", None), ], modal=False ) prompt.hide() self.assertFalse(prompt.is_visible()) prompt.show() self.assertTrue(prompt.is_visible()) button = ui_test.find("TestPrompt//Frame/**/Button[*].text==' test_button'") await button.click() #self.assertFalse(prompt.is_visible()) del prompt
1,228
Python
32.216215
85
0.640065
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_extension.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 asyncio import omni.kit.app from unittest.mock import Mock, patch, ANY from .. import get_content_window from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path from omni.kit.helper.file_utils import FILE_OPENED_EVENT from omni.kit.widget.filebrowser import is_clipboard_cut, get_clipboard_items, clear_clipboard class MockItem: def __init__(self, path: str): self.name = path self.path = path self.writeable = True self.is_folder = True self.is_deleted = False class TestContentBrowser(omni.kit.test.AsyncTestCase): """ Testing omni.kit.window.content_browser extension. NOTE that since the dialog is a singleton, we use an async lock to ensure that only one test runs at a time. In practice, this is not a issue since there's only one instance in the app. """ __lock = asyncio.Lock() async def setUp(self): pass async def wait_for_update(self, wait_frames=20): for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() async def tearDown(self): pass async def test_set_search_delegate(self): """Testing that hiding the window destroys it""" mock_search_delegate = Mock() async with self.__lock: under_test = get_content_window() await self.wait_for_update() under_test.set_search_delegate(mock_search_delegate) under_test.unset_search_delegate(mock_search_delegate) mock_search_delegate.build_ui.assert_called_once() async def test_open_event(self): """Testing that on open event should auto navigate""" under_test = get_content_window() event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream.push(FILE_OPENED_EVENT, payload={"url": get_test_data_path(__name__, "bound_shapes.usda")}) with patch.object(under_test, "navigate_to") as mock: await ui_test.human_delay(50) mock.assert_called_once() event_stream.push(FILE_OPENED_EVENT, payload={"url": get_test_data_path(__name__, "bound_shapes.usda")}) async def test_interface(self): """Testing all simple interface""" under_test = get_content_window() under_test.set_current_directory("omniverse:/") self.assertEqual(under_test.get_current_directory(), "omniverse:/") self.assertEqual(under_test.get_current_selections(), []) under_test.show_model(None) def dummy(*args, **kwargs): pass under_test.subscribe_selection_changed(dummy) under_test.unsubscribe_selection_changed(dummy) under_test.delete_context_menu("test") under_test.toggle_bookmark_from_path("", "omniverse:/", False) #under_test.add_checkpoint_menu("test", "", None, None) #under_test.delete_checkpoint_menu("test") under_test.add_listview_menu("test", "", None, None) under_test.delete_listview_menu("test") under_test.add_import_menu("test", "", None, None) under_test.delete_import_menu("test") self.assertEqual(under_test.get_file_open_handler("test"), None) under_test.add_file_open_handler("test", dummy, None) under_test.delete_file_open_handler("test") self.assertIsNotNone(under_test.api) self.assertIsNotNone(under_test.get_checkpoint_widget()) self.assertIsNone(under_test.get_timestamp_widget()) async def test_api(self): """Testing rest api interface""" api = get_content_window().api self.assertIsNotNone(api) #api._post_warning("test") def dummy(*args, **kwargs): pass api.subscribe_selection_changed(dummy) api._notify_selection_subs(2, []) return mock_item_list = [MockItem(str(i)) for i in range(10)] with patch.object(api.view, "get_selections", return_value=mock_item_list) as mock: api.copy_selected_items() mock.assert_called_once() self.assertFalse(is_clipboard_cut()) mock.reset_mock() api.cut_selected_items() self.assertEqual(get_clipboard_items(), mock_item_list) mock.assert_called_once() with patch.object(api.view, "get_selections", return_value=mock_item_list) as mock: api.delete_selected_items() mock.assert_called_once() mock_item_list1 = [MockItem("test")] with patch("omni.kit.widget.filebrowser.get_clipboard_items", return_value=mock_item_list) as mock, \ patch.object(api.view, "get_selections", return_value=mock_item_list1) as mock2: api.paste_items() api.clear_clipboard() mock2.assert_called_once()
5,291
Python
41.677419
119
0.650539
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_rename.py
import omni.kit.test import os import random import shutil import tempfile from pathlib import Path from unittest.mock import patch from omni import ui from carb.input import KeyboardInput from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from ..test_helper import ContentBrowserTestHelper # FIXME: Currently force this to run before test_navigate, since it was not easy to close out the # "add neclues connection" window in test class TestFileRename(AsyncTestCase): """Testing ContentBrowserWidget drag and drop behavior""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass def _prepare_test_dir(self, temp_dir, temp_file): # make sure we start off clean if os.path.exists(temp_dir): os.rmdir(temp_dir) os.makedirs(temp_dir) with open(os.path.join(temp_dir, temp_file), "w") as _: pass async def test_rename_file(self): """Testing renaming a file.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) filename = "temp.mdl" self._prepare_test_dir(temp_dir, filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(50) await content_browser_helper.navigate_to_async(temp_dir) await ui_test.human_delay(50) await content_browser_helper.toggle_grid_view_async(True) await ui_test.human_delay(50) t = await content_browser_helper.get_item_async(temp_dir + "/" + filename) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(50) item = await content_browser_helper.get_gridview_item_async(filename) if item is None: return await item.right_click() await ui_test.human_delay() return await ui_test.select_context_menu("Rename") popup = ui.Workspace.get_window(f"Rename {filename}") self.assertIsNotNone(popup) self.assertTrue(popup.visible) def dummy(*args, **kwargs): return "dummy.txt" with patch( "omni.kit.window.popup_dialog.InputDialog.get_value", side_effect=dummy ): await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay(10) # file should have been renamed to dummy.txt now self.assertFalse(os.path.exists(os.path.join(temp_dir, filename))) self.assertTrue(os.path.exists(os.path.join(temp_dir, "dummy.txt"))) await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) # Cleanup shutil.rmtree(temp_dir) async def test_rename_folder(self): """Testing renaming a folder.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) src_folder = os.path.join(temp_dir, "test_folder") filename = "temp.mdl" self._prepare_test_dir(src_folder, filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() # TODO: need to refresh the browser item here, but why await content_browser_helper.navigate_to_async(src_folder) await content_browser_helper.navigate_to_async(temp_dir) t = await content_browser_helper.get_item_async(src_folder) await content_browser_helper.toggle_grid_view_async(True) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(50) item = await content_browser_helper.get_gridview_item_async("test_folder") if item is None: return await item.right_click() await ui_test.human_delay() return await ui_test.select_context_menu("Rename") popup = ui.Workspace.get_window("Rename test_folder") self.assertIsNotNone(popup) self.assertTrue(popup.visible) def dummy(*args, **kwargs): return "renamed_folder" with patch( "omni.kit.window.popup_dialog.InputDialog.get_value", side_effect=dummy ): await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay(20) # file should have been renamed to dummy.txt now self.assertFalse(os.path.exists(src_folder)) renamed_folder = os.path.join(temp_dir, "renamed_folder") self.assertTrue(os.path.exists(renamed_folder)) self.assertTrue(os.path.exists(os.path.join(renamed_folder, filename))) await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) # Cleanup shutil.rmtree(temp_dir)
5,535
Python
38.827338
100
0.618428
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_download.py
import omni.kit.test import os from pathlib import Path from tempfile import TemporaryDirectory, NamedTemporaryFile from unittest.mock import patch, Mock import omni.ui as ui import carb.settings from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.window.file_exporter import get_file_exporter from ..widget import ContentBrowserWidget from ..test_helper import ContentBrowserTestHelper from ..file_ops import download_items from .. import get_content_window from ..context_menu import ContextMenu class TestDownload(AsyncTestCase): """Testing ContentBrowserWidget._download_items""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): # hide download window on test teardown window = ui.Workspace.get_window("Download Files") if window: window.visible = False async def test_no_selection(self): """Testing when nothing is selected, don't open up file exporter.""" # currently marking this as the first test to run since ui.Workspace.get_window result would not # be None if other tests had shown the window once download_items([]) await ui_test.human_delay() window = ui.Workspace.get_window("Download Files") try: self.assertIsNone(window) except AssertionError: # in the case where the window is created, then the window should be invisible self.assertFalse(window.visible) async def test_single_selection(self): """Testing when downloading with a single item selected.""" with TemporaryDirectory() as tmpdir_fd: # need to resolve to deal with the abbreviated user filename such as "LINE8~1" tmpdir = Path(tmpdir_fd).resolve() temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False) temp_fd.close() _, filename = os.path.split(temp_fd.name) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.refresh_current_directory() await content_browser_helper.navigate_to_async(str(tmpdir)) items = await content_browser_helper.select_items_async(str(tmpdir), [filename]) await ui_test.human_delay() with patch("omni.kit.notification_manager.post_notification") as mock_post_notification: self.assertEqual(len(items), 1) download_items(items) await ui_test.human_delay(10) file_exporter = get_file_exporter() self.assertIsNotNone(file_exporter) # the filename for file exporter should be pre-filled (same as the source filename) self.assertEqual(file_exporter._dialog.get_filename(), filename) # the filename field should enable input self.assertTrue(file_exporter._dialog._widget._enable_filename_input) file_exporter._dialog.set_current_directory(str(tmpdir)) await ui_test.human_delay() window = ui.Workspace.get_window("Download Files") self.assertTrue(window.visible) file_exporter._dialog.set_filename("dummy") file_exporter.click_apply() await ui_test.human_delay(10) # should have created a downloaded file in the same directory, with the same extension self.assertTrue(tmpdir.joinpath("dummy.mdl").exists) mock_post_notification.assert_called_once() async def test_multi_selection(self): """Testing when downloading with multiple items selected.""" with TemporaryDirectory() as tmpdir_fd: # need to resolve to deal with the abbreviated user filename such as "LINE8~1" tmpdir = Path(tmpdir_fd).resolve() temp_files = [] for _ in range(2): temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False) temp_fd.close() _, filename = os.path.split(temp_fd.name) temp_files.append(filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.refresh_current_directory() await content_browser_helper.navigate_to_async(str(tmpdir)) items = await content_browser_helper.select_items_async(str(tmpdir), temp_files) await ui_test.human_delay() with patch("omni.kit.notification_manager.post_notification") as mock_post_notification: self.assertEqual(len(items), len(temp_files)) download_items(items) await ui_test.human_delay(10) file_exporter = get_file_exporter() self.assertIsNotNone(file_exporter) window = ui.Workspace.get_window("Download Files") self.assertTrue(window.visible) # the filename field should disable input self.assertFalse(file_exporter._dialog._widget._enable_filename_input) with TemporaryDirectory() as another_tmpdir_fd: dst_tmpdir = Path(another_tmpdir_fd) file_exporter._dialog.set_current_directory(str(dst_tmpdir)) await ui_test.human_delay() # OM-99158: Check that the apply button is not disabled self.assertTrue(file_exporter._dialog._widget.file_bar._apply_button.enabled) file_exporter.click_apply() await ui_test.human_delay(10) # should have created downloaded files in the dst directory downloaded_files = [file for file in os.listdir(dst_tmpdir)] self.assertEqual(set(temp_files), set(downloaded_files)) self.assertEqual(mock_post_notification.call_count, len(items)) async def test_multi_results(self): """Testing when downloading with multiple results.""" with TemporaryDirectory() as tmpdir_fd: # need to resolve to deal with the abbreviated user filename such as "LINE8~1" tmpdir = Path(tmpdir_fd).resolve() temp_files = [] for _ in range(3): temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False) temp_fd.close() _, filename = os.path.split(temp_fd.name) temp_files.append(filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.refresh_current_directory() await content_browser_helper.navigate_to_async(str(tmpdir)) items = await content_browser_helper.select_items_async(str(tmpdir), temp_files) await ui_test.human_delay() with patch.object(omni.kit.window.content_browser.file_ops, "copy_items_with_callback", side_effect=self._mock_copy_items_with_callback),\ patch("omni.kit.notification_manager.post_notification") as mock_post_notification: self.assertEqual(len(items), len(temp_files)) download_items(items) await ui_test.human_delay(10) file_exporter = get_file_exporter() self.assertIsNotNone(file_exporter) window = ui.Workspace.get_window("Download Files") self.assertTrue(window.visible) # the filename field should disable input self.assertFalse(file_exporter._dialog._widget._enable_filename_input) with TemporaryDirectory() as another_tmpdir_fd: dst_tmpdir = Path(another_tmpdir_fd) file_exporter._dialog.set_current_directory(str(dst_tmpdir)) await ui_test.human_delay() # OM-99158: Check that the apply button is not disabled self.assertTrue(file_exporter._dialog._widget.file_bar._apply_button.enabled) file_exporter.click_apply() await ui_test.human_delay(10) self.assertEqual(mock_post_notification.call_count, len(items)) def _mock_copy_items_with_callback(self, src_paths, dst_paths, callback=None, copy_callback=None): # Fist one succeeded on copy # Second one failed on copy # Thrid has exception during copy copy_callback(src_paths[0], dst_paths[0], omni.client.Result.OK) copy_callback(src_paths[1], dst_paths[1], omni.client.Result.ERROR_NOT_SUPPORTED) expected_results = [dst_paths[0],dst_paths[1], Exception("Test Exception")] callback(expected_results) async def test_show_download_menuitem_setting(self): """Testing show download menuitem setting works as expect.""" old_setting_value = carb.settings.get_settings().get("exts/omni.kit.window.content_browser/show_download_menuitem") item = Mock() item.path = "test" item.is_folder = False item.writeable = True carb.settings.get_settings().set("exts/omni.kit.window.content_browser/show_download_menuitem", True) await ui_test.human_delay(10) menu_with_download = ContextMenu() menu_with_download.show(item, [item]) await ui_test.human_delay(30) menu_dict = await ui_test.get_context_menu(menu_with_download.menu) has_download_menuitem = False for name in menu_dict["_"]: if name == "Download": has_download_menuitem = True self.assertTrue(has_download_menuitem) menu_with_download.destroy() carb.settings.get_settings().set("exts/omni.kit.window.content_browser/show_download_menuitem", False) await ui_test.human_delay(10) menu_without_download = ContextMenu() await ui_test.human_delay(10) menu_without_download.show(item, [item]) menu_dict = await ui_test.get_context_menu(menu_without_download.menu) has_download_menuitem = False for name in menu_dict["_"]: if name == "Download": has_download_menuitem = True self.assertFalse(has_download_menuitem) menu_without_download.destroy() carb.settings.get_settings().set("exts/omni.kit.window.content_browser/show_download_menuitem", old_setting_value)
10,524
Python
46.840909
150
0.624382
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_navigate.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 import omni.client from unittest.mock import patch, Mock from omni.kit import ui_test from omni.kit.test.async_unittest import AsyncTestCase from omni.kit.test_suite.helpers import get_test_data_path from .. import get_content_window class TestNavigate(AsyncTestCase): """Testing ContentBrowserWidget.open_and_navigate_to""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass async def test_file_found_and_opened(self): """Testing when navigating to USD file, opens it""" content_browser = get_content_window() under_test = content_browser.window.widget url = get_test_data_path(__name__, "4Lights.usda") mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): # patch("omni.kit.window.content_browser.widget.open_stage") as mock_open_stage: under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_called_once_with(omni.client.normalize_url(url)) async def test_file_with_spaces_found_and_opened(self): """Testing file with surrounding spaces is correctly found""" content_browser = get_content_window() under_test = content_browser.window.widget url = " " + get_test_data_path(__name__, "4Lights.usda") + " " mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_called_once_with(omni.client.normalize_url(url.strip())) async def test_folder_found_not_opened(self): """Testing when navigating to folder with USD extension, doesn't open it""" content_browser = get_content_window() under_test = content_browser.window.widget url = get_test_data_path(__name__, "folder.usda") mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_not_called() async def test_invalid_usd_path_still_opened(self): """Testing that even if a USD path is invalid, we still try to open it""" content_browser = get_content_window() under_test = content_browser.window.widget url = get_test_data_path(__name__, "not-found.usda") mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_called_once_with(omni.client.normalize_url(url.strip()))
3,449
Python
44.394736
115
0.679327
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_test_helper.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.test import omni.kit.app import omni.usd 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, get_prims, wait_stage_loading, arrange_windows from ..test_helper import ContentBrowserTestHelper class TestDragDropTreeView(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 512) # After running each test async def tearDown(self): await wait_stage_loading() async def test_config_menu_setting(self): await ui_test.find("Content").focus() async with ContentBrowserTestHelper() as content_browser_helper: old_setting = await content_browser_helper.get_config_menu_settings() # TODO: Why this not works as expect? await content_browser_helper.set_config_menu_settings({"test": "test"}) test_dict = await content_browser_helper.get_config_menu_settings() standard_dict = {'hide_unknown': False, 'hide_thumbnails': True, 'show_details': True, 'show_udim_sequence': False} self.assertEqual(test_dict,standard_dict) await content_browser_helper.set_config_menu_settings(old_setting) async def test_select_single_item(self): await ui_test.find("Content").focus() # select file to show info usd_path = get_test_data_path(__name__) async with ContentBrowserTestHelper() as content_browser_helper: selections = await content_browser_helper.select_items_async(usd_path, names=["4Lights.usda"]) await ui_test.human_delay(4) # Verify selections self.assertEqual([sel.name for sel in selections], ['4Lights.usda']) async def test_select_multiple_items(self): await ui_test.find("Content").focus() # select file to show info usd_path = get_test_data_path(__name__) filenames = ["4Lights.usda", "bound_shapes.usda", "quatCube.usda"] async with ContentBrowserTestHelper() as content_browser_helper: selections = await content_browser_helper.select_items_async(usd_path, names=filenames+["nonexistent.usda"]) await ui_test.human_delay(4) # Verify selections self.assertEqual(sorted([sel.name for sel in selections]), sorted(filenames)) async def test_drag_drop_single_item(self): await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) await wait_stage_loading() await ui_test.find("Content").focus() await ui_test.find("Stage").focus() # verify prims usd_context = omni.usd.get_context() stage = usd_context.get_stage() paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader']) # drag/drop files to stage window stage_window = ui_test.find("Stage") drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) async with ContentBrowserTestHelper() as content_browser_helper: for file_path in ["4Lights.usda", "quatCube.usda"]: await content_browser_helper.drag_and_drop_tree_view(get_test_data_path(__name__, file_path), drag_target=drag_target) # verify prims paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube']) async def test_drag_drop_multiple_items(self): await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) await wait_stage_loading() await ui_test.find("Content").focus() await ui_test.find("Stage").focus() # verify prims usd_context = omni.usd.get_context() stage = usd_context.get_stage() paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader']) # drag/drop files to stage window stage_window = ui_test.find("Stage") drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 96) async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__) await content_browser_helper.drag_and_drop_tree_view(usd_path, names=["4Lights.usda", "quatCube.usda"], drag_target=drag_target) # verify prims paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube'])
6,769
Python
58.385964
557
0.679864
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_cut_paste.py
import omni.kit.test from unittest.mock import patch import omni.client from omni import ui from carb.input import KeyboardInput from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path from omni.kit.widget.filebrowser import is_clipboard_cut, get_clipboard_items, clear_clipboard from ..test_helper import ContentBrowserTestHelper class TestCutPaste(AsyncTestCase): """Testing ContentBrowserWidget cut and paste behavior""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass async def test_paste_availability(self): """Testing paste context menu shows up correctly.""" test_dir = get_test_data_path(__name__) test_file = "4Lights.usda" test_folder = "folder.usda" async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async(test_dir) await content_browser_helper.toggle_grid_view_async(True) await ui_test.human_delay(100) item = await content_browser_helper.get_gridview_item_async(test_file) folder_item = await content_browser_helper.get_gridview_item_async(test_folder) if not item: return await item.right_click() await ui_test.human_delay() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertIn("Cut", context_options) self.assertNotIn("Paste", context_options) await ui_test.select_context_menu("Cut") # now paste should be available await ui_test.human_delay() await folder_item.right_click() await ui_test.human_delay() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertIn("Paste", context_options) # paste will not be available if more than one item is selected, but Cut should await content_browser_helper.select_items_async(test_dir, [test_file, test_folder]) await item.right_click() await ui_test.human_delay() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertNotIn("Paste", context_options) self.assertIn("Cut", context_options) clear_clipboard() async def test_cut_and_paste(self): """Testing cut and paste.""" test_dir = get_test_data_path(__name__) test_file = "4Lights.usda" test_folder = "folder.usda" async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async(test_dir) await content_browser_helper.toggle_grid_view_async(True) await ui_test.human_delay(100) item = await content_browser_helper.get_gridview_item_async(test_file) folder_item = await content_browser_helper.get_gridview_item_async(test_folder) if not item: return if not folder_item: return await folder_item.right_click() await ui_test.human_delay() await ui_test.select_context_menu("Cut") # cut clipboard should have one item in it self.assertTrue(is_clipboard_cut()) self.assertEqual(1, len(get_clipboard_items())) self.assertEqual(get_clipboard_items()[0].path.replace("\\", "/").lower(), f"{test_dir}/{test_folder}".replace("\\", "/").lower()) # cut clipboard should still have one item in it, but updated await item.right_click() await ui_test.human_delay() await ui_test.select_context_menu("Cut") self.assertTrue(is_clipboard_cut()) self.assertEqual(1, len(get_clipboard_items())) cut_path = get_clipboard_items()[0].path self.assertEqual(cut_path.replace("\\", "/").lower(), f"{test_dir}/{test_file}".replace("\\", "/").lower()) with patch.object(omni.client, "move_async", return_value=(omni.client.Result.OK, None)) as mock_move: await folder_item.right_click() await ui_test.human_delay() await ui_test.select_context_menu("Paste") await ui_test.human_delay(10) window = ui_test.find("MOVE") self.assertIsNotNone(window) await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay() mock_move.assert_called_once() # clipboard should be cleared now self.assertEqual(get_clipboard_items(), []) self.assertFalse(is_clipboard_cut())
4,918
Python
40.68644
119
0.610207
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_external_drag_drop.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 tempfile import omni.kit.app import omni.usd 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, get_prims, wait_stage_loading, arrange_windows from omni.kit.window.content_browser import get_content_window class TestExternalDragDrop(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 512) # After running each test async def tearDown(self): await wait_stage_loading() async def test_external_drag_drop(self): # position mouse await ui_test.find("Content").click() await ui_test.human_delay() with tempfile.TemporaryDirectory() as tmpdir: test_file = f"{tmpdir}/bound_shapes.usda" # browse to tempdir content_browser = get_content_window() content_browser.navigate_to(str(tmpdir)) await ui_test.human_delay(50) # if target file exists remove if os.path.exists(test_file): os.remove(test_file) # simulate drag/drop item_path = get_test_data_path(__name__, "bound_shapes.usda") omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [item_path]}) await ui_test.human_delay(50) # verify exists self.assertTrue(os.path.exists(test_file))
1,924
Python
36.01923
118
0.678274
omniverse-code/kit/exts/omni.kit.window.content_browser/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [2.6.8] - 2023-01-19 ### Updated - Removed restriction on moving/copying files between servers. ## [2.6.7] - 2023-01-11 ### Updated - Added UDIM support ## [2.6.6] - 2022-12-08 ### Fixed - Bring content_browser window into focus during tests, as Stage window was on top now. ## [2.6.5] - 2022-11-27 ### Updated - Switch out pyperclip with linux-friendly copy & paste ## [2.6.4] - 2022-11-08 ### Updated - Added rename/move features to content browser, UX is similar to Navigator. ## [2.6.3] - 2022-11-15 ### Updated - Updated the docs. ## [2.6.2] - 2022-11-15 ### Fixed - Fix error message when delete a file in content browser(OM-72757) ## [2.6.1] - 2022-11-09 ### Updated - Auto-connects user specified server at startup ## [2.5.9] - 2022-11-07 ### Updated - Add option to overwrite downloading a single file/folder using user input, and pre-populate filename - Downloading with multi-selection will disable filename field input - Added tests for download ## [2.5.8] - 2022-11-03 ### Updated - Persist customizations when window is closed and re-opened. ## [2.5.7] - 2022-11-03 ### Fixed - Restores 'mounted_servers' setting for specifying default server connections. ## [2.5.6] - 2022-11-01 ### Updated - When opening a stage, auto-connect to nucleus. ## [2.5.5] - 2022-10-28 ### Fixed - delete folder in Content browser auto select and center it's parent (OM-65585) ## [2.5.4] - 2022-10-14 ### Fixed - external drag/drop works again (OM-65824) ## [2.5.3] - 2022-09-30 ### Fixed - Set the menu checkbox when the window is appearing ## [2.5.2] - 2022-09-28 ### Updated - Use omni.client instead of carb.settings to store bookmarks. ## [2.5.1] - 2022-09-20 ### Updated - Change menu refresh to use interal async for not block ui. ## [2.5.0] - 2022-08-30 ### Fixed - Refactored thumbnails provider ## [2.4.33] - 2022-07-27 ### Fixed - Fixed the window when changing layout (OM-48414) ## [2.4.32] - 2022-07-26 ### Added - Don't invadvertently try to open directories as USD files during navigation - Strip spaces around Url - Adds unittests for test helper ## [2.4.31] - 2022-07-19 ### Added - Fixes placement of filter menu ## [2.4.30] - 2022-07-13 ### Added - Added test helper. ## [2.4.29] - 2022-07-08 ### Fixed - the issue of 'ContentBrowserExtension' object has no attribute '_window' while calling `shutdown_extensions` function of omni.kit.window.content_browser ## [2.4.28] - 2022-05-11 ### Added - Prevents copying files from one server to another, which currently crashes the app. ## [2.4.27] - 2022-05-03 ### Added - Adds api to retrieve the checkpoint widget. - Adds async option to navigate_to function. ## [2.4.24] - 2022-04-26 ### Added - Restores open with payloads disabled to context menus. ## [2.4.23] - 2022-04-18 ### Added - Limits extent that splitter can be dragged, to prevent breaking. ## [2.4.22] - 2022-04-12 ### Added - Adds splitter to adjust width of detail pane. ## [2.4.21] - 2022-04-11 ### Fixed - Empty window when changing layout (OM-48414) ## [2.4.20] - 2022-04-06 ### Added - Disable unittests from loading at startup. ## [2.4.19] - 2022-04-04 ### Updated - Removed "show real path" option. ## [2.4.18] - 2022-03-31 ### Updated - Removed "Open with payloads disabled" from context menu in widget. ## [2.4.17] - 2022-03-18 ### Updated - Updates search results when directory changed. ## [2.4.16] - 2022-03-18 ### Fixed - `add_import_menu` is permanent and the Import menu is not destroyed when the window is closed ## [2.4.15] - 2022-03-14 ### Updated - Refactored asset type handling ## [2.4.13] - 2022-03-08 ### Updated - Sends external drag drop to search delegate ## [2.4.12] - 2022-02-15 ### Updated - Adds custom search delegate ## [2.4.11] - 2022-01-20 ### Updated - Adds setting to customize what collections are shown ## [2.4.10] - 2021-11-22 ### Updated - Simplified code for building checkpoint widget. ## [2.4.9] - 2021-11-16 ### Updated - Ported search box to filepicker and refactored the tool bar into a shared component. ## [2.4.8] - 2021-09-17 ### Updated - Added widget identifers ## [2.4.7] - 2021-08-13 ### Updated - Added "Open With Payloads Disabled" to checkpoint menu ## [2.4.6] - 2021-08-12 ### Updated - Fixed the "copy URL/description" functions for checkpoints. ## [2.4.5] - 2021-08-09 ### Updated - Smoother update of thumbnails while populating a search filter. ## [2.4.4] - 2021-07-20 ### Updated - Disables "restore checkpoint" action menu for head version ## [2.4.3] - 2021-07-20 ### Updated - Fixes checkoint selection ## [2.4.2] - 2021-07-12 ### Updated - Starts up in tree view if "show_grid_view" setting is set to false. ## [2.4.1] - 2021-07-12 ### Updated - Moved checkpoints panel to new detail view ## [2.3.7] - 2021-06-25 ### Updated - Enabled persistent pane settings ## [2.3.6] - 2021-06-24 ### Updated - Pass open_file to `FilePickerView` - `get_file_open_handler` ignore checkpoint ## [2.3.5] - 2021-06-21 ### Updated - Update the directory path from either tree or list view. ## [2.3.4] - 2021-06-10 ### Updated - Menu options are persistent ## [2.3.3] - 2021-06-08 ### Updated - When "show checkpoints" unchecked, the panel is hidden and remains so. ## [2.3.2] - 2021-06-07 ### Updated - Added splitter bar for resizing checkpoints panel. - Refactored checkpoints panel and zoom bar into FilePickerView widget. - More thorough destruction of class instances upon shutdown. ## [2.3.1] - 2021-05-18 ### Updated - Eliminates manually initiated refresh of the UI when creating new folder, deleting items, and copying items; these conflict with auto refresh. ### [2.2.2] - 2021-04-09 ### Changes - Added drag/drop support from outside kit ## [2.2.1] - 2021-04-09 ### Changed - Show <head> entry in versioning pane. ## [2.2.0] - 2021-03-19 ### Added - Supported drag and drop from versioning pane. ## [2.1.3] - 2021-02-16 ### Updated - Fixes thumbnails for search model. ## [2.1.2] - 2021-02-10 ### Changes - Updated StyleUI handling ## [2.1.1] - 2021-02-09 ### Updated - Fixed navigation slowness caused by processing of thumbnails. - Uses auto thumbnails generated by deeptag if manual thumbnails not available. ## [2.1.0] - 2021-02-04 ### Added - Added `subscribe_selection_changed` to extension interface. - Added optional versioning pane on supported server (only when omni.kit.widget.versioning is enabled). ## [2.0.0] - 2021-01-03 ### Updated - Refactored for async directory listing to improve overall stability in case of network delays. ## [1.8.10] - 2020-12-10 ### Updated - UI speedup: Opens file concurrently with navigating to path. ## [1.8.9] - 2020-12-5 ### Updated - Adds 'reconnect server' action to context menu ## [1.8.8] - 2020-12-03 ### Updated - Adds ability to rename connections and bookmarks ## [1.8.7] - 2020-12-01 ### Updated - Renamed to just "Content". - Applies visibility filter to search results. ## [1.8.6] - 2020-11-26 ### Updated - Defaults browser bar to display real path ## [1.8.5] - 2020-11-25 ### Updated - Adds file_open set of APIs to open files with user specified apps. - Pasting a URL into browser bar opens the file. ## [1.8.4] - 2020-11-23 ### Updated - Allows multi-selection copies. ## [1.8.3] - 2020-11-20 ### Updated - Allows multi-selection deletion. - Updates and scrolls to download folder upon downloading files. ## [1.8.2] - 2020-11-19 ### Updated - Allows multi-selection downloads. ## [1.8.1] - 2020-11-06 ### Added - Keep connections and bookmarks between content browser and filepicker in sync. ## [1.8.0] - 2020-10-31 ### Added - Now able to resolve URL paths pasted into the browser bar ## [1.7.1] - 2020-10-30 ### Fixed - Fix reference leak when shutting down content browser ## [1.7.0] - 2020-10-29 ### Added - API methods to add menu items to the import button - User folders to "my-computer" collection - Refactored Options Menu into generic popup_dialog window - Fixed opening of USD files and updated to use the open_stage function from omni.kit.window.file ## [1.6.0] - 2020-10-27 ### Added - Ported context menu to omni.kit.window.filepicker. - Consolidated API methods into api module. ## [1.0.0] - 2020-10-14 ### Added - Initial commit for internal release.
8,285
Markdown
23.808383
154
0.686421
omniverse-code/kit/exts/omni.kit.window.content_browser/docs/README.md
# Kit Content Browser Extension [omni.kit.window.content_browser] The Content Browser extension
97
Markdown
23.499994
65
0.814433
omniverse-code/kit/exts/omni.kit.window.content_browser/docs/index.rst
omni.kit.window.content_browser ############################### A window extension for browsing Omniverse content. .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.window.content_browser :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: :imported-members:
334
reStructuredText
17.61111
50
0.631737
omniverse-code/kit/exts/omni.kit.window.content_browser/docs/Overview.md
# Overview A window extension for browsing filesystem, including Nucleus, content
82
Markdown
26.666658
70
0.829268
omniverse-code/kit/exts/omni.usd.schema.omniscripting/pxr/OmniScriptingSchemaTools/__init__.py
# #==== # Copyright (c) 2020, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _omniScriptingSchemaTools from pxr import Tf Tf.PrepareModule(_omniScriptingSchemaTools, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,689
Python
28.649122
100
0.711664
omniverse-code/kit/exts/omni.usd.schema.omniscripting/pxr/OmniScriptingSchemaTools/_omniScriptingSchemaTools.pyi
from __future__ import annotations import pxr.OmniScriptingSchemaTools._omniScriptingSchemaTools import typing __all__ = [ "applyOmniScriptingAPI", "removeOmniScriptingAPI" ] def applyOmniScriptingAPI(*args, **kwargs) -> None: pass def removeOmniScriptingAPI(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'omniScriptingSchemaTools'
362
unknown
21.687499
61
0.743094
omniverse-code/kit/exts/omni.usd.schema.omniscripting/pxr/OmniScriptingSchema/_omniScriptingSchema.pyi
from __future__ import annotations import pxr.OmniScriptingSchema._omniScriptingSchema import typing import Boost.Python import pxr.Usd __all__ = [ "OmniScriptingAPI" ] class OmniScriptingAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateOmniScriptingScriptsAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetOmniScriptingScriptsAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'omniScriptingSchema'
1,031
unknown
26.157894
89
0.646945
omniverse-code/kit/exts/omni.usd.schema.omniscripting/pxr/OmniScriptingSchema/__init__.py
# # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _omniScriptingSchema from pxr import Tf Tf.PrepareModule(_omniScriptingSchema, locals()) del Tf try: from . import __DOC __DOC.Execute(locals()) del __DOC except Exception: pass
1,518
Python
32.755555
100
0.735178
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/PACKAGE-LICENSES/omni.kit.filebrowser_column.acl-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/config/extension.toml
[package] version = "1.0.0" authors = ["NVIDIA"] title = "Access Column in Content Browser" description="The column that is showing the access flags of the file." readme = "docs/README.md" repository = "" keywords = ["column", "filebrowser", "content", "tag"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.client" = {} "omni.kit.widget.filebrowser" = {} [[python.module]] name = "omni.kit.filebrowser_column.acl" # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.filebrowser_column.acl.tests" [[test]] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", ] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", ]
787
TOML
23.624999
80
0.696315
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/acl_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. # from .acl_delegate import AclDelegate from omni.kit.widget.filebrowser import ColumnDelegateRegistry import omni.ext class AclExtension(omni.ext.IExt): def on_startup(self, ext_id): self._subscription = ColumnDelegateRegistry().register_column_delegate("ACL", AclDelegate) def on_shutdown(self): self._subscription = None
782
Python
38.149998
98
0.78133
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/__init__.py
from .acl_extension import AclExtension
40
Python
19.49999
39
0.85
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/acl_delegate.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.widget.filebrowser import ColumnItem from omni.kit.widget.filebrowser import AbstractColumnDelegate import asyncio import carb import functools import omni.client import omni.ui as ui import traceback def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except asyncio.CancelledError: pass except Exception as e: carb.log_error(f"Exception when async '{func}'") carb.log_error(f"{e}") carb.log_error(f"{traceback.format_exc()}") return wrapper class AclDelegate(AbstractColumnDelegate): """ The object that adds the new column "Access" to fileblowser. The columns displays access flags. """ @property def initial_width(self): """The width of the column""" return ui.Pixel(40) def build_header(self): """Build the header""" ui.Label("ACL", style_type_name_override="TreeView.Header") @handle_exception async def build_widget(self, item: ColumnItem): """ Build the widget for the given item. Works inside Frame in async mode. Once the widget is created, it will replace the content of the frame. It allow to await something for a while and create the widget when the result is available. """ result, entry = await omni.client.stat_async(item.path) if result != omni.client.Result.OK: ui.Label("Error", style_type_name_override="TreeView.Item") return flags = entry.access text = "" if flags & omni.client.AccessFlags.READ: text += "R" if flags & omni.client.AccessFlags.WRITE: text += "W" if flags & omni.client.AccessFlags.ADMIN: text += "A" text = text or "none" ui.Label(text, style_type_name_override="TreeView.Item")
2,467
Python
29.85
76
0.653425
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/tests/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .acl_test import TestAcl
463
Python
45.399995
76
0.807775
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/tests/acl_test.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from ..acl_delegate import AclDelegate from ..acl_delegate import ColumnItem from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import asyncio import omni.kit.app import omni.ui as ui import tempfile CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data") class AwaitWithFrame: """ A future-like object that runs the given future and makes sure it's always in the given frame's scope. It allows for creating widgets asynchronously. """ def __init__(self, frame: ui.Frame, future: asyncio.Future): self._frame = frame self._future = future def __await__(self): # create an iterator object from that iterable iter_obj = iter(self._future.__await__()) # infinite loop while True: try: with self._frame: yield next(iter_obj) except StopIteration: break self._frame = None self._future = None class TestAcl(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): temp = tempfile.NamedTemporaryFile() window = await self.create_test_window() with window.frame: frame = ui.Frame(style={"TreeView.Item": {"color": 0xFFFFFFFF}}) item = ColumnItem(temp.name) delegate = AclDelegate() await AwaitWithFrame(frame, delegate.build_widget(item)) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir) temp.close()
2,284
Python
29.466666
82
0.652364
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/docs/CHANGELOG.md
# Changelog This document records all notable changes to `omni.kit.filebrowser_column.acl` extension. ## [1.0.0] - 2020-10-05 ### Added - Initial example implementation of extension that creates a column in Content Explorer
228
Markdown
21.899998
70
0.758772
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/docs/README.md
# omni.kit.filebrowser_column.acl ## Access column in Content Browser The example extension adds a new column to Content Browser. The extension is based on `omni.client` and is showing the access flags of the file.
217
Markdown
30.142853
76
0.78341
omniverse-code/kit/exts/omni.kit.window.splash/omni/splash/__init__.py
from ._splash import *
23
Python
10.999995
22
0.695652
omniverse-code/kit/exts/omni.kit.window.splash/omni/splash/tests/__init__.py
from .test_splash import *
27
Python
12.999994
26
0.740741
omniverse-code/kit/exts/omni.kit.window.splash/omni/splash/tests/test_splash.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.test import omni.kit.app from omni.kit.test import AsyncTestCase import omni.splash class TestSplash(AsyncTestCase): async def setUp(self): self._splash_iface = omni.splash.acquire_splash_screen_interface() async def tearDown(self): pass async def test_001_close_autocreated(self): # This test just closes the automatically created by the extension on startup self._splash_iface.close_all() async def test_002_create_destroy_splash(self): splash = self._splash_iface.create("${resources}/splash/splash.png", 1.0) self._splash_iface.show(splash) for _ in range(3): await omni.kit.app.get_app().next_update_async() self.assertTrue(self._splash_iface.is_valid(splash)) for _ in range(3): await omni.kit.app.get_app().next_update_async() self._splash_iface.close(splash)
1,350
Python
31.951219
85
0.704444
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/capture_progress.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import asyncio from enum import Enum, IntEnum import datetime import subprocess import carb import omni.ui as ui import omni.kit.app class CaptureStatus(IntEnum): NONE = 0 CAPTURING = 1 PAUSED = 2 FINISHING = 3 TO_START_ENCODING = 4 ENCODING = 5 CANCELLED = 6 class CaptureProgress: def __init__(self): self._init_internal() def _init_internal(self, total_frames=1): self._total_frames = total_frames # at least to capture 1 frame if self._total_frames < 1: self._total_frames = 1 self._capture_status = CaptureStatus.NONE self._elapsed_time = 0.0 self._estimated_time_remaining = 0.0 self._current_frame_time = 0.0 self._average_time_per_frame = 0.0 self._encoding_time = 0.0 self._current_frame = 0 self._first_frame_num = 0 self._got_first_frame = False self._progress = 0.0 self._current_subframe = -1 self._total_subframes = 1 self._subframe_time = 0.0 self._total_frame_time = 0.0 self._average_time_per_subframe = 0.0 self._total_preroll_frames = 0 self._prerolled_frames = 0 self._path_trace_iteration_num = 0 self._path_trace_subframe_num = 0 self._total_iterations = 0 self._average_time_per_iteration = 0.0 self._is_handling_settle_latency_frames = False self._settle_latency_frames_done = 0 self._total_settle_latency_frames = 0 @property def capture_status(self): return self._capture_status @capture_status.setter def capture_status(self, value): self._capture_status = value @property def elapsed_time(self): return self._get_time_string(self._elapsed_time) @property def estimated_time_remaining(self): return self._get_time_string(self._estimated_time_remaining) @property def current_frame_time(self): return self._get_time_string(self._current_frame_time) @property def average_frame_time(self): return self._get_time_string(self._average_time_per_frame) @property def encoding_time(self): return self._get_time_string(self._encoding_time) @property def progress(self): return self._progress @property def current_subframe(self): return self._current_subframe if self._current_subframe >= 0 else 0 @property def total_subframes(self): return self._total_subframes @property def subframe_time(self): return self._get_time_string(self._subframe_time) @property def average_time_per_subframe(self): return self._get_time_string(self._average_time_per_subframe) @property def total_preroll_frames(self): return self._total_preroll_frames @total_preroll_frames.setter def total_preroll_frames(self, value): self._total_preroll_frames = value @property def prerolled_frames(self): return self._prerolled_frames @prerolled_frames.setter def prerolled_frames(self, value): self._prerolled_frames = value @property def path_trace_iteration_num(self): return self._path_trace_iteration_num @path_trace_iteration_num.setter def path_trace_iteration_num(self, value): self._path_trace_iteration_num = value @property def path_trace_subframe_num(self): return self._path_trace_subframe_num @path_trace_subframe_num.setter def path_trace_subframe_num(self, value): self._path_trace_subframe_num = value @property def total_iterations(self): return self._total_iterations @property def average_time_per_iteration(self): return self._get_time_string(self._average_time_per_iteration) @property def current_frame_count(self): return self._current_frame - self._first_frame_num @property def total_frames(self): return self._total_frames @property def is_handling_settle_latency_frames(self): return self._is_handling_settle_latency_frames @property def settle_latency_frames_done(self): return self._settle_latency_frames_done @property def total_settle_latency_frames(self): return self._total_settle_latency_frames def start_capturing(self, total_frames, preroll_frames=0): self._init_internal(total_frames) self._total_preroll_frames = preroll_frames self._capture_status = CaptureStatus.CAPTURING def finish_capturing(self): self._init_internal() def is_prerolling(self): return ( (self._capture_status == CaptureStatus.CAPTURING or self._capture_status == CaptureStatus.PAUSED) and self._total_preroll_frames > 0 and self._total_preroll_frames > self._prerolled_frames ) def add_encoding_time(self, time): if self._estimated_time_remaining > 0.0: self._elapsed_time += self._estimated_time_remaining self._estimated_time_remaining = 0.0 self._encoding_time += time def add_frame_time(self, frame, time, pt_subframe_num=0, pt_total_subframes=0, pt_iteration_num=0, pt_iteration_per_subframe=0, \ handling_settle_latency_frames=False, settle_latency_frames_done=0, total_settle_latency_frames=0): if not self._got_first_frame: self._got_first_frame = True self._first_frame_num = frame self._current_frame = frame self._path_trace_subframe_num = pt_subframe_num self._path_trace_iteration_num = pt_iteration_num self._total_subframes = pt_total_subframes self._total_iterations = pt_iteration_per_subframe self._elapsed_time += time if self._current_frame != frame: frames_captured = self._current_frame - self._first_frame_num + 1 self._average_time_per_frame = self._elapsed_time / frames_captured self._current_frame = frame self._current_frame_time = time else: self._current_frame_time += time if frame == self._first_frame_num: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: total_frame_time = self._average_time_per_frame * self._total_frames # if users pause for long times, or there are skipped frames, it's possible that elapsed time will be greater than estimated total time # if this happens, estimate it again if self._elapsed_time >= total_frame_time: if self._elapsed_time < time + self._average_time_per_frame: total_frame_time += time + self._average_time_per_frame else: total_frame_time = self._elapsed_time + self._average_time_per_frame * (self._total_frames - self._current_frame + 1) self._estimated_time_remaining = total_frame_time - self._elapsed_time self._progress = self._elapsed_time / total_frame_time self._is_handling_settle_latency_frames = handling_settle_latency_frames self._settle_latency_frames_done = settle_latency_frames_done self._total_settle_latency_frames = total_settle_latency_frames def add_single_frame_capture_time_for_pt(self, subframe, total_subframes, time): self._total_subframes = total_subframes self._elapsed_time += time if self._current_subframe != subframe: self._subframe_time = time if self._current_subframe == -1: self._average_time_per_subframe = self._elapsed_time else: self._average_time_per_subframe = self._elapsed_time / subframe self._total_frame_time = self._average_time_per_subframe * total_subframes else: self._subframe_time += time self._current_subframe = subframe if self._current_subframe == 0: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: if self._elapsed_time >= self._total_frame_time: self._total_frame_time += time + self._average_time_per_subframe self._estimated_time_remaining = self._total_frame_time - self._elapsed_time self._progress = self._elapsed_time / self._total_frame_time def add_single_frame_capture_time_for_iray(self, subframe, total_subframes, iterations_done, iterations_per_subframe, time): self._total_subframes = total_subframes self._total_iterations = iterations_per_subframe self._elapsed_time += time self._path_trace_iteration_num = iterations_done if self._current_subframe != subframe: self._subframe_time = time if self._current_subframe == -1: self._average_time_per_subframe = self._elapsed_time else: self._average_time_per_subframe = self._elapsed_time / subframe self._total_frame_time = self._average_time_per_subframe * total_subframes else: self._subframe_time += time self._current_subframe = subframe if self._current_subframe == 0: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: if self._elapsed_time >= self._total_frame_time: self._total_frame_time += time + self._average_time_per_subframe self._estimated_time_remaining = self._total_frame_time - self._elapsed_time self._progress = self._elapsed_time / self._total_frame_time def _get_time_string(self, time_seconds): hours = int(time_seconds / 3600) minutes = int((time_seconds - hours*3600) / 60) seconds = time_seconds - hours*3600 - minutes*60 time_string = "" if hours > 0: time_string += '{:d}h '.format(hours) if minutes > 0: time_string += '{:d}m '.format(minutes) else: if hours > 0: time_string += "0m " time_string += '{:.2f}s'.format(seconds) return time_string PROGRESS_WINDOW_WIDTH = 360 PROGRESS_WINDOW_HEIGHT = 280 PROGRESS_BAR_WIDTH = 216 PROGRESS_BAR_HEIGHT = 20 PROGRESS_BAR_HALF_HEIGHT = PROGRESS_BAR_HEIGHT / 2 TRIANGLE_WIDTH = 6 TRIANGLE_HEIGHT = 10 TRIANGLE_OFFSET_Y = 10 PROGRESS_WIN_DARK_STYLE = { "Triangle::progress_marker": {"background_color": 0xFFD1981D}, "Rectangle::progress_bar_background": { "border_width": 0.5, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "background_color": 0xFF888888, }, "Rectangle::progress_bar_full": { "border_width": 0.5, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "background_color": 0xFFD1981D, }, "Rectangle::progress_bar": { "background_color": 0xFFD1981D, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "corner_flag": ui.CornerFlag.LEFT, "alignment": ui.Alignment.LEFT, }, } PAUSE_BUTTON_STYLE = { "NvidiaLight": { "Button.Label::pause": {"color": 0xFF333333}, "Button.Label::pause:disabled": {"color": 0xFF666666}, }, "NvidiaDark": { "Button.Label::pause": {"color": 0xFFCCCCCC}, "Button.Label::pause:disabled": {"color": 0xFF666666}, }, } class CaptureProgressWindow: def __init__(self): self._app = omni.kit.app.get_app_interface() self._update_sub = None self._window_caption = "Capture Progress" self._window = None self._progress = None self._progress_bar_len = PROGRESS_BAR_HALF_HEIGHT self._progress_step = 0.5 self._is_single_frame_mode = False self._show_pt_subframes = False self._show_pt_iterations = False self._support_pausing = True self._is_external_window = False def show( self, progress, single_frame_mode: bool = False, show_pt_subframes: bool = False, show_pt_iterations: bool = False, support_pausing: bool = True, ) -> None: self._progress = progress self._is_single_frame_mode = single_frame_mode self._show_pt_subframes = show_pt_subframes self._show_pt_iterations = show_pt_iterations self._support_pausing = support_pausing self._build_ui() self._update_sub = self._app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.kit.capure.viewport progress" ) def close(self): if self._is_external_window: asyncio.ensure_future(self._move_back_to_main_window()) else: self._window.destroy() self._window = None self._update_sub = None def move_to_external_window(self): self._window.move_to_new_os_window() self._is_external_window = True def move_to_main_window(self): asyncio.ensure_future(self._move_back_to_main_window()) self._is_external_window = False def is_external_window(self): return self._is_external_window async def _move_back_to_main_window(self): self._window.move_to_main_os_window() for i in range(2): await omni.kit.app.get_app().next_update_async() self._window.destroy() self._window = None self._is_external_window = False def _build_progress_bar(self): self._progress_bar_area.clear() self._progress_bar_area.set_style(PROGRESS_WIN_DARK_STYLE) with self._progress_bar_area: with ui.Placer(offset_x=self._progress_bar_len - TRIANGLE_WIDTH / 2, offset_y=TRIANGLE_OFFSET_Y): ui.Triangle( name="progress_marker", width=TRIANGLE_WIDTH, height=TRIANGLE_HEIGHT, alignment=ui.Alignment.CENTER_BOTTOM, ) with ui.ZStack(): ui.Rectangle(name="progress_bar_background", width=PROGRESS_BAR_WIDTH, height=PROGRESS_BAR_HEIGHT) ui.Rectangle(name="progress_bar", width=self._progress_bar_len, height=PROGRESS_BAR_HEIGHT) def _build_ui_timer(self, text, init_value): with ui.HStack(): with ui.HStack(width=ui.Percent(50)): ui.Spacer() ui.Label(text, width=0) with ui.HStack(width=ui.Percent(50)): ui.Spacer(width=15) timer_label = ui.Label(init_value) ui.Spacer() return timer_label def _build_multi_frames_capture_timers(self): self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time) self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining) frame_count_str = f"{self._progress.current_frame_count}/{self._progress.total_frames}" self._ui_frame_count = self._build_ui_timer("Current/Total frames", frame_count_str) self._ui_current_frame_time = self._build_ui_timer("Current frame time", self._progress.current_frame_time) if self._show_pt_subframes: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes = self._build_ui_timer("Subframe/Total subframes", subframes_str) if self._show_pt_iterations: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes = self._build_ui_timer("Subframe/Total subframes", subframes_str) iter_str = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_pt_iterations = self._build_ui_timer("Iterations done/Total", iter_str) self._ui_ave_frame_time = self._build_ui_timer("Average time per frame", self._progress.average_frame_time) self._ui_encoding_time = self._build_ui_timer("Encoding", self._progress.encoding_time) def _build_single_frame_capture_timers(self): self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time) self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining) if self._show_pt_subframes: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count = self._build_ui_timer("Subframe/Total subframes", subframe_count) self._ui_current_frame_time = self._build_ui_timer("Current subframe time", self._progress.subframe_time) self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_time_per_subframe) if self._show_pt_iterations: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count = self._build_ui_timer("Subframe/Total subframes", subframe_count) iteration_count = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_iteration_count = self._build_ui_timer("Iterations done/Per subframe", iteration_count) # self._ui_ave_iteration_time = self._build_ui_timer("Average time per iteration", self._progress.average_time_per_iteration) self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_time_per_subframe) def _build_notification_area(self): with ui.HStack(): ui.Spacer(width=ui.Percent(20)) self._notification = ui.Label("") ui.Spacer(width=ui.Percent(10)) def _build_ui(self): if self._window is None: style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle") if not style_settings: style_settings = "NvidiaDark" self._window = ui.Window( self._window_caption, width=PROGRESS_WINDOW_WIDTH, height=PROGRESS_WINDOW_HEIGHT, style=PROGRESS_WIN_DARK_STYLE, ) with self._window.frame: with ui.VStack(): with ui.HStack(): ui.Spacer(width=ui.Percent(20)) self._progress_bar_area = ui.VStack() self._build_progress_bar() ui.Spacer(width=ui.Percent(20)) ui.Spacer(height=5) if self._is_single_frame_mode: self._build_single_frame_capture_timers() else: self._build_multi_frames_capture_timers() self._build_notification_area() with ui.HStack(): with ui.HStack(width=ui.Percent(50)): ui.Spacer() self._ui_pause_button = ui.Button( "Pause", height=0, clicked_fn=self._on_pause_clicked, enabled=self._support_pausing, style=PAUSE_BUTTON_STYLE[style_settings], name="pause", ) with ui.HStack(width=ui.Percent(50)): ui.Spacer(width=15) ui.Button("Cancel", height=0, clicked_fn=self._on_cancel_clicked) ui.Spacer() ui.Spacer() self._window.visible = True self._update_timers() def _on_pause_clicked(self): if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause": self._progress.capture_status = CaptureStatus.PAUSED self._ui_pause_button.text = "Resume" elif self._progress.capture_status == CaptureStatus.PAUSED: self._progress.capture_status = CaptureStatus.CAPTURING self._ui_pause_button.text = "Pause" def _on_cancel_clicked(self): if ( self._progress.capture_status == CaptureStatus.CAPTURING or self._progress.capture_status == CaptureStatus.PAUSED ): self._progress.capture_status = CaptureStatus.CANCELLED def _update_timers(self): if self._is_single_frame_mode: self._ui_elapsed_time.text = self._progress.elapsed_time self._ui_remaining_time.text = self._progress.estimated_time_remaining if self._show_pt_subframes: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count.text = subframe_count self._ui_current_frame_time.text = self._progress.subframe_time self._ui_ave_frame_time.text = self._progress.average_time_per_subframe if self._show_pt_iterations: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count.text = subframe_count iteration_count = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_iteration_count.text = iteration_count self._ui_ave_frame_time.text = self._progress.average_time_per_subframe else: self._ui_elapsed_time.text = self._progress.elapsed_time self._ui_remaining_time.text = self._progress.estimated_time_remaining frame_count_str = f"{self._progress.current_frame_count}/{self._progress.total_frames}" self._ui_frame_count.text = frame_count_str self._ui_current_frame_time.text = self._progress.current_frame_time if self._show_pt_subframes: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes.text = subframes_str if self._show_pt_iterations: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes.text = subframes_str iter_str = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_pt_iterations.text = iter_str self._ui_ave_frame_time.text = self._progress.average_frame_time self._ui_encoding_time.text = self._progress.encoding_time def _update_notification(self): if self._progress.capture_status == CaptureStatus.CAPTURING: if self._progress.is_prerolling(): msg = 'Running preroll frames {}/{}, please wait...'.format( self._progress.prerolled_frames, self._progress.total_preroll_frames ) self._notification.text = msg elif not self._is_single_frame_mode: if self._progress.is_handling_settle_latency_frames: msg = 'Running settle latency frames {}/{}...'.format( self._progress.settle_latency_frames_done, self._progress.total_settle_latency_frames ) self._notification.text = msg else: self._notification.text = f"Capturing frame {self._progress.current_frame_count}..." elif self._progress.capture_status == CaptureStatus.ENCODING: self._notification.text = "Encoding..." else: self._notification.text = "" def _on_update(self, event): self._update_notification() self._update_timers() self._progress_bar_len = ( PROGRESS_BAR_WIDTH - PROGRESS_BAR_HEIGHT ) * self._progress.progress + PROGRESS_BAR_HALF_HEIGHT self._build_progress_bar()
24,530
Python
40.648557
147
0.605014
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import math import time import datetime import asyncio import omni.ext import carb import omni.kit.app import omni.timeline import omni.usd import omni.ui from pxr import Gf, Sdf from .capture_options import * from .capture_progress import * from .video_generation import VideoGenerationHelper from .helper import ( get_num_pattern_file_path, check_render_product_ext_availability, is_valid_render_product_prim_path, RenderProductCaptureHelper, is_kit_104_and_above, # TODO: Remove this as it is no longer used, but kept only if transitively depended on get_vp_object_visibility, set_vp_object_visibility, ) from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file import omni.appwindow PERSISTENT_SETTINGS_PREFIX = "/persistent" FILL_VIEWPORT_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/fillViewport" SEQUENCE_CAPTURE_WAIT = "/app/captureSequence/waitFrames" MP4_ENCODING_BITRATE_SETTING = "/exts/omni.videoencoding/bitrate" MP4_ENCODING_IFRAME_INTERVAL_SETTING = "/exts/omni.videoencoding/iframeinterval" MP4_ENCODING_PRESET_SETTING = "/exts/omni.videoencoding/preset" MP4_ENCODING_PROFILE_SETTING = "/exts/omni.videoencoding/profile" MP4_ENCODING_RC_MODE_SETTING = "/exts/omni.videoencoding/rcMode" MP4_ENCODING_RC_TARGET_QUALITY_SETTING = "/exts/omni.videoencoding/rcTargetQuality" MP4_ENCODING_VIDEO_FULL_RANGE_SETTING = "/exts/omni.videoencoding/videoFullRangeFlag" VIDEO_FRAMES_DIR_NAME = "frames" DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO = ".png" capture_instance = None class RenderStatus(IntEnum): # Note render status values from rtx/hydra/HydraRenderResults.h # Rendering was successful. A path tracer might not have reached a stopping criterion though. eSuccess = 0 # Rendering was successful and the renderer has reached a stopping criterion on this iteration. eStopCriterionJustReached = 1 # Rendering was successful and the renderer has reached a stopping criterion. eStopCriterionReached = 2 # Rendering failed eFailed = 3 class CaptureExtension(omni.ext.IExt): def on_startup(self): global capture_instance capture_instance = self self._options = CaptureOptions() self._progress = CaptureProgress() self._progress_window = CaptureProgressWindow() import omni.renderer_capture self._renderer = omni.renderer_capture.acquire_renderer_capture_interface() self._viewport_api = None self._app = omni.kit.app.get_app_interface() self._timeline = omni.timeline.get_timeline_interface() self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._settings = carb.settings.get_settings() self._show_default_progress_window = True self._progress_update_fn = None self._forward_one_frame_fn = None self._capture_finished_fn = None self._to_capture_render_product = False self._render_product_path_for_capture = "" self._is_adaptivesampling_stop_criterion_reached = False class ReshadeUpdateState(): PRE_CAPTURE = 0 POST_CAPTURE = 1 POST_CAPTURE_READY = 3 def on_shutdown(self): self._progress = None self._progress_window = None global capture_instance capture_instance = None @property def options(self): return self._options @options.setter def options(self, value): self._options = value @property def progress(self): return self._progress @property def show_default_progress_window(self): return self._show_default_progress_window @show_default_progress_window.setter def show_default_progress_window(self, value): self._show_default_progress_window = value @property def progress_update_fn(self): return self._progress_update_fn @progress_update_fn.setter def progress_update_fn(self, value): self._progress_update_fn = value @property def forward_one_frame_fn(self): return self._forward_one_frame_fn @forward_one_frame_fn.setter def forward_one_frame_fn(self, value): self._forward_one_frame_fn = value @property def capture_finished_fn(self): return self._capture_finished_fn @capture_finished_fn.setter def capture_finished_fn(self, value): self._capture_finished_fn = value def start(self): self._to_capture_render_product = self._check_if_to_capture_render_product() if self._to_capture_render_product: self._render_product_path_for_capture = RenderProductCaptureHelper.prepare_render_product_for_capture( self._options.render_product, self._options.camera, Gf.Vec2i(self._options.res_width, self._options.res_height) ) if len(self._render_product_path_for_capture) == 0: carb.log_warn(f"Capture will use render product {self._options.render_product}'s original camera and resolution because it failed to make a copy of it for processing.") self._render_product_path_for_capture = self._options.render_product # use usd time code for animation play during capture, caption option's fps setting for movie encoding if CaptureOptions.INVALID_ANIMATION_FPS == self._options.animation_fps: self._capture_fps = self._timeline.get_time_codes_per_seconds() else: self._capture_fps = self._options.animation_fps if not self._prepare_folder_and_counters(): if self._render_product_path_for_capture != self._options.render_product: RenderProductCaptureHelper.remove_render_product_for_capture(self._render_product_path_for_capture) self._render_product_path_for_capture = "" return if self._prepare_viewport(): self._start_internal() def pause(self): if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause": self._progress.capture_status = CaptureStatus.PAUSED def resume(self): if self._progress.capture_status == CaptureStatus.PAUSED: self._progress.capture_status = CaptureStatus.CAPTURING def cancel(self): if ( self._progress.capture_status == CaptureStatus.CAPTURING or self._progress.capture_status == CaptureStatus.PAUSED ): self._progress.capture_status = CaptureStatus.CANCELLED def _update_progress_hook(self): if self._progress_update_fn is not None: self._progress_update_fn( self._progress.capture_status, self._progress.progress, self._progress.elapsed_time, self._progress.estimated_time_remaining, self._progress.current_frame_time, self._progress.average_frame_time, self._progress.encoding_time, self._frame_counter, self._total_frame_count, ) def _get_index_for_image(self, dir, file_name, image_suffix): def is_int(string_val): try: v = int(string_val) return True except: return False images = os.listdir(dir) name_len = len(file_name) suffix_len = len(image_suffix) max_index = 0 for item in images: if item.startswith(file_name) and item.endswith(image_suffix): num_part = item[name_len : (len(item) - suffix_len)] if is_int(num_part): num = int(num_part) if max_index < num: max_index = num return max_index + 1 def _float_to_time(self, ft): hour = int(ft) ft = (ft - hour) * 60 minute = int(ft) ft = (ft - minute) * 60 second = int(ft) ft = (ft - second) * 1000000 microsecond = int(ft) return datetime.time(hour, minute, second, microsecond) def _check_if_to_capture_render_product(self): if len(self._options.render_product) == 0: return False omnigraph_exts_available = check_render_product_ext_availability() if not omnigraph_exts_available: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as it needs both omni.graph.nodes and omni.graph.examples.cpp enabled to work.") return False viewport_api = get_active_viewport() render_product_name = viewport_api.render_product_path if viewport_api else None if not render_product_name: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as Kit SDK needs updating to support viewport window render product APIs: {e}") return False if is_valid_render_product_prim_path(self._options.render_product): return True else: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as it's not a valid Render Product prim path") return False def _is_environment_sunstudy_player(self): if self._options.sunstudy_player is not None: return type(self._options.sunstudy_player).__module__ == "omni.kit.environment.core.sunstudy_player.player" else: carb.log_warn("Sunstudy player type check is valid only when the player is available.") return False def _update_sunstudy_player_time(self): if self._is_environment_sunstudy_player(): self._options.sunstudy_player.current_time = self._sunstudy_current_time else: self._options.sunstudy_player.update_time(self._sunstudy_current_time) def _set_sunstudy_player_time(self, current_time): if self._is_environment_sunstudy_player(): self._options.sunstudy_player.current_time = current_time else: date_time = self._options.sunstudy_player.get_date_time() time_to_set = self._float_to_time(current_time) new_date_time = datetime.datetime( date_time.year, date_time.month, date_time.day, time_to_set.hour, time_to_set.minute, time_to_set.second ) self._options.sunstudy_player.set_date_time(new_date_time) def _prepare_sunstudy_counters(self): self._total_frame_count = self._options.fps * self._options.sunstudy_movie_length_in_seconds duration = self._options.sunstudy_end_time - self._options.sunstudy_start_time self._sunstudy_iterations_per_frame = self._options.ptmb_subframes_per_frame self._sunstudy_delta_time_per_iteration = duration / float(self._total_frame_count * self._sunstudy_iterations_per_frame) self._sunstudy_current_time = self._options.sunstudy_start_time self._set_sunstudy_player_time(self._sunstudy_current_time) def _prepare_folder_and_counters(self): self._workset_dir = self._options.output_folder if not self._make_sure_directory_writeable(self._workset_dir): carb.log_warn(f"Capture failed due to unable to create folder {self._workset_dir} or this folder is not writeable.") self._finish() return False if self._options.is_capturing_nth_frames(): if self._options.capture_every_Nth_frames == 1: frames_folder = self._options.file_name + "_frames" else: frames_folder = self._options.file_name + "_" + str(self._options.capture_every_Nth_frames) + "th_frames" self._nth_frames_dir = os.path.join(self._workset_dir, frames_folder) if not self._make_sure_directory_existed(self._nth_frames_dir): carb.log_warn(f"Capture failed due to unable to create folder {self._nth_frames_dir}") self._finish() return False if self._options.is_video(): self._frames_dir = os.path.join(self._workset_dir, self._options.file_name + "_" + VIDEO_FRAMES_DIR_NAME) if not self._make_sure_directory_existed(self._frames_dir): carb.log_warn( f"Capture failed due to unable to create folder {self._workset_dir} to save frames of the video." ) self._finish() return False self._video_name = self._options.get_full_path() self._frame_pattern_prefix = os.path.join(self._frames_dir, self._options.file_name) if self._options.is_capturing_frame(): self._start_time = float(self._options.start_frame) / self._capture_fps self._end_time = float(self._options.end_frame + 1) / self._capture_fps self._time = self._start_time self._frame = self._options.start_frame self._start_number = self._frame self._total_frame_count = round((self._end_time - self._start_time) * self._capture_fps) else: self._start_time = self._options.start_time self._end_time = self._options.end_time self._time = self._options.start_time self._frame = int(self._options.start_time * self._capture_fps) self._start_number = self._frame self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._capture_fps) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._prepare_sunstudy_counters() else: if self._options.is_capturing_nth_frames(): self._frame_pattern_prefix = self._nth_frames_dir if self._options.is_capturing_frame(): self._start_time = float(self._options.start_frame) / self._capture_fps self._end_time = float(self._options.end_frame + 1) / self._capture_fps self._time = self._start_time self._frame = self._options.start_frame self._start_number = self._frame self._total_frame_count = round((self._end_time - self._start_time) * self._capture_fps) else: self._start_time = self._options.start_time self._end_time = self._options.end_time self._time = self._options.start_time self._frame = int(self._options.start_time * self._capture_fps) self._start_number = self._frame self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._capture_fps) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._prepare_sunstudy_counters() else: index = self._get_index_for_image(self._workset_dir, self._options.file_name, self._options.file_type) self._frame_pattern_prefix = os.path.join(self._workset_dir, self._options.file_name + str(index)) self._start_time = self._timeline.get_current_time() self._end_time = self._timeline.get_current_time() self._time = self._timeline.get_current_time() self._frame = 1 self._start_number = self._frame self._total_frame_count = 1 self._subframe = 0 self._sample_count = 0 self._frame_counter = 0 self._real_time_settle_latency_frames_done = 0 self._settle_latency_frames = self._get_settle_latency_frames() self._last_skipped_frame_path = "" self._path_trace_iterations = 0 self._time_rate = 1.0 / self._capture_fps self._time_subframe_rate = ( self._time_rate * (self._options.ptmb_fsc - self._options.ptmb_fso) / self._options.ptmb_subframes_per_frame ) return True def _prepare_viewport(self): viewport_api = get_active_viewport() if viewport_api is None: return False self._is_legacy_vp = hasattr(viewport_api, 'legacy_window') self._record_current_window_status(viewport_api) capture_camera = Sdf.Path(self._options.camera) if capture_camera != self._saved_camera: viewport_api.camera_path = capture_camera if not self._is_legacy_vp: viewport_api.updates_enabled = True if self._saved_fill_viewport_option: fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=viewport_api.id) # for application level capture, we want it to fill the viewport to make the viewport resolution the same to application window resolution # while for viewport capture, we can get images with the correct resolution so doesn't need it to fill viewport self._settings.set(fv_setting_path, self._options.app_level_capture) capture_resolution = (self._options.res_width, self._options.res_height) if capture_resolution != (self._saved_resolution_width, self._saved_resolution_height): viewport_api.resolution = capture_resolution self._settings.set_bool("/persistent/app/captureFrame/viewport", True) self._settings.set_bool("/app/captureFrame/setAlphaTo1", not self._options.save_alpha) if self._options.file_type == ".exr": self._settings.set_bool("/app/captureFrame/hdr", self._options.hdr_output) else: self._settings.set_bool("/app/captureFrame/hdr", False) if self._options.save_alpha: self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", True) self._settings.set_bool("/rtx/post/backgroundZeroAlpha/backgroundComposite", False) if self._options.hdr_output: self._settings.set_bool("/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst", True) if self._to_capture_render_product: viewport_api.render_product_path = self._render_product_path_for_capture # we only clear selection for non application level capture, other we will lose the ui.scene elemets during capture if not self._options.app_level_capture: self._selection.clear_selected_prim_paths() if self._options.render_preset == CaptureRenderPreset.RAY_TRACE: self._switch_renderer = self._saved_hd_engine != "rtx" or self._saved_render_mode != "RaytracedLighting" if self._switch_renderer: viewport_api.set_hd_engine("rtx", "RaytracedLighting") carb.log_info("Switching to RayTracing Mode") elif self._options.render_preset == CaptureRenderPreset.PATH_TRACE: self._switch_renderer = self._saved_hd_engine != "rtx" or self._saved_render_mode != "PathTracing" if self._switch_renderer: viewport_api.set_hd_engine("rtx", "PathTracing") carb.log_info("Switching to PathTracing Mode") elif self._options.render_preset == CaptureRenderPreset.IRAY: self._switch_renderer = self._saved_hd_engine != "iray" or self._saved_render_mode != "iray" if self._switch_renderer: viewport_api.set_hd_engine("iray", "iray") carb.log_info("Switching to IRay Mode") # now that Iray is not loaded automatically until renderer gets switched # we have to save and set the Iray settings after the renderer switch self._record_and_set_iray_settings() else: self._switch_renderer = False carb.log_info("Keeping current Render Mode") if self._options.debug_material_type == CaptureDebugMaterialType.SHADED: self._settings.set_int("/rtx/debugMaterialType", -1) elif self._options.debug_material_type == CaptureDebugMaterialType.WHITE: self._settings.set_int("/rtx/debugMaterialType", 0) else: carb.log_info("Keeping current debug mateiral type") # tell timeline window to stop force checks of end time so that it won't affect capture range self._settings.set_bool("/exts/omni.anim.window.timeline/playinRange", False) # set it to 0 to ensure we accumulate as many samples as requested even across subframes (for motion blur) # for non-motion blur path trace capture, we now rely on adaptive sampling's return status to decide if it's still # need to do more samples if self._is_capturing_pt_mb(): self._settings.set_int("/rtx/pathtracing/totalSpp", 0) # don't show light and grid during capturing self._set_vp_object_settings(viewport_api) # disable async rendering for capture, otherwise it won't capture images correctly if self._saved_async_rendering: self._settings.set_bool("/app/asyncRendering", False) if self._saved_async_renderingLatency: self._settings.set_bool("/app/asyncRenderingLowLatency", False) # Rendering to some image buffers additionally require explicitly setting `set_capture_sync(True)`, on top of # disabling the `/app/asyncRendering` setting. This can otherwise cause images to hold corrupted buffer # information by erroneously assuming a complete image buffer is available when only a first partial subframe # has been renderer (as in the case of EXR): self._renderer.set_capture_sync( self._options.file_type == ".exr" ) # frames to wait for the async settings above to be ready, they will need to be detected by viewport, and # then viewport will notify the renderer not to do async rendering self._frames_to_disable_async_rendering = 2 # Normally avoid using a high /rtx/pathtracing/spp setting since it causes GPU # timeouts for large sample counts. But a value larger than 1 can be useful in Multi-GPU setups self._settings.set_int( "/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp) ) # Setting resetPtAccumOnlyWhenExternalFrameCounterChanges ensures we control accumulation explicitly # by simpling changing the /rtx/externalFrameCounter value self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", True) # Enable syncLoads in materialDB and Hydra. This is needed to make sure texture updates finish before we start the rendering self._settings.set("/rtx/materialDb/syncLoads", True) self._settings.set("/rtx/hydra/materialSyncLoads", True) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", False) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0) self._settings.set("/rtx-transient/samplerFeedbackTileSize", 1) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency", 0) #for now, reshade needs to be turned off and on again to apply settings self._settings.set_bool("/rtx/reshade/enable", False) #need to skip several updates for reshade settings to apply: self._frames_to_apply_reshade = 2 # these settings need to be True to ensure XR Output Alpha in composited image is right if not self._saved_output_alpha_in_composite: self._settings.set("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite", True) # do not show the minibar of timeline window self._settings.set("/exts/omni.kit.timeline.minibar/stay_on_playing", False) # enable sequencer camera self._settings.set("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera", True) # set timeline animation fps if self._capture_fps != self._saved_timeline_fps: self._timeline.set_time_codes_per_second(self._capture_fps) # return success return True def _show_progress_window(self): return ( self._options.is_video() or self._options.is_capturing_nth_frames() or (self._options.show_single_frame_progress and self._options.is_capturing_pathtracing_single_frame()) ) and self.show_default_progress_window def _start_internal(self): # if we want preroll, then set timeline's current time back with the preroll frames' time, # and rely on timeline to do the preroll using the give timecode if self._options.preroll_frames > 0: self._timeline.set_current_time(self._start_time - self._options.preroll_frames / self._capture_fps) else: self._timeline.set_current_time(self._start_time) # initialize Reshade state for update loop self._reshade_switch_state = self.ReshadeUpdateState.PRE_CAPTURE # change timeline to be in play state self._timeline.play(start_timecode=self._start_time*self._capture_fps, end_timecode=self._end_time*self._capture_fps, looping=False) # disable automatic time update in timeline so that movie capture tool can control time step self._timeline.set_auto_update(False) self._update_sub = ( omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update, order=1000000) ) self._is_adaptivesampling_stop_criterion_reached = False self._progress.start_capturing(self._total_frame_count, self._options.preroll_frames) # always show single frame capture progress for PT mode self._options.show_single_frame_progress = True if self._show_progress_window(): self._progress_window.show( self._progress, self._options.is_capturing_pathtracing_single_frame(), show_pt_subframes=self._options.render_preset == CaptureRenderPreset.PATH_TRACE, show_pt_iterations=self._options.render_preset == CaptureRenderPreset.IRAY ) # prepare for application level capture if self._options.app_level_capture: # move the progress window to external window, and then hide application UI if self._show_progress_window(): self._progress_window.move_to_external_window() self._settings.set("/app/window/hideUi", True) def _record_and_set_iray_settings(self): if self._options.render_preset == CaptureRenderPreset.IRAY: self._saved_iray_sample_limit = self._settings.get_as_int("/rtx/iray/progressive_rendering_max_samples") self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._options.path_trace_spp) self._saved_iray_render_sync_flag = self._settings.get_as_bool("/iray/render_synchronous") if not self._saved_iray_render_sync_flag: self._settings.set_bool("/iray/render_synchronous", True) def _restore_iray_settings(self): if self._options.render_preset == CaptureRenderPreset.IRAY: self._settings.set_bool("/iray/render_synchronous", self._saved_iray_render_sync_flag) self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._saved_iray_sample_limit) def __save_mp4_encoding_settings(self): self._saved_mp4_encoding_bitrate = self._settings.get_as_int(MP4_ENCODING_BITRATE_SETTING) self._saved_mp4_encoding_iframe_interval = self._settings.get_as_int(MP4_ENCODING_IFRAME_INTERVAL_SETTING) self._saved_mp4_encoding_preset = self._settings.get(MP4_ENCODING_PRESET_SETTING) self._saved_mp4_encoding_profile = self._settings.get(MP4_ENCODING_PROFILE_SETTING) self._saved_mp4_encoding_rc_mode = self._settings.get(MP4_ENCODING_RC_MODE_SETTING) self._saved_mp4_encoding_rc_target_quality = self._settings.get(MP4_ENCODING_RC_TARGET_QUALITY_SETTING) self._saved_mp4_encoding_video_full_range_flag = self._settings.get(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING) def __set_mp4_encoding_settings(self): self._settings.set(MP4_ENCODING_BITRATE_SETTING, self._options.mp4_encoding_bitrate) self._settings.set(MP4_ENCODING_IFRAME_INTERVAL_SETTING, self._options.mp4_encoding_iframe_interval) self._settings.set(MP4_ENCODING_PRESET_SETTING, self._options.mp4_encoding_preset) self._settings.set(MP4_ENCODING_PROFILE_SETTING, self._options.mp4_encoding_profile) self._settings.set(MP4_ENCODING_RC_MODE_SETTING, self._options.mp4_encoding_rc_mode) self._settings.set(MP4_ENCODING_RC_TARGET_QUALITY_SETTING, self._options.mp4_encoding_rc_target_quality) self._settings.set(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING, self._options.mp4_encoding_video_full_range_flag) def _save_and_set_mp4_encoding_settings(self): if self._options.is_video(): self.__save_mp4_encoding_settings() self.__set_mp4_encoding_settings() def _restore_mp4_encoding_settings(self): if self._options.is_video(): self._settings.set(MP4_ENCODING_BITRATE_SETTING, self._saved_mp4_encoding_bitrate) self._settings.set(MP4_ENCODING_IFRAME_INTERVAL_SETTING, self._saved_mp4_encoding_iframe_interval) self._settings.set(MP4_ENCODING_PRESET_SETTING, self._saved_mp4_encoding_preset) self._settings.set(MP4_ENCODING_PROFILE_SETTING, self._saved_mp4_encoding_profile) self._settings.set(MP4_ENCODING_RC_MODE_SETTING, self._saved_mp4_encoding_rc_mode) self._settings.set(MP4_ENCODING_RC_TARGET_QUALITY_SETTING, self._saved_mp4_encoding_rc_target_quality) self._settings.set(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING, self._saved_mp4_encoding_video_full_range_flag) def _save_and_set_application_capture_settings(self): # as in application capture mode, we actually capture the window size instead of the renderer output, thus we do this with two steps: # 1. set it to fill the viewport, and padding to (0, -1) to make viewport's size equals to application window size # 2. resize application window to the resolution that users set in movie capture, so that we can save the images with the desired resolution # this is not ideal because when we resize the application window, the size is actaully limited by the screen resolution so it's possible that # the resulting window size could be smaller than what we want. # also, it's more intuitive that padding should be (0, 0), but it has to be (0, -1) after tests as we still have 1 pixel left at top and bottom. if self._options.app_level_capture: vp_window = omni.ui.Workspace.get_window("Viewport") self._saved_viewport_padding_x = vp_window.padding_x self._saved_viewport_padding_y = vp_window.padding_y vp_window.padding_x = 0 vp_window.padding_y = -1 app_window_factory = omni.appwindow.acquire_app_window_factory_interface() app_window = app_window_factory.get_app_window() self._saved_app_window_size = app_window.get_size() app_window.resize(self._options.res_width, self._options._res_height) def _restore_application_capture_settings(self): if self._options.app_level_capture: vp_window = omni.ui.Workspace.get_window("Viewport") vp_window.padding_x = self._saved_viewport_padding_x vp_window.padding_y = self._saved_viewport_padding_y app_window_factory = omni.appwindow.acquire_app_window_factory_interface() app_window = app_window_factory.get_app_window() app_window.resize(self._saved_app_window_size[0], self._saved_app_window_size[1]) def _record_vp_object_settings(self, viewport_api) -> None: self._saved_display_outline = get_vp_object_visibility(viewport_api, "guide/selection") self._saved_display_lights = get_vp_object_visibility(viewport_api, "scene/lights") self._saved_display_audio = get_vp_object_visibility(viewport_api, "scene/audio") self._saved_display_camera = get_vp_object_visibility(viewport_api, "scene/cameras") self._saved_display_grid = get_vp_object_visibility(viewport_api, "guide/grid") def _set_vp_object_settings(self, viewport_api) -> None: set_vp_object_visibility(viewport_api, "guide/selection", False) set_vp_object_visibility(viewport_api, "scene/lights", False) set_vp_object_visibility(viewport_api, "scene/audio", False) set_vp_object_visibility(viewport_api, "scene/cameras", False) set_vp_object_visibility(viewport_api, "guide/grid", False) def _restore_vp_object_settings(self, viewport_api): set_vp_object_visibility(viewport_api, "guide/selection", self._saved_display_outline) set_vp_object_visibility(viewport_api, "scene/lights", self._saved_display_lights) set_vp_object_visibility(viewport_api, "scene/audio", self._saved_display_audio) set_vp_object_visibility(viewport_api, "scene/cameras", self._saved_display_camera) set_vp_object_visibility(viewport_api, "guide/grid", self._saved_display_grid) def _record_current_window_status(self, viewport_api): assert viewport_api is not None, "No viewport to record to" self._viewport_api = viewport_api self._saved_camera = viewport_api.camera_path self._saved_hydra_engine = viewport_api.hydra_engine if not self._is_legacy_vp: self._saved_vp_updates_enabled = self._viewport_api.updates_enabled fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=self._viewport_api.id) self._saved_fill_viewport_option = self._settings.get_as_bool(fv_setting_path) resolution = viewport_api.resolution self._saved_resolution_width = int(resolution[0]) self._saved_resolution_height = int(resolution[1]) self._saved_hd_engine = viewport_api.hydra_engine self._saved_render_mode = viewport_api.render_mode self._saved_capture_frame_viewport = self._settings.get("/persistent/app/captureFrame/viewport") self._saved_debug_material_type = self._settings.get_as_int("/rtx/debugMaterialType") self._saved_total_spp = self._settings.get_as_int("/rtx/pathtracing/totalSpp") self._saved_spp = self._settings.get_as_int("/rtx/pathtracing/spp") self._saved_reset_pt_accum_only = self._settings.get("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges") self._record_vp_object_settings(viewport_api) self._saved_async_rendering = self._settings.get("/app/asyncRendering") self._saved_async_renderingLatency = self._settings.get("/app/asyncRenderingLowLatency") self._saved_background_zero_alpha = self._settings.get("/rtx/post/backgroundZeroAlpha/enabled") self._saved_background_zero_alpha_comp = self._settings.get("/rtx/post/backgroundZeroAlpha/backgroundComposite") self._saved_background_zero_alpha_zp_first = self._settings.get( "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst" ) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._saved_sunstudy_current_time = self._options.sunstudy_current_time self._saved_timeline_current_time = self._timeline.get_current_time() self._saved_timeline_fps = self._timeline.get_time_codes_per_seconds() self._saved_rtx_sync_load_setting = self._settings.get("/rtx/materialDb/syncLoads") if self._to_capture_render_product: self._saved_render_product = viewport_api.render_product_path omnigraph_use_legacy_sim_setting = self._settings.get_as_bool("/persistent/omnigraph/useLegacySimulationPipeline") if omnigraph_use_legacy_sim_setting is not None and omnigraph_use_legacy_sim_setting is True: carb.log_warn("/persistent/omnigraph/useLegacySimulationPipeline setting is True, which might affect render product capture and cause the capture to have no output.") self._saved_hydra_sync_load_setting = self._settings.get("/rtx/hydra/materialSyncLoads") self._saved_async_texture_streaming = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/async") self._saved_texture_streaming_budget = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB") self._saved_sampler_feedback_tile_size = self._settings.get_as_int("/rtx-transient/samplerFeedbackTileSize") self._saved_texture_streaming_eviction_frame_latency = self._settings.get_as_int("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency") # save Reshade state in post process settings self._saved_reshade_state = bool(self._settings.get("/rtx/reshade/enable")) self._saved_output_alpha_in_composite = self._settings.get_as_bool("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite") # save the visibility status of timeline window's minibar added in OM-92643 self._saved_timeline_window_mimibar_visibility = self._settings.get_as_bool("/exts/omni.kit.timeline.minibar/stay_on_playing") # save the setting for sequencer camera, we want to enable it during capture self._saved_use_sequencer_camera = self._settings.get_as_bool("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera") # if to capture mp4, save encoding settings self._save_and_set_mp4_encoding_settings() # if to capture in application mode, save viewport's padding values as we will reset it to make resolution of final image match what users set as possible as we can self._save_and_set_application_capture_settings() def _restore_window_status(self): viewport_api, self._viewport_api = self._viewport_api, None assert viewport_api is not None, "No viewport to restore to" if not self._is_legacy_vp and not self._saved_vp_updates_enabled: viewport_api.updates_enabled = self._saved_vp_updates_enabled if not self._is_legacy_vp and self._saved_fill_viewport_option: fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=viewport_api.id) self._settings.set(fv_setting_path, self._saved_fill_viewport_option) viewport_api.camera_path = self._saved_camera viewport_api.resolution = (self._saved_resolution_width, self._saved_resolution_height) if self._switch_renderer: viewport_api.set_hd_engine(self._saved_hydra_engine, self._saved_render_mode) self._settings.set_bool("/persistent/app/captureFrame/viewport", self._saved_capture_frame_viewport) self._settings.set_int("/rtx/debugMaterialType", self._saved_debug_material_type) self._settings.set_int("/rtx/pathtracing/totalSpp", self._saved_total_spp) self._settings.set_int("/rtx/pathtracing/spp", self._saved_spp) self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", self._saved_reset_pt_accum_only) self._restore_vp_object_settings(viewport_api) self._settings.set_bool("/app/asyncRendering", self._saved_async_rendering) self._settings.set_bool("/app/asyncRenderingLowLatency", self._saved_async_renderingLatency) self._renderer.set_capture_sync(not self._saved_async_rendering) self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", self._saved_background_zero_alpha) self._settings.set_bool( "/rtx/post/backgroundZeroAlpha/backgroundComposite", self._saved_background_zero_alpha_comp ) self._settings.set_bool( "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst", self._saved_background_zero_alpha_zp_first ) self._restore_iray_settings() if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._set_sunstudy_player_time(self._saved_sunstudy_current_time) self._settings.set("/rtx/materialDb/syncLoads", self._saved_rtx_sync_load_setting) self._settings.set("/rtx/hydra/materialSyncLoads", self._saved_hydra_sync_load_setting) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", self._saved_async_texture_streaming) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", self._saved_texture_streaming_budget) self._settings.set("/rtx-transient/samplerFeedbackTileSize", self._saved_sampler_feedback_tile_size) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency", self._saved_texture_streaming_eviction_frame_latency) self._settings.set("/app/captureFrame/hdr", False) # tell timeline window it can restart force checks of end time self._settings.set_bool("/exts/omni.anim.window.timeline/playinRange", True) if self._to_capture_render_product: viewport_api.render_product_path = self._saved_render_product # set Reshade to its initial value it had before te capture: self._settings.set("/rtx/reshade/enable", self._saved_reshade_state) # set Reshade update loop state to initial value, so we're ready for the next run of the update loop: self._reshade_switch_state = self.ReshadeUpdateState.PRE_CAPTURE self._settings.set("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite", self._saved_output_alpha_in_composite) if self._saved_timeline_window_mimibar_visibility: self._setting.set("/exts/omni.kit.timeline.minibar/stay_on_playing", self._saved_timeline_window_mimibar_visibility) self._settings.set("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera", self._saved_use_sequencer_camera) # if to capture mp4, restore encoding settings self._restore_mp4_encoding_settings() # if to capture in application mode, restore viewport's padding values self._restore_application_capture_settings() def _clean_pngs_in_directory(self, directory): self._clean_files_in_directory(directory, ".png") def _clean_files_in_directory(self, directory, suffix): images = os.listdir(directory) for item in images: if item.endswith(suffix): os.remove(os.path.join(directory, item)) def _make_sure_directory_existed(self, directory): if not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as error: carb.log_warn(f"Directory cannot be created: {dir}") return False return True def _make_sure_directory_writeable(self, directory): if not self._make_sure_directory_existed(directory): return False # if the directory exists, try to create a test folder and then remove it to check if it's writeable # Normally this should be done using omni.client.stat api, unfortunately it won't work well if the # give folder is a read-only one mapped by O Drive. try: test_folder_name = "(@m#C$%^)((test^file$@@).testfile" full_test_path = os.path.join(directory, test_folder_name) f = open(full_test_path, "a") f.close() os.remove(full_test_path) except OSError as error: return False return True def _finish(self): if ( self._progress.capture_status == CaptureStatus.FINISHING or self._progress.capture_status == CaptureStatus.CANCELLED ): self._update_sub = None self._restore_window_status() self._sample_count = 0 self._start_number = 0 self._frame_counter = 0 self._path_trace_iterations = 0 self._progress.capture_status = CaptureStatus.NONE # restore timeline settings # stop timeline, but re-enable auto update timeline = self._timeline timeline.set_auto_update(True) timeline.stop() self._timeline.set_current_time(self._saved_timeline_current_time) if self._capture_fps != self._saved_timeline_fps: self._timeline.set_time_codes_per_second(self._saved_timeline_fps) if self._to_capture_render_product and (self._render_product_path_for_capture != self._options.render_product): RenderProductCaptureHelper.remove_render_product_for_capture(self._render_product_path_for_capture) # restore application ui if in application level capture mode if self._options.app_level_capture: self._settings.set("/app/window/hideUi", False) if self._show_progress_window(): self._progress_window.close() if self._capture_finished_fn is not None: self._capture_finished_fn() def _wait_for_image_writing(self, seconds_to_wait: float = 5, seconds_to_sleep: float = 0.1): # wait for the last frame is written to disk # my tests of scenes of different complexity show a range of 0.2 to 1 seconds wait time # so 5 second max time should be enough and we can early quit by checking the last # frame every 0.1 seconds. seconds_tried = 0.0 carb.log_info("Waiting for frames to be ready for encoding.") while seconds_tried < seconds_to_wait: if os.path.isfile(self._frame_path) and os.access(self._frame_path, os.R_OK): break else: time.sleep(seconds_to_sleep) seconds_tried += seconds_to_sleep if seconds_tried >= seconds_to_wait: carb.log_warn(f"Wait time out. To start encoding with images already have.") def _capture_image(self, frame_path: str): if self._options.app_level_capture: self._capture_application(frame_path) else: self._capture_viewport(frame_path) def _capture_application(self, frame_path: str): async def capture_frame(capture_filename: str): try: import omni.renderer_capture renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface() renderer_capture.capture_next_frame_swapchain(capture_filename) carb.log_info(f"Capturing {capture_filename} in application level.") except ImportError: carb.log_error(f"Failed to capture {capture_filename} due to unable to import omni.renderer_capture.") await omni.kit.app.get_app().next_update_async() asyncio.ensure_future(capture_frame(frame_path)) def _capture_viewport(self, frame_path: str): is_hdr = self.options._hdr_output render_product_path = self.options._render_product if self._to_capture_render_product else None format_desc = None if self._options.file_type == ".exr": format_desc = {} format_desc["format"] = "exr" format_desc["compression"] = self._options.exr_compression_method capture_viewport_to_file( self._viewport_api, file_path=frame_path, is_hdr=is_hdr, render_product_path=render_product_path, format_desc=format_desc ) carb.log_info(f"Capturing {frame_path}") def _get_current_frame_output_path(self): frame_path = "" if self._options.is_video(): frame_path = get_num_pattern_file_path( self._frames_dir, self._options.file_name, self._options.file_name_num_pattern, self._frame, DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO, self._options.renumber_negative_frame_number_from_0, abs(self._start_number) ) else: if self._options.is_capturing_nth_frames(): if self._frame_counter % self._options.capture_every_Nth_frames == 0: frame_path = get_num_pattern_file_path( self._frame_pattern_prefix, self._options.file_name, self._options.file_name_num_pattern, self._frame, self._options.file_type, self._options.renumber_negative_frame_number_from_0, abs(self._start_number) ) else: frame_path = self._frame_pattern_prefix + self._options.file_type return frame_path def _handle_skipping_frame(self, dt): if not self._options.overwrite_existing_frames: if os.path.exists(self._frame_path): carb.log_warn(f"Frame {self._frame_path} exists, skip it...") self._settings.set_int("/rtx/pathtracing/spp", 1) self._subframe = 0 self._sample_count = 0 self._path_trace_iterations = 0 can_continue = True if self._forward_one_frame_fn is not None: can_continue = self._forward_one_frame_fn(dt) elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \ (self._options.is_video() or self._options.is_capturing_nth_frames()): self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration * self._sunstudy_iterations_per_frame self._update_sunstudy_player_time() else: # movie type is SEQUENCE self._time = self._start_time + (self._frame - self._start_number) * self._time_rate self._timeline.set_current_time(self._time) self._frame += 1 self._frame_counter += 1 # check if capture ends if self._forward_one_frame_fn is not None: if can_continue is False: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING else: if self._time >= self._end_time or self._frame_counter >= self._total_frame_count: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING return True else: if os.path.exists(self._frame_path) and self._last_skipped_frame_path != self._frame_path: carb.log_warn(f"Frame {self._frame_path} will be overwritten.") self._last_skipped_frame_path = self._frame_path return False def _get_default_settle_lateny_frames(self): # to workaround OM-40632, and OM-50514 FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK = 5 if self._options.render_preset == CaptureRenderPreset.RAY_TRACE: return FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK elif ( self._options.render_preset == CaptureRenderPreset.PATH_TRACE or self._options.render_preset == CaptureRenderPreset.IRAY ): pt_frames = self._options.ptmb_subframes_per_frame * self._options.path_trace_spp if pt_frames >= FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK: return 0 else: return FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK - pt_frames else: return 0 def _is_using_default_settle_latency_frames(self): return self._options.real_time_settle_latency_frames == 0 and self._settings.get(SEQUENCE_CAPTURE_WAIT) is None def _get_settle_latency_frames(self): settle_latency_frames = self._options.real_time_settle_latency_frames # Force a delay when capturing a range of frames if settle_latency_frames == 0 and (self._options.is_video() or self._options.is_capturing_nth_frames()): # Allow an explicit default to delay in SEQUENCE_CAPTURE_WAIT, when unset use logic below settle_latency_frames = self._settings.get(SEQUENCE_CAPTURE_WAIT) if settle_latency_frames is None: # Force a 4 frame delay when no sub-frames, otherwise account for sub-frames contributing to that 4 settle_latency_frames = self._get_default_settle_lateny_frames() carb.log_info(f"Forcing {settle_latency_frames} frame delay per frame for sequence capture") return settle_latency_frames def _is_handling_settle_latency_frames(self): return ((self._options.is_video() or self._options.is_capturing_nth_frames()) and self._settle_latency_frames > 0 and self._real_time_settle_latency_frames_done < self._settle_latency_frames ) def _handle_real_time_capture_settle_latency(self): # settle latency only works with sequence capture if not (self._options.is_video() or self._options.is_capturing_nth_frames()): return False if self._settle_latency_frames > 0: self._real_time_settle_latency_frames_done += 1 if self._real_time_settle_latency_frames_done > self._settle_latency_frames: self._real_time_settle_latency_frames_done = 0 return False else: self._subframe = 0 self._sample_count = 0 return True return False def _is_capturing_pt_mb(self): return CaptureRenderPreset.PATH_TRACE == self._options.render_preset and self._options.ptmb_subframes_per_frame > 1 def _is_capturing_pt_no_mb(self): return CaptureRenderPreset.PATH_TRACE == self._options.render_preset and 1 == self._options.ptmb_subframes_per_frame def _is_pt_adaptivesampling_stop_criterion_reached(self): if self._viewport_api is None: return False else: render_status = self._viewport_api.frame_info.get('status') return (render_status is not None and RenderStatus.eStopCriterionReached == render_status and self._is_capturing_pt_no_mb() ) def _on_update(self, e): dt = e.payload["dt"] if self._progress.capture_status == CaptureStatus.FINISHING: # need to turn reshade off, update, and turn on again in _restore_window_status to apply pre-capture resolution if self._reshade_switch_state == self.ReshadeUpdateState.POST_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", False) self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE_READY return self._finish() self._update_progress_hook() elif self._progress.capture_status == CaptureStatus.CANCELLED: # need to turn reshade off, update, and turn on again in _restore_window_status to apply pre-capture resolution if self._reshade_switch_state == self.ReshadeUpdateState.POST_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", False) self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE_READY return carb.log_warn("video recording cancelled") self._update_progress_hook() self._finish() elif self._progress.capture_status == CaptureStatus.ENCODING: if VideoGenerationHelper().encoding_done: self._progress.capture_status = CaptureStatus.FINISHING self._update_progress_hook() self._progress.add_encoding_time(dt) elif self._progress.capture_status == CaptureStatus.TO_START_ENCODING: if VideoGenerationHelper().is_encoding is False: self._wait_for_image_writing() if self._options.renumber_negative_frame_number_from_0 is True and self._start_number < 0: video_frame_start_num = 0 else: video_frame_start_num = self._start_number started = VideoGenerationHelper().generating_video( self._video_name, self._frames_dir, self._options.file_name, self._options.file_name_num_pattern, video_frame_start_num, self._total_frame_count, self._options.fps, ) if started: self._progress.capture_status = CaptureStatus.ENCODING self._update_progress_hook() self._progress.add_encoding_time(dt) else: carb.log_warn("Movie capture failed to encode the capture images.") self._progress.capture_status = CaptureStatus.FINISHING elif self._progress.capture_status == CaptureStatus.CAPTURING: if self._frames_to_disable_async_rendering >= 0: self._frames_to_disable_async_rendering -= 1 return #apply Reshade and skip frames to to pick up capturing resolution if self._reshade_switch_state == self.ReshadeUpdateState.PRE_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", self._saved_reshade_state) # need to skip a couple of updates for Reshade settings to apply: if self._frames_to_apply_reshade>=0: self._frames_to_apply_reshade=self._frames_to_apply_reshade-1 return self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE return if self._progress.is_prerolling(): self._progress.prerolled_frames += 1 self._settings.set_int("/rtx/pathtracing/spp", 1) left_preroll_frames = self._options.preroll_frames - self._progress.prerolled_frames self._timeline.set_current_time(self._start_time - left_preroll_frames / self._capture_fps) return self._frame_path = self._get_current_frame_output_path() if self._handle_skipping_frame(dt): self._progress.add_frame_time(self._frame, dt) self._update_progress_hook() return self._settings.set_int( "/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp) ) if self._options.render_preset == CaptureRenderPreset.IRAY: iterations_done = int(self._settings.get("/iray/progression")) self._path_trace_iterations = iterations_done self._sample_count = iterations_done else: self._sample_count += self._options.spp_per_iteration self._path_trace_iterations = self._sample_count self._timeline.set_prerolling(False) self._settings.set_int("/rtx/externalFrameCounter", self._frame) # update progress timers if self._options.is_capturing_pathtracing_single_frame(): if self._options.render_preset == CaptureRenderPreset.PATH_TRACE: self._progress.add_single_frame_capture_time_for_pt(self._subframe, self._options.ptmb_subframes_per_frame, dt) elif self._options.render_preset == CaptureRenderPreset.IRAY: self._progress.add_single_frame_capture_time_for_iray( self._subframe, self._options.ptmb_subframes_per_frame, self._path_trace_iterations, self._options.path_trace_spp, dt ) else: carb.log_warn(f"Movie capture: we don't support progress for {self._options.render_preset} in single frame capture mode.") else: self._progress.add_frame_time(self._frame, dt, self._subframe + 1, self._options.ptmb_subframes_per_frame, self._path_trace_iterations, self._options.path_trace_spp, self._is_handling_settle_latency_frames() and not self._is_using_default_settle_latency_frames(), self._real_time_settle_latency_frames_done, self._settle_latency_frames ) self._update_progress_hook() # check if path trace and meet the samples per pixels stop criterion render_status = self._viewport_api.frame_info.get('status') if RenderStatus.eStopCriterionReached == render_status and self._is_adaptivesampling_stop_criterion_reached: carb.log_info("Got continuous path tracing adaptive sampling stop criterion reached event, skip this frame for it to finish.") return self._is_adaptivesampling_stop_criterion_reached = self._is_pt_adaptivesampling_stop_criterion_reached() # capture frame when we reach the sample count for this frame and are rendering the last subframe # Note _sample_count can go over _samples_per_pixel when 'spp_per_iteration > 1' # also handle the case when we have adaptive sampling enabled and it returns stop criterion reached if (self._sample_count >= self._options.path_trace_spp) and \ (self._subframe == self._options.ptmb_subframes_per_frame - 1) or \ self._is_adaptivesampling_stop_criterion_reached: if self._handle_real_time_capture_settle_latency(): return if self._options.is_video(): self._capture_image(self._frame_path) else: if self._options.is_capturing_nth_frames(): if self._frame_counter % self._options.capture_every_Nth_frames == 0: self._capture_image(self._frame_path) else: self._progress.capture_status = CaptureStatus.FINISHING self._capture_image(self._frame_path) # reset time the *next frame* (since otherwise we capture the first sample) if self._sample_count >= self._options.path_trace_spp or self._is_adaptivesampling_stop_criterion_reached: self._sample_count = 0 self._path_trace_iterations = 0 self._subframe += 1 if self._subframe == self._options.ptmb_subframes_per_frame: self._subframe = 0 self._frame += 1 self._frame_counter += 1 self._time = self._start_time + (self._frame - self._start_number) * self._time_rate can_continue = False if self._forward_one_frame_fn is not None: can_continue = self._forward_one_frame_fn(dt) elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \ (self._options.is_video() or self._options.is_capturing_nth_frames()): self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration self._update_sunstudy_player_time() else: if self._options.is_video() or self._options.is_capturing_nth_frames(): cur_time = ( self._time + (self._options.ptmb_fso * self._time_rate) + self._time_subframe_rate * self._subframe ) self._timeline.set_current_time(cur_time) if self._forward_one_frame_fn is not None: if can_continue == False: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING else: if self._time >= self._end_time or self._frame_counter >= self._total_frame_count: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING @staticmethod def get_instance(): global capture_instance return capture_instance
65,590
Python
51.599038
195
0.63496
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/video_generation.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import threading import carb try: from video_encoding import get_video_encoding_interface except ImportError: get_video_encoding_interface = lambda: None from .singleton import Singleton from .helper import get_num_pattern_file_path g_video_encoding_api = get_video_encoding_interface() @Singleton class VideoGenerationHelper: def __init__(self): self._init_internal() @property def is_encoding(self): return self._is_encoding @property def encoding_done(self): return self._is_encoding == False and self._encoding_done == True def generating_video( self, video_name, frames_dir, filename_prefix, filename_num_pattern, start_number, total_frames, frame_rate, image_type=".png" ): carb.log_warn(f"Using videoencoding plugin to encode video ({video_name})") global g_video_encoding_api self._encoding_finished = False if g_video_encoding_api is None: carb.log_warn("Video encoding api not available; cannot encode video.") return False # acquire list of available frame image files, based on start_number and filename_pattern next_frame = start_number frame_count = 0 self._frame_filenames = [] while True: frame_path = get_num_pattern_file_path( frames_dir, filename_prefix, filename_num_pattern, next_frame, image_type ) if os.path.isfile(frame_path) and os.access(frame_path, os.R_OK): self._frame_filenames.append(frame_path) next_frame += 1 frame_count += 1 if frame_count == total_frames: break else: break carb.log_warn(f"Found {len(self._frame_filenames)} frames to encode.") if len(self._frame_filenames) == 0: carb.log_warn(f"No frames to encode.") return False if not g_video_encoding_api.start_encoding(video_name, frame_rate, len(self._frame_filenames), True): carb.log_warn(f"videoencoding plug failed to start encoding.") return False if self._encoding_thread == None: self._encoding_thread = threading.Thread(target=self._encode_image_file_sequence, args=()) self._is_encoding = True self._encoding_thread.start() return True def _init_internal(self): self._video_generation_done_fn = None self._frame_filenames = [] self._encoding_thread = None self._is_encoding = False self._encoding_done = False def _encode_image_file_sequence(self): global g_video_encoding_api try: for frame_filename in self._frame_filenames: g_video_encoding_api.encode_next_frame_from_file(frame_filename) except: import traceback carb.log_warn(traceback.format_exc()) finally: g_video_encoding_api.finalize_encoding() self._init_internal() self._encoding_done = True
3,608
Python
33.701923
109
0.622228
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import CaptureExtension from .capture_options import * from .capture_progress import *
537
Python
40.384612
76
0.808194
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/capture_options.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from enum import Enum, IntEnum import carb class CaptureMovieType(IntEnum): SEQUENCE = 0 SUNSTUDY = 1 PLAYLIST = 2 class CaptureRangeType(IntEnum): FRAMES = 0 SECONDS = 1 class CaptureRenderPreset(IntEnum): PATH_TRACE = 0 RAY_TRACE = 1 IRAY = 2 class CaptureDebugMaterialType(IntEnum): SHADED = 0 WHITE = 1 EXR_COMPRESSION_METHODS = {"zip", "zips", "dwaa", "dwab", "piz", "rle", "b44", "b44a"} MP4_ENCODING_PRESETS = { "PRESET_DEFAULT", "PRESET_HP", "PRESET_HQ", "PRESET_BD", "PRESET_LOW_LATENCY_DEFAULT", "PRESET_LOW_LATENCY_HQ", "PRESET_LOW_LATENCY_HP", "PRESET_LOSSLESS_DEFAULT", "PRESET_LOSSLESS_HP" } MP4_ENCODING_PROFILES = { "H264_PROFILE_BASELINE", "H264_PROFILE_MAIN", "H264_PROFILE_HIGH", "H264_PROFILE_HIGH_444", "H264_PROFILE_STEREO", "H264_PROFILE_SVC_TEMPORAL_SCALABILITY", "H264_PROFILE_PROGRESSIVE_HIGH", "H264_PROFILE_CONSTRAINED_HIGH", "HEVC_PROFILE_MAIN", "HEVC_PROFILE_MAIN10", "HEVC_PROFILE_FREXT" } MP4_ENCODING_RC_MODES = { "RC_CONSTQP", "RC_VBR", "RC_CBR", "RC_CBR_LOWDELAY_HQ", "RC_CBR_HQ", "RC_VBR_HQ" } class CaptureOptions: """ All Capture options that will be used when capturing. Note: When adding an attribute make sure it is exposed via the constructor. Not doing this will cause erorrs when serializing and deserializing this object. """ INVALID_ANIMATION_FPS = -1 def __init__( self, camera="camera", range_type=CaptureRangeType.FRAMES, capture_every_nth_frames=-1, fps=24, start_frame=1, end_frame=40, start_time=0, end_time=10, res_width=1920, res_height=1080, render_preset=CaptureRenderPreset.PATH_TRACE, debug_material_type=CaptureDebugMaterialType.SHADED, spp_per_iteration=1, path_trace_spp=1, ptmb_subframes_per_frame=1, ptmb_fso=0.0, ptmb_fsc=1.0, output_folder="", file_name="Capture", file_name_num_pattern=".####", file_type=".tga", save_alpha=False, hdr_output=False, show_pathtracing_single_frame_progress=False, preroll_frames=0, overwrite_existing_frames=False, movie_type=CaptureMovieType.SEQUENCE, sunstudy_start_time=0.0, sunstudy_current_time=0.0, sunstudy_end_time=0.0, sunstudy_movie_length_in_seconds=0, sunstudy_player=None, real_time_settle_latency_frames=0, renumber_negative_frame_number_from_0=False, render_product="", exr_compression_method="zips", mp4_encoding_bitrate=16777216, mp4_encoding_iframe_interval=60, mp4_encoding_preset="PRESET_DEFAULT", mp4_encoding_profile="H264_PROFILE_HIGH", mp4_encoding_rc_mode="RC_VBR", mp4_encoding_rc_target_quality=0, mp4_encoding_video_full_range_flag=False, app_level_capture=False, animation_fps=INVALID_ANIMATION_FPS ): self._camera = camera self._range_type = range_type self._capture_every_nth_frames = capture_every_nth_frames self._fps = fps self._start_frame = start_frame self._end_frame = end_frame self._start_time = start_time self._end_time = end_time self._res_width = res_width self._res_height = res_height self._render_preset = render_preset self._debug_material_type = debug_material_type self._spp_per_iteration = spp_per_iteration self._path_trace_spp = path_trace_spp self._ptmb_subframes_per_frame = ptmb_subframes_per_frame self._ptmb_fso = ptmb_fso self._ptmb_fsc = ptmb_fsc self._output_folder = output_folder self._file_name = file_name self._file_name_num_pattern = file_name_num_pattern self._file_type = file_type self._save_alpha = save_alpha self._hdr_output = hdr_output self._show_pathtracing_single_frame_progress = show_pathtracing_single_frame_progress self._preroll_frames = preroll_frames self._overwrite_existing_frames = overwrite_existing_frames self._movie_type = movie_type self._sunstudy_start_time = sunstudy_start_time self._sunstudy_current_time = sunstudy_current_time self._sunstudy_end_time = sunstudy_end_time self._sunstudy_movie_length_in_seconds = sunstudy_movie_length_in_seconds self._sunstudy_player = sunstudy_player self._real_time_settle_latency_frames = real_time_settle_latency_frames self._renumber_negative_frame_number_from_0 = renumber_negative_frame_number_from_0 self._render_product = render_product self.exr_compression_method = exr_compression_method self.mp4_encoding_bitrate = mp4_encoding_bitrate self.mp4_encoding_iframe_interval = mp4_encoding_iframe_interval self.mp4_encoding_preset = mp4_encoding_preset self.mp4_encoding_profile = mp4_encoding_profile self.mp4_encoding_rc_mode = mp4_encoding_rc_mode self.mp4_encoding_rc_target_quality = mp4_encoding_rc_target_quality self.mp4_encoding_video_full_range_flag = mp4_encoding_video_full_range_flag self._app_level_capture = app_level_capture self.animation_fps = animation_fps def to_dict(self): data = vars(self) return {key.lstrip("_"): value for key, value in data.items()} @classmethod def from_dict(cls, options): return cls(**options) @property def camera(self): return self._camera @camera.setter def camera(self, value): self._camera = value @property def range_type(self): return self._range_type @range_type.setter def range_type(self, value): self._range_type = value @property def capture_every_Nth_frames(self): return self._capture_every_nth_frames @capture_every_Nth_frames.setter def capture_every_Nth_frames(self, value): self._capture_every_nth_frames = value @property def fps(self): return self._fps @fps.setter def fps(self, value): self._fps = value @property def start_frame(self): return self._start_frame @start_frame.setter def start_frame(self, value): self._start_frame = value @property def end_frame(self): return self._end_frame @end_frame.setter def end_frame(self, value): self._end_frame = value @property def start_time(self): return self._start_time @start_time.setter def start_time(self, value): self._start_time = value @property def end_time(self): return self._end_time @end_time.setter def end_time(self, value): self._end_time = value @property def res_width(self): return self._res_width @res_width.setter def res_width(self, value): self._res_width = value @property def res_height(self): return self._res_height @res_height.setter def res_height(self, value): self._res_height = value @property def render_preset(self): return self._render_preset @render_preset.setter def render_preset(self, value): self._render_preset = value @property def debug_material_type(self): return self._debug_material_type @debug_material_type.setter def debug_material_type(self, value): self._debug_material_type = value @property def spp_per_iteration(self): return self._spp_per_iteration @spp_per_iteration.setter def spp_per_iteration(self, value): self._spp_per_iteration = value @property def path_trace_spp(self): return self._path_trace_spp @path_trace_spp.setter def path_trace_spp(self, value): self._path_trace_spp = value @property def ptmb_subframes_per_frame(self): return self._ptmb_subframes_per_frame @ptmb_subframes_per_frame.setter def ptmb_subframes_per_frame(self, value): self._ptmb_subframes_per_frame = value @property def ptmb_fso(self): return self._ptmb_fso @ptmb_fso.setter def ptmb_fso(self, value): self._ptmb_fso = value @property def ptmb_fsc(self): return self._ptmb_fsc @ptmb_fsc.setter def ptmb_fsc(self, value): self._ptmb_fsc = value @property def output_folder(self): return self._output_folder @output_folder.setter def output_folder(self, value): self._output_folder = value @property def file_name(self): return self._file_name @file_name.setter def file_name(self, value): self._file_name = value @property def file_name_num_pattern(self): return self._file_name_num_pattern @file_name_num_pattern.setter def file_name_num_pattern(self, value): self._file_name_num_pattern = value @property def file_type(self): return self._file_type @file_type.setter def file_type(self, value): self._file_type = value @property def save_alpha(self): return self._save_alpha @save_alpha.setter def save_alpha(self, value): self._save_alpha = value @property def hdr_output(self): return self._hdr_output @hdr_output.setter def hdr_output(self, value): self._hdr_output = value @property def show_pathtracing_single_frame_progress(self): return self._show_pathtracing_single_frame_progress @show_pathtracing_single_frame_progress.setter def show_pathtracing_single_frame_progress(self, value): self._show_pathtracing_single_frame_progress = value @property def preroll_frames(self): return self._preroll_frames @preroll_frames.setter def preroll_frames(self, value): self._preroll_frames = value @property def overwrite_existing_frames(self): return self._overwrite_existing_frames @overwrite_existing_frames.setter def overwrite_existing_frames(self, value): self._overwrite_existing_frames = value @property def movie_type(self): return self._movie_type @movie_type.setter def movie_type(self, value): self._movie_type = value @property def sunstudy_start_time(self): return self._sunstudy_start_time @sunstudy_start_time.setter def sunstudy_start_time(self, value): self._sunstudy_start_time = value @property def sunstudy_current_time(self): return self._sunstudy_current_time @sunstudy_current_time.setter def sunstudy_current_time(self, value): self._sunstudy_current_time = value @property def sunstudy_end_time(self): return self._sunstudy_end_time @sunstudy_end_time.setter def sunstudy_end_time(self, value): self._sunstudy_end_time = value @property def sunstudy_movie_length_in_seconds(self): return self._sunstudy_movie_length_in_seconds @sunstudy_movie_length_in_seconds.setter def sunstudy_movie_length_in_seconds(self, value): self._sunstudy_movie_length_in_seconds = value @property def sunstudy_player(self): return self._sunstudy_player @sunstudy_player.setter def sunstudy_player(self, value): self._sunstudy_player = value @property def real_time_settle_latency_frames(self): return self._real_time_settle_latency_frames @real_time_settle_latency_frames.setter def real_time_settle_latency_frames(self, value): self._real_time_settle_latency_frames = value @property def renumber_negative_frame_number_from_0(self): return self._renumber_negative_frame_number_from_0 @renumber_negative_frame_number_from_0.setter def renumber_negative_frame_number_from_0(self, value): self._renumber_negative_frame_number_from_0 = value @property def render_product(self): return self._render_product @render_product.setter def render_product(self, value): self._render_product = value @property def exr_compression_method(self): return self._exr_compression_method @exr_compression_method.setter def exr_compression_method(self, value): global EXR_COMPRESSION_METHODS if value in EXR_COMPRESSION_METHODS: self._exr_compression_method = value else: self._exr_compression_method = "zips" carb.log_warn(f"Can't set unsupported compression method {value} for exr format, set to default zip16. Supported values are: {EXR_COMPRESSION_METHODS}") @property def mp4_encoding_bitrate(self): return self._mp4_encoding_bitrate @mp4_encoding_bitrate.setter def mp4_encoding_bitrate(self, value): self._mp4_encoding_bitrate = value @property def mp4_encoding_iframe_interval(self): return self._mp4_encoding_iframe_interval @mp4_encoding_iframe_interval.setter def mp4_encoding_iframe_interval(self, value): self._mp4_encoding_iframe_interval = value @property def mp4_encoding_preset(self): return self._mp4_encoding_preset @mp4_encoding_preset.setter def mp4_encoding_preset(self, value): global MP4_ENCODING_PRESETS if value in MP4_ENCODING_PRESETS: self._mp4_encoding_preset = value else: self._mp4_encoding_preset = "PRESET_DEFAULT" carb.log_warn(f"Can't set unsupported mp4 encoding preset {value}, set to default {self._mp4_encoding_preset}. Supported values are: {MP4_ENCODING_PRESETS}") @property def mp4_encoding_profile(self): return self._mp4_encoding_profile @mp4_encoding_profile.setter def mp4_encoding_profile(self, value): global MP4_ENCODING_PROFILES if value in MP4_ENCODING_PROFILES: self._mp4_encoding_profile = value else: self._mp4_encoding_profile = "H264_PROFILE_HIGH" carb.log_warn(f"Can't set unsupported mp4 encoding profile {value}, set to default {self._mp4_encoding_profile}. Supported values are: {MP4_ENCODING_PROFILES}") @property def mp4_encoding_rc_mode(self): return self._mp4_encoding_rc_mode @mp4_encoding_rc_mode.setter def mp4_encoding_rc_mode(self, value): global MP4_ENCODING_RC_MODES if value in MP4_ENCODING_RC_MODES: self._mp4_encoding_rc_mode = value else: self._mp4_encoding_rc_mode = "RC_VBR" carb.log_warn(f"Can't set unsupported mp4 encoding rate control mode {value}, set to default {self._mp4_encoding_rc_mode}. Supported values are: {MP4_ENCODING_RC_MODES}") @property def mp4_encoding_rc_target_quality(self): return self._mp4_encoding_rc_target_quality @mp4_encoding_rc_target_quality.setter def mp4_encoding_rc_target_quality(self, value): if 0 <= value and value <= 51: self._mp4_encoding_rc_target_quality = value else: self._mp4_encoding_rc_target_quality = 0 carb.log_warn(f"Can't set unsupported mp4 encoding rate control target quality {value}, set to default {self._mp4_encoding_rc_target_quality}. Supported range is [0, 51]") @property def mp4_encoding_video_full_range_flag(self): return self._mp4_encoding_video_full_range_flag @mp4_encoding_video_full_range_flag.setter def mp4_encoding_video_full_range_flag(self, value): self._mp4_encoding_video_full_range_flag = value @property def app_level_capture(self): return self._app_level_capture @app_level_capture.setter def app_level_capture(self, value): self._app_level_capture = value @property def animation_fps(self): return self._animation_fps @animation_fps.setter def animation_fps(self, value): self._animation_fps = value def is_video(self): return self.file_type == ".mp4" def is_capturing_nth_frames(self): return self._capture_every_nth_frames > 0 def is_capturing_pathtracing_single_frame(self): return ( self.is_video() is False and self.is_capturing_nth_frames() is False and (self.render_preset == CaptureRenderPreset.PATH_TRACE or self.render_preset == CaptureRenderPreset.IRAY) ) def is_capturing_frame(self): return self._range_type == CaptureRangeType.FRAMES def get_full_path(self): return os.path.join(self._output_folder, self._file_name + self._file_type)
17,273
Python
28.629503
183
0.645632
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/helper.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import carb import omni.kit.app import omni.usd from pxr import Sdf, UsdRender, Gf, Usd ViewportObjectsSettingDict = { "guide/selection": "/app/viewport/outline/enabled", "scene/lights": "/app/viewport/show/lights", "scene/audio": "/app/viewport/show/audio", "scene/cameras": "/app/viewport/show/camera", "guide/grid": "/app/viewport/grid/enabled" } def get_num_pattern_file_path(frames_dir, file_name, num_pattern, frame_num, file_type, renumber_frames=False, renumber_offset=0): if renumber_frames: renumbered_frames = frame_num + renumber_offset else: renumbered_frames = frame_num abs_frame_num = abs(renumbered_frames) padding_length = len(num_pattern.strip(".")[len(str(abs_frame_num)) :]) if renumbered_frames >= 0: padded_string = "0" * padding_length + str(renumbered_frames) else: padded_string = "-" + "0" * padding_length + str(abs_frame_num) filename = ".".join((file_name, padded_string, file_type.strip("."))) frame_path = os.path.join(frames_dir, filename) return frame_path def is_ext_enabled(ext_name): ext_manager = omni.kit.app.get_app().get_extension_manager() return ext_manager.is_extension_enabled(ext_name) # TODO: These version checks exists only in case down-stream movie-capture has imported them # They should be removed for 105.2 and above. # def check_kit_major_version(version_num: int) -> bool: kit_version = omni.kit.app.get_app().get_build_version().split(".") try: major_ver = int(kit_version[0]) return major_ver >= version_num except Exception as e: return False def is_kit_104_and_above() -> bool: return False def is_kit_105_and_above() -> bool: return True def get_vp_object_setting_path(viewport_api, setting_key: str) -> str: usd_context_name = viewport_api.usd_context_name if setting_key.startswith("scene"): setting_path = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible" else: setting_path = f"/persistent/app/viewport/{viewport_api.id}/{setting_key}/visible" return setting_path def get_vp_object_visibility(viewport_api, setting_key: str) -> bool: settings = carb.settings.get_settings() setting_path = get_vp_object_setting_path(viewport_api, setting_key) return settings.get_as_bool(setting_path) def set_vp_object_visibility(viewport_api, setting_key: str, visible: bool) -> None: if get_vp_object_visibility(viewport_api, setting_key) == visible: return settings = carb.settings.get_settings() action_key = { "guide/selection": "toggle_selection_hilight_visibility", "scene/lights": "toggle_light_visibility", "scene/audio": "toggle_audio_visibility", "scene/cameras": "toggle_camera_visibility", "guide/grid": "toggle_grid_visibility" }.get(setting_key, None) if not action_key: carb.log_error(f"No mapping between {setting_key} and omni.kit.viewport.actions") return action_registry = omni.kit.actions.core.get_action_registry() action = action_registry.get_action("omni.kit.viewport.actions", action_key) if action: action.execute(viewport_api=viewport_api, visible=visible) else: carb.log_error(f"Did not find action omni.kit.viewport.actions.{action_key}") def check_render_product_ext_availability(): return is_ext_enabled("omni.graph.nodes") and is_ext_enabled("omni.graph.examples.cpp") def is_valid_render_product_prim_path(prim_path): try: import omni.usd from pxr import UsdRender usd_context = omni.usd.get_context() stage = usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path) if prim: return prim.IsA(UsdRender.Product) else: return False except Exception as e: return False class RenderProductCaptureHelper: @staticmethod def prepare_render_product_for_capture(render_product_prim_path, new_camera, new_resolution): usd_context = omni.usd.get_context() stage = usd_context.get_stage() working_layer = stage.GetSessionLayer() prim = stage.GetPrimAtPath(render_product_prim_path) path_new = omni.usd.get_stage_next_free_path(stage, render_product_prim_path, False) if prim.IsA(UsdRender.Product): with Usd.EditContext(stage, working_layer): omni.kit.commands.execute("CopyPrim", path_from=render_product_prim_path, path_to=path_new, duplicate_layers=False, combine_layers=True,exclusive_select=True) prim_new = stage.GetPrimAtPath(path_new) if prim_new.IsA(UsdRender.Product): omni.usd.editor.set_no_delete(prim_new, False) prim_new.GetAttribute("resolution").Set(new_resolution) prim_new.GetRelationship("camera").SetTargets([new_camera]) else: path_new = "" else: path_new = "" return path_new @staticmethod def remove_render_product_for_capture(render_product_prim_path): usd_context = omni.usd.get_context() stage = usd_context.get_stage() working_layer = stage.GetSessionLayer() prim = working_layer.GetPrimAtPath(render_product_prim_path) if prim: if prim.nameParent: name_parent = prim.nameParent else: name_parent = working_layer.pseudoRoot if not name_parent: return name = prim.name if name in name_parent.nameChildren: del name_parent.nameChildren[name]
6,149
Python
36.730061
174
0.660433
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/singleton.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
697
Python
32.238094
76
0.725968
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/__init__.py
from .test_capture_options import TestCaptureOptions from .test_capture_hdr import TestCaptureHdr from .test_capture_png import TestCapturePng from .test_capture_render_product import TestCaptureRenderProduct
208
Python
51.249987
65
0.865385
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_helper.py
import os import os.path import asyncio import carb import omni.kit.app def clean_files_in_directory(directory, suffix): if not os.path.exists(directory): return images = os.listdir(directory) for item in images: if item.endswith(suffix): os.remove(os.path.join(directory, item)) def make_sure_directory_existed(directory): if not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as error: carb.log_warn(f"Directory cannot be created: {dir}") return False return True # TODO: Remove this as it is no longer used, but kept only if transitively depended on # def is_kit_104_and_above(): kit_version = omni.kit.app.get_app().get_build_version().split(".") try: major_ver = int(kit_version[0]) return major_ver >= 104 except Exception as e: return False async def wait_for_image_writing(image_path, seconds_to_wait: float = 30, seconds_to_sleep: float = 0.5): seconds_tried = 0.0 carb.log_info(f"Waiting for {image_path} to be written to disk.") while seconds_tried < seconds_to_wait: if os.path.isfile(image_path) and os.access(image_path, os.R_OK): carb.log_info(f"{image_path} is written to disk in {seconds_tried}s.") break else: await asyncio.sleep(seconds_to_sleep) seconds_tried += seconds_to_sleep if seconds_tried >= seconds_to_wait: carb.log_warn(f"Waiting for {image_path} timed out..")
1,562
Python
30.259999
105
0.638924
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_hdr.py
from typing import Type import os import os.path import omni.kit.test import carb import carb.settings import carb.tokens import pathlib import gc from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport, create_viewport_window, capture_viewport_to_file from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") class TestCaptureHdr(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' settings = carb.settings.get_settings() self._frames_wait_for_capture_resource_ready = 6 await omni.usd.get_context(self._usd_context).new_stage_async() async def test_hdr_capture(self): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_hdr_test" filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".exr" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") exr_path = os.path.join(options._output_folder, "Capture1.exr") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = True options.camera = viewport_api.camera_path.pathString # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path) async def _test_exr_compression_method(self, compression_method): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_exr_compression_method_test_" + compression_method filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".exr" options.exr_compression_method = compression_method options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") exr_path = os.path.join(options._output_folder, "Capture1.exr") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = True options.camera = viewport_api.camera_path.pathString # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path) async def test_exr_compression_method_rle(self): await self._test_exr_compression_method("rle") async def test_exr_compression_method_zip(self): await self._test_exr_compression_method("zip") async def test_exr_compression_method_dwaa(self): await self._test_exr_compression_method("dwaa") async def test_exr_compression_method_dwab(self): await self._test_exr_compression_method("dwab") async def test_exr_compression_method_piz(self): await self._test_exr_compression_method("piz") async def test_exr_compression_method_b44(self): await self._test_exr_compression_method("b44") async def test_exr_compression_method_b44a(self): await self._test_exr_compression_method("b44a") # Notes: The following multiple viewport tests will fail now and should be revisited after we confirm the # multiple viewport capture support in new SRD. # # Make sure we do not crash in the unsupported multi-view case # async def test_hdr_multiview_capture(self): # viewport_api = get_active_viewport(self._usd_context) # # Wait until the viewport has valid resources # await viewport_api.wait_for_rendered_frames() # new_viewport = create_viewport_window("Viewport 2") # capture_filename = "capture.hdr_test.multiview" # filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) # options = CaptureOptions() # options.file_type = ".exr" # options.output_folder = str(filePath) # self._make_sure_directory_existed(options.output_folder) # self._clean_files_in_directory(options.output_folder, ".exr") # exr_path = os.path.join(options._output_folder, "Capture1.exr") # carb.log_warn(f"Capture image path: {exr_path}") # options.hdr_output = True # options.camera = viewport_api.camera_path.pathString # capture_instance = CaptureExtension().get_instance() # capture_instance.options = options # capture_instance.start() # capture_viewport_to_file(new_viewport.viewport_api, file_path=exr_path) # i = self._frames_wait_for_capture_resource_ready # while i > 0: # await omni.kit.app.get_app().next_update_async() # i -= 1 # options = None # capture_instance = None # gc.collect() # assert os.path.isfile(exr_path) # if viewport_widget: # viewport_widget.destroy() # del viewport_widget # async def test_hdr_multiview_capture_legacy(self): # await self.do_test_hdr_multiview_capture(True) # async def test_hdr_multiview_capture(self): # await self.do_test_hdr_multiview_capture(False)
6,254
Python
38.588607
109
0.668372
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_options.py
from typing import Type import omni.kit.test import omni.kit.capture.viewport.capture_options as _capture_options class TestCaptureOptions(omni.kit.test.AsyncTestCase): async def test_capture_options_serialisation(self): options = _capture_options.CaptureOptions() data_dict = options.to_dict() self.assertIsInstance(data_dict, dict) async def test_capture_options_deserialisation(self): options = _capture_options.CaptureOptions() data_dict = options.to_dict() regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict) self.assertIsInstance(regenerated_options, _capture_options.CaptureOptions) async def test_capture_options_values_persisted(self): options = _capture_options.CaptureOptions(camera="my_camera") data_dict = options.to_dict() regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict) self.assertEqual(regenerated_options.camera, "my_camera") async def test_adding_random_attribute_fails(self): """ Test that adding new attributes without making them configurable via the __init__ will raise an exception """ options = _capture_options.CaptureOptions() options._my_new_value = "foo" data_dict = options.to_dict() with self.assertRaises(TypeError, msg="__init__() got an unexpected keyword argument 'my_new_value'"): regnerated = _capture_options.CaptureOptions.from_dict(data_dict) async def test_capture_options_unsupported_exr_compression_method(self): options = _capture_options.CaptureOptions(exr_compression_method="sth_wrong") self.assertEqual(options.exr_compression_method, "zips") async def test_capture_options_mp4_encoding_settings(self): options = _capture_options.CaptureOptions( mp4_encoding_bitrate=4194304, mp4_encoding_iframe_interval=10, mp4_encoding_preset="PRESET_LOSSLESS_HP", mp4_encoding_profile="H264_PROFILE_PROGRESSIVE_HIGH", mp4_encoding_rc_mode="RC_VBR_HQ", mp4_encoding_rc_target_quality=51, mp4_encoding_video_full_range_flag=True, ) self.assertEqual(options.mp4_encoding_bitrate, 4194304) self.assertEqual(options.mp4_encoding_iframe_interval, 10) self.assertEqual(options.mp4_encoding_preset, "PRESET_LOSSLESS_HP") self.assertEqual(options.mp4_encoding_profile, "H264_PROFILE_PROGRESSIVE_HIGH") self.assertEqual(options._mp4_encoding_rc_mode, "RC_VBR_HQ") self.assertEqual(options._mp4_encoding_rc_target_quality, 51) self.assertEqual(options.mp4_encoding_video_full_range_flag, True) async def test_capture_options_unsupported_mp4_encoding_settings(self): options = _capture_options.CaptureOptions( mp4_encoding_bitrate=4194304, mp4_encoding_iframe_interval=10, mp4_encoding_preset="PRESET_NOT_EXISTING", mp4_encoding_profile="PROFILE_NOT_EXISTING", mp4_encoding_rc_mode="RC_NOT_EXISTING", mp4_encoding_rc_target_quality=52, mp4_encoding_video_full_range_flag=True, ) self.assertEqual(options.mp4_encoding_bitrate, 4194304) self.assertEqual(options.mp4_encoding_iframe_interval, 10) self.assertEqual(options.mp4_encoding_preset, "PRESET_DEFAULT") self.assertEqual(options.mp4_encoding_profile, "H264_PROFILE_HIGH") self.assertEqual(options._mp4_encoding_rc_mode, "RC_VBR") self.assertEqual(options._mp4_encoding_rc_target_quality, 0) self.assertEqual(options.mp4_encoding_video_full_range_flag, True)
3,701
Python
47.077921
117
0.690354
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_render_product.py
import os import os.path import omni.kit.test import omni.usd import carb import carb.settings import carb.tokens import pathlib import gc import unittest from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport from omni.kit.test_suite.helpers import wait_stage_loading from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent.parent.parent) class TestCaptureRenderProduct(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' self._frames_per_sec_to_wait_for_capture_resource_ready = 60 test_usd = TEST_DIR + "/data/tests/usd/PTAccumulateTest.usd" carb.log_warn(f"testing capture with usd {test_usd}") self._capture_folder_1spp = "rp_1spp" self._capture_folder_32spp = "rp_32spp" self._capture_folder_sequence = "rp_seq" self._context = omni.usd.get_context() self._capture_instance = CaptureExtension().get_instance() await self._context.open_stage_async(test_usd) await wait_stage_loading() for _ in range(2): await omni.kit.app.get_app().next_update_async() async def tearDown(self) -> None: self._capture_instance = None async def _test_render_product_capture(self, image_folder, render_product_name, spp, enable_hdr=True, sequence_capture=False, start_frame=0, end_frame=10): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() # wait for PT to resolve after loading, otherwise it's easy to crash i = self._frames_per_sec_to_wait_for_capture_resource_ready * 50 while i > 0: await omni.kit.app.get_app().next_update_async() i -= 1 # assert True capture_folder_name = image_folder filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) options = CaptureOptions() options.file_type = ".exr" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") options.hdr_output = enable_hdr options.camera = viewport_api.camera_path.pathString options.render_preset = omni.kit.capture.viewport.CaptureRenderPreset.PATH_TRACE options.render_product = render_product_name options.path_trace_spp = spp # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 if sequence_capture: options.capture_every_Nth_frames = 1 options.start_frame = start_frame options.end_frame = end_frame self._capture_instance.options = options self._capture_instance.start() options = None async def _verify_file_exist(self, capture_folder_name, aov_channel): exr_path = self._get_exr_path(capture_folder_name, aov_channel) carb.log_warn(f"Verifying image: {exr_path}") await wait_for_image_writing(exr_path, 40) assert os.path.isfile(exr_path) def _get_exr_path(self, capture_folder_name, aov_channel): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) exr_path = os.path.join(str(image_folder), "Capture1_" + aov_channel + ".exr") return exr_path def _get_captured_image_size(self, capture_folder_name, aov_channel): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) exr_path = os.path.join(str(image_folder), "Capture1_" + aov_channel + ".exr") if os.path.isfile(exr_path): return os.path.getsize(exr_path) else: return 0 async def test_capture_1_default_rp(self): if True: # skip the test for vp2 due to OM-77175: we know it will fail and have a bug for it so mark it true here # and re-enable it after the bug gets fixed image_folder_name = "vp2_default_rp" default_rp_name = "/Render/RenderProduct_omni_kit_widget_viewport_ViewportTexture_0" assert True for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() return await self._test_render_product_capture(image_folder_name, default_rp_name, 16, enable_hdr=False) exr_path = self._get_exr_path(image_folder_name, "LdrColor") await wait_for_image_writing(exr_path) await self._test_render_product_capture(image_folder_name, default_rp_name, 16) await self._verify_file_exist(image_folder_name, "LdrColor") for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() async def test_capture_2_user_created_rp(self): await self._test_render_product_capture(self._capture_folder_1spp, "/Render/RenderView", 1) for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() await self._verify_file_exist(self._capture_folder_1spp, "LdrColor") await self._verify_file_exist(self._capture_folder_1spp, "HdrColor") await self._verify_file_exist(self._capture_folder_1spp, "PtGlobalIllumination") await self._verify_file_exist(self._capture_folder_1spp, "PtReflections") await self._verify_file_exist(self._capture_folder_1spp, "PtWorldNormal") # the render product capture process will write the image file multiple times during the capture # so give it more cycles to settle down to check file size for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 20): await omni.kit.app.get_app().next_update_async() async def test_capture_3_rp_accumulation(self): await self._test_render_product_capture(self._capture_folder_32spp, "/Render/RenderView", 32) for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() await self._verify_file_exist(self._capture_folder_32spp, "LdrColor") # the render product capture process will write the image file multiple times during the capture # so give it more cycles to settle down to check file size for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 20): await omni.kit.app.get_app().next_update_async() # compare result of test_capture_2_user_created_rp images to check accumulation works or not # if it works, more spp will result in smaller file size file_size_1spp = self._get_captured_image_size(self._capture_folder_1spp, "LdrColor") file_size_32spp = self._get_captured_image_size(self._capture_folder_32spp, "LdrColor") carb.log_warn(f"File size of 1spp capture is {file_size_1spp} bytes, and file size of 64spp capture is {file_size_32spp}") expected_result = file_size_32spp != file_size_1spp assert expected_result async def test_capture_4_rp_sequence(self): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(self._capture_folder_sequence, "Capture_frames") clean_files_in_directory(image_folder, ".exr") await self._test_render_product_capture(self._capture_folder_sequence, "/Render/RenderView", 1, True, True, 0, 10) start_frame_exr_path_1 = os.path.join(str(image_folder), "Capture.0000_" + "LdrColor" + ".exr") start_frame_exr_path_2 = os.path.join(str(image_folder), "Capture.0000_" + "PtGlobalIllumination" + ".exr") end_frame_exr_path_1 = os.path.join(str(image_folder), "Capture.0010_" + "LdrColor" + ".exr") end_frame_exr_path_2 = os.path.join(str(image_folder), "Capture.0010_" + "PtGlobalIllumination" + ".exr") await wait_for_image_writing(end_frame_exr_path_2, 50) assert os.path.isfile(start_frame_exr_path_1) assert os.path.isfile(start_frame_exr_path_2) assert os.path.isfile(end_frame_exr_path_1) assert os.path.isfile(end_frame_exr_path_2)
8,586
Python
49.511764
159
0.669811
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_png.py
from typing import Type import os import os.path import omni.kit.test import carb import carb.settings import carb.tokens import pathlib import gc from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport, create_viewport_window, capture_viewport_to_file from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") class TestCapturePng(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' settings = carb.settings.get_settings() self._frames_wait_for_capture_resource_ready = 6 await omni.usd.get_context(self._usd_context).new_stage_async() async def test_png_capture(self): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_png_test" filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".png" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".png") exr_path = os.path.join(options._output_folder, "Capture1.png") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = False options.camera = viewport_api.camera_path.pathString capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path)
2,027
Python
37.26415
107
0.702023
omniverse-code/kit/exts/omni.kit.window.imguidebug/PACKAGE-LICENSES/omni.kit.window.imguidebug-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.imguidebug/config/extension.toml
[package] title = "ImguiDebugWindows" description = "Extension to enable low-level debug windows" authors = ["NVIDIA"] version = "1.0.0" changelog="docs/CHANGELOG.md" readme = "docs/README.md" repository = "" [dependencies] "omni.ui" = {} [[native.plugin]] path = "bin/*.plugin" recursive = false [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/rtx-transient/debugwindows/enable=true", "--/rtx-transient/debugwindows/TestWindow=true", "--/rtx-transient/debugwindows/test=true" ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.ui_test", ]
617
TOML
20.310344
59
0.685575
omniverse-code/kit/exts/omni.kit.window.imguidebug/docs/CHANGELOG.md
# Changelog ## [1.0.0] - 2022-05-04 ### Added - Initial implementation.
73
Markdown
11.333331
25
0.630137
omniverse-code/kit/exts/omni.kit.window.imguidebug/docs/README.md
# omni.kit.debug.windows ## Introduction Enables low-level Imgui debug windows
82
Markdown
10.857141
37
0.768293
omniverse-code/kit/exts/omni.kit.window.imguidebug/docs/index.rst
omni.kit.debug.windows module ################################## .. toctree:: :maxdepth: 1 CHANGELOG
109
reStructuredText
12.749998
34
0.458716
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/OmniSkelSchema/__init__.py
# #==== # Copyright (c) 2018, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _omniSkelSchema from pxr import Tf Tf.PrepareModule(_omniSkelSchema, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,669
Python
28.298245
100
0.708209
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/OmniSkelSchema/_omniSkelSchema.pyi
from __future__ import annotations import pxr.OmniSkelSchema._omniSkelSchema import typing import Boost.Python import pxr.Usd import pxr.UsdGeom __all__ = [ "OmniJoint", "OmniJointBoxShapeAPI", "OmniJointCapsuleShapeAPI", "OmniJointLimitsAPI", "OmniJointShapeAPI", "OmniJointSphereShapeAPI", "OmniSkelBaseAPI", "OmniSkelBaseType", "OmniSkeletonAPI" ] class OmniJoint(pxr.UsdGeom.Xform, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateBindRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateBindScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateBindTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTagAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetBindRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetBindScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetBindTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTagAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSkeletonAndJointToken(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniJointBoxShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSize(*args, **kwargs) -> None: ... @staticmethod def SetSize(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointCapsuleShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetHeight(*args, **kwargs) -> None: ... @staticmethod def GetRadius(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def SetHeight(*args, **kwargs) -> None: ... @staticmethod def SetRadius(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointLimitsAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateEnabledAttr(*args, **kwargs) -> None: ... @staticmethod def CreateOffsetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingHorizontalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingVerticalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistMaximumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistMinimumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetEnabledAttr(*args, **kwargs) -> None: ... @staticmethod def GetLocalTransform(*args, **kwargs) -> None: ... @staticmethod def GetOffsetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSwingHorizontalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetSwingVerticalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistMaximumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistMinimumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpOrderAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpRotateXYZAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpTranslateAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetLocalTransform(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetXformOpOrderAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpRotateXYZAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpTranslateAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointSphereShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetRadius(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def SetRadius(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniSkelBaseAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniSkelBaseType(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniSkeletonAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def CreateUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'omniSkelSchema'
8,960
unknown
34.418972
139
0.635826
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchemaTools/_animationSchemaTools.pyi
from __future__ import annotations import pxr.AnimationSchemaTools._animationSchemaTools import typing import Boost.Python __all__ = [ "AddAnimation", "AddCurve", "AddCurves", "AddKey", "AddKeys", "ComputeTangent", "CopyKey", "DeleteAnimation", "DeleteCurves", "DeleteInfinityType", "DeleteKey", "GetAllKeys", "GetCurves", "GetKey", "GetKeys", "GetTangentControlStrategy", "HasAnimation", "HasCurve", "HasInfinityType", "HasKey", "Key", "MoveKey", "RaiseTimeSamplesToEditTarget", "SetInfinityType", "SetKey", "SwitchEditTargetForSessionLayer", "TangentControlStrategy", "testSkelRoot", "verifySkelAnimation" ] class Key(Boost.Python.instance): @staticmethod def GetRelativeInTangentX(*args, **kwargs) -> None: ... @staticmethod def GetRelativeOutTangentX(*args, **kwargs) -> None: ... @property def broken(self) -> None: """ :type: None """ @property def inRawTangent(self) -> None: """ :type: None """ @property def inTangentType(self) -> None: """ :type: None """ @property def outRawTangent(self) -> None: """ :type: None """ @property def outTangentType(self) -> None: """ :type: None """ @property def time(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ @property def weighted(self) -> None: """ :type: None """ __instance_size__ = 88 __safe_for_unpickling__ = True pass class TangentControlStrategy(Boost.Python.instance): @staticmethod def ValidateInControl(*args, **kwargs) -> None: ... @staticmethod def ValidateOutControl(*args, **kwargs) -> None: ... __instance_size__ = 32 pass def AddAnimation(*args, **kwargs) -> None: pass def AddCurve(*args, **kwargs) -> None: pass def AddCurves(*args, **kwargs) -> None: pass def AddKey(*args, **kwargs) -> None: pass def AddKeys(*args, **kwargs) -> None: pass def ComputeTangent(*args, **kwargs) -> None: pass def CopyKey(*args, **kwargs) -> None: pass def DeleteAnimation(*args, **kwargs) -> None: pass def DeleteCurves(*args, **kwargs) -> None: pass def DeleteInfinityType(*args, **kwargs) -> None: pass def DeleteKey(*args, **kwargs) -> None: pass def GetAllKeys(*args, **kwargs) -> None: pass def GetCurves(*args, **kwargs) -> None: pass def GetKey(*args, **kwargs) -> None: pass def GetKeys(*args, **kwargs) -> None: pass def GetTangentControlStrategy(*args, **kwargs) -> None: pass def HasAnimation(*args, **kwargs) -> None: pass def HasCurve(*args, **kwargs) -> None: pass def HasInfinityType(*args, **kwargs) -> None: pass def HasKey(*args, **kwargs) -> None: pass def MoveKey(*args, **kwargs) -> None: pass def RaiseTimeSamplesToEditTarget(*args, **kwargs) -> None: pass def SetInfinityType(*args, **kwargs) -> None: pass def SetKey(*args, **kwargs) -> None: pass def SwitchEditTargetForSessionLayer(*args, **kwargs) -> None: pass def testSkelRoot(*args, **kwargs) -> None: pass def verifySkelAnimation(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'animationSchemaTools'
3,422
unknown
21.973154
61
0.590006
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchemaTools/__init__.py
# #==== # Copyright (c) 2021, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _animationSchemaTools from pxr import Tf Tf.PrepareModule(_animationSchemaTools, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,681
Python
28.508771
100
0.710291
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchema/__init__.py
# #==== # Copyright (c) 2018, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _animationSchema from pxr import Tf Tf.PrepareModule(_animationSchema, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,671
Python
28.333333
100
0.708558
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchema/_animationSchema.pyi
from __future__ import annotations import pxr.AnimationSchema._animationSchema import typing import Boost.Python import pxr.AnimationSchema import pxr.Usd import pxr.UsdGeom __all__ = [ "AnimationCurveAPI", "AnimationData", "AnimationDataAPI", "GetTangentControlStrategy", "Infinity", "Key", "SkelAnimationAnnotation", "SkelJoint", "Tangent", "TangentControlStrategy", "Tokens" ] class AnimationCurveAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def DeleteCurve(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetCurves(*args, **kwargs) -> None: ... @staticmethod def GetDefaultTangentType(*args, **kwargs) -> None: ... @staticmethod def GetInfinityType(*args, **kwargs) -> None: ... @staticmethod def GetKeys(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetTicksPerSecond(*args, **kwargs) -> None: ... @staticmethod def SetDefaultTangentType(*args, **kwargs) -> None: ... @staticmethod def SetInfinityType(*args, **kwargs) -> None: ... @staticmethod def SetKeys(*args, **kwargs) -> None: ... @staticmethod def ValidateKeys(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class AnimationData(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class AnimationDataAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateAnimationDataBindingRel(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetAnimationDataBindingRel(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class Infinity(Boost.Python.enum, int): Post = pxr.AnimationSchema.Infinity.Post Pre = pxr.AnimationSchema.Infinity.Pre __slots__ = () names = {'Pre': pxr.AnimationSchema.Infinity.Pre, 'Post': pxr.AnimationSchema.Infinity.Post} values = {0: pxr.AnimationSchema.Infinity.Pre, 1: pxr.AnimationSchema.Infinity.Post} pass class Key(Boost.Python.instance): @property def inTangent(self) -> None: """ :type: None """ @property def outTangent(self) -> None: """ :type: None """ @property def tangentBroken(self) -> None: """ :type: None """ @property def tangentWeighted(self) -> None: """ :type: None """ @property def time(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ __instance_size__ = 88 pass class SkelAnimationAnnotation(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateEndAttr(*args, **kwargs) -> None: ... @staticmethod def CreateStartAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTagAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetEndAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetStartAttr(*args, **kwargs) -> None: ... @staticmethod def GetTagAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class SkelJoint(pxr.UsdGeom.Boundable, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateHideAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetHideAttr(*args, **kwargs) -> None: ... @staticmethod def GetJoint(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class Tangent(Boost.Python.instance): @property def time(self) -> None: """ :type: None """ @property def type(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ __instance_size__ = 40 pass class TangentControlStrategy(Boost.Python.instance): @staticmethod def ValidateInControl(*args, **kwargs) -> None: ... @staticmethod def ValidateOutControl(*args, **kwargs) -> None: ... __instance_size__ = 32 pass class Tokens(Boost.Python.instance): animationDataBinding = 'animationData:binding' auto_ = 'auto' constant = 'constant' cycle = 'cycle' cycleRelative = 'cycleRelative' defaultTangentType = 'defaultTangentType' end = 'end' fixed = 'fixed' flat = 'flat' hide = 'hide' inTangentTimes = 'inTangentTimes' inTangentTypes = 'inTangentTypes' inTangentValues = 'inTangentValues' linear = 'linear' oscillate = 'oscillate' outTangentTimes = 'outTangentTimes' outTangentTypes = 'outTangentTypes' outTangentValues = 'outTangentValues' postInfinityType = 'postInfinityType' preInfinityType = 'preInfinityType' smooth = 'smooth' start = 'start' step = 'step' tag = 'tag' tangentBrokens = 'tangentBrokens' tangentWeighteds = 'tangentWeighteds' times = 'times' values = 'values' pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass def GetTangentControlStrategy(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'animationSchema'
6,668
unknown
28.378855
143
0.612028
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchema/_retargetingSchema.pyi
from __future__ import annotations import pxr.RetargetingSchema._retargetingSchema import typing import Boost.Python import pxr.Usd __all__ = [ "AnimationSkelBindingAPI", "ControlRigAPI", "JointConstraint" ] class AnimationSkelBindingAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def BakeRetargetedSkelAnimation(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def ComputeRetargetedJointLocalTransforms(*args, **kwargs) -> None: ... @staticmethod def CreateSourceSkeletonRel(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSourceSkeleton(*args, **kwargs) -> None: ... @staticmethod def GetSourceSkeletonRel(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class ControlRigAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def CreateIKTargetsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateJointConstraintsRel(*args, **kwargs) -> None: ... @staticmethod def CreateJointTagsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTagsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTransformsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTypeAttr(*args, **kwargs) -> None: ... @staticmethod def CreateUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def GetIKTargetsAttr(*args, **kwargs) -> None: ... @staticmethod def GetJointConstraintsRel(*args, **kwargs) -> None: ... @staticmethod def GetJointTagsAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTagsAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTransformsAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetTypeAttr(*args, **kwargs) -> None: ... @staticmethod def GetUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class JointConstraint(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateFrameAttr(*args, **kwargs) -> None: ... @staticmethod def CreateJointAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetFrameAttr(*args, **kwargs) -> None: ... @staticmethod def GetJointAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSwingAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'retargetingSchema'
3,957
unknown
32.542373
96
0.632044
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchema/__init__.py
# #==== # Copyright (c) 2018, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _retargetingSchema from pxr import Tf Tf.PrepareModule(_retargetingSchema, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,675
Python
28.403508
100
0.709254
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchemaTools/__init__.py
# #==== # Copyright (c) 2021, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _retargetingSchemaTools from pxr import Tf Tf.PrepareModule(_retargetingSchemaTools, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,685
Python
28.578947
100
0.710979
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchemaTools/_retargetingSchemaTools.pyi
from __future__ import annotations import pxr.RetargetingSchemaTools._retargetingSchemaTools import typing __all__ = [ "testSkelRoot", "verifySkelAnimation" ] def testSkelRoot(*args, **kwargs) -> None: pass def verifySkelAnimation(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'retargetingSchemaTools'
332
unknown
19.812499
57
0.71988
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/__init__.py
from .scripts.extension import *
33
Python
15.999992
32
0.787879
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/scripts/extension.py
import omni.ext from .settings import OmniHydraSettings class PublicExtension(omni.ext.IExt): def on_startup(self): self._settings = OmniHydraSettings() def on_shutdown(self): self._settings = None
225
Python
19.545453
44
0.697778
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/scripts/settings.py
import asyncio import omni.ui import omni.kit.app import omni.kit.commands import carb.settings ### Copied from omni.phyx; Kit team will coalesce into omni.ui.settings module class Model(omni.ui.AbstractValueModel): def __init__(self, path): super().__init__() self._path = path val = carb.settings.get_settings().get(path) if val is None: val = 0 self._value = val def on_change(item, event_type, path=path): self._value = carb.settings.get_settings().get(path) self._value_changed() self._sub = omni.kit.app.SettingChangeSubscription(path, on_change) def get_value_as_bool(self): return self._value def get_value_as_int(self): return self._value def get_value_as_float(self): return self._value def get_value_as_string(self): return self._value def set_value(self, value): omni.kit.commands.execute("ChangeSetting", path=self._path, value=value) self._value = value self._value_changed() def create_setting_widget(setting_path, cls, **kwargs): model = Model(setting_path) widget = cls(model, **kwargs) return (model, widget) ### end omni.physx boilerplate class OmniHydraSettings(omni.ui.Window): def __init__(self): self._title = "OmniHydra Developer Settings" super().__init__(self._title, omni.ui.DockPreference.LEFT_BOTTOM, width=800, height=600) self._widgets = [] with self.frame: self._build_ui() asyncio.ensure_future(self._dock_window(self._title, omni.ui.DockPosition.SAME)) async def _dock_window(self, window_title: str, position: omni.ui.DockPosition, ratio: float = 1.0): frames = 3 while frames > 0: if omni.ui.Workspace.get_window(window_title): break frames = frames - 1 await omni.kit.app.get_app().next_update_async() window = omni.ui.Workspace.get_window(window_title) dockspace = omni.ui.Workspace.get_window("Property") if window and dockspace: window.dock_in(dockspace, position, ratio=ratio) window.dock_tab_bar_visible = False def on_shutdown(self): self._widgets = [] def _add_setting_widget(self, name, path, cls, **kwargs): with omni.ui.VStack(): omni.ui.Spacer(height=2) with omni.ui.HStack(height=20): self._widgets.append(create_setting_widget(path, cls, **kwargs)) omni.ui.Label(name) def _build_settings_ui(self): self._add_setting_widget("Use fast scene delegate", "/persistent/omnihydra/useFastSceneDelegate", omni.ui.CheckBox) self._add_setting_widget("Use scene graph instancing", "/persistent/omnihydra/useSceneGraphInstancing", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter", "/persistent/omnihydra/useSkelAdapter", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter blendshape", "/persistent/omnihydra/useSkelAdapterBlendShape", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter deform graph", "/persistent/omnihydra/useSkelAdapterDeformGraph", omni.ui.CheckBox) self._add_setting_widget("Use cached xform time samples", "/persistent/omnihydra/useCachedXformTimeSamples", omni.ui.CheckBox) self._add_setting_widget("Use async RenderGraph in _PullFromRingBuffer", "/persistent/omnihydra/useAsyncRenderGraph", omni.ui.CheckBox) self._add_setting_widget("Use fast xform path from Fabric to renderer", "/persistent/rtx/hydra/readTransformsFromFabricInRenderDelegate", omni.ui.CheckBox) def _build_usdrt_settings_ui(self): self._add_setting_widget("Use Fabric World Bounds", "/app/omni.usd/useFabricWorldBounds", omni.ui.CheckBox) self._add_setting_widget("Use camera-based priority sorting", "/app/usdrt/scene_delegate/useWorldInterestBasedSorting", omni.ui.CheckBox) self._add_setting_widget("GPU Memory Budget %", "/app/usdrt/scene_delegate/gpuMemoryBudgetPercent", omni.ui.FloatSlider, min=0., max=100.) with omni.ui.CollapsableFrame("Geometry Streaming"): with omni.ui.VStack(): self._add_setting_widget("Enable geometry streaming", "/app/usdrt/scene_delegate/geometryStreaming/enabled", omni.ui.CheckBox) self._add_setting_widget("Enable proxy cubes for unloaded prims", "/app/usdrt/scene_delegate/enableProxyCubes", omni.ui.CheckBox) self._add_setting_widget("Solid Angle Loading To Load in first batch", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleToLoadInFirstChunk", omni.ui.FloatSlider, min=0, max=1, step=0.0001) self._add_setting_widget("Solid Angle Loading Limit", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimit", omni.ui.FloatSlider, min=0, max=1, step=0.0001) self._add_setting_widget("Solid Angle Loading Limit Divider", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimitDivider", omni.ui.FloatSlider, min=1, max=10000, step=100) self._add_setting_widget("Number of frames between batches", "/app/usdrt/scene_delegate/numFramesBetweenLoadBatches", omni.ui.IntSlider, min=1, max=50) self._add_setting_widget("Number of vertices to load per batch", "/app/usdrt/scene_delegate/geometryStreaming/numberOfVerticesToLoadPerChunk", omni.ui.IntSlider, min=1, max=5000000) self._add_setting_widget("Number of vertices to unload per batch", "/app/usdrt/scene_delegate/geometryStreaming/numberOfVerticesToUnloadPerChunk", omni.ui.IntSlider, min=1, max=5000000) self._add_setting_widget("Number of cubes proxy instances per instancer", "/app/usdrt/scene_delegate/proxyInstanceBucketSize", omni.ui.IntSlider, min=0, max=200000) with omni.ui.CollapsableFrame("Memory Budget Experimental Stability Values"): with omni.ui.VStack(): self._add_setting_widget("Update Delay in microseconds", "/app/usdrt/scene_delegate/updateDelayInMicroSeconds", omni.ui.IntSlider, min=0, max=1000000) self._add_setting_widget("GPU Memory Deadzone %", "/app/usdrt/scene_delegate/gpuMemoryBudgetDeadZone", omni.ui.FloatSlider, min=0., max=50.) self._add_setting_widget("GPU Memory Filter Damping", "/app/usdrt/scene_delegate/gpuMemoryFilterDamping", omni.ui.FloatSlider, min=0., max=2.) with omni.ui.CollapsableFrame("Memory Limit Testing (pretend values)"): with omni.ui.VStack(): self._add_setting_widget("Enable memory testing", "/app/usdrt/scene_delegate/testing/enableMemoryTesting", omni.ui.CheckBox) self._add_setting_widget("GPU Memory Available", "/app/usdrt/scene_delegate/testing/availableDeviceMemory", omni.ui.FloatSlider, min=0., max=float(1024*1024*1024*8)) self._add_setting_widget("GPU Memory Total", "/app/usdrt/scene_delegate/testing/totalDeviceMemory", omni.ui.FloatSlider, min=0., max=float(1024*1024*1024*8)) with omni.ui.CollapsableFrame("USD Population (reload scene to see effect)"): with omni.ui.VStack(): self._add_setting_widget("Read Curves", "/app/usdrt/population/utils/readCurves", omni.ui.CheckBox) self._add_setting_widget("Read Materials", "/app/usdrt/population/utils/readMaterials", omni.ui.CheckBox) self._add_setting_widget("Read Lights", "/app/usdrt/population/utils/readLights", omni.ui.CheckBox) self._add_setting_widget("Read Primvars", "/app/usdrt/population/utils/readPrimvars", omni.ui.CheckBox) self._add_setting_widget("Enable Subcomponent merging", "/app/usdrt/population/utils/mergeSubcomponents", omni.ui.CheckBox) self._add_setting_widget("Enable Instance merging", "/app/usdrt/population/utils/mergeInstances", omni.ui.CheckBox) self._add_setting_widget("Enable Material merging", "/app/usdrt/population/utils/mergeMaterials", omni.ui.CheckBox) self._add_setting_widget("Single-threaded population", "/app/usdrt/population/utils/singleThreaded", omni.ui.CheckBox) self._add_setting_widget("Disable Light Scaling (non-RTX delegates)", "/app/usdrt/scene_delegate/disableLightScaling", omni.ui.CheckBox) self._add_setting_widget("Use Fabric Scene Graph Instancing", "/app/usdrt/population/utils/handleSceneGraphInstances", omni.ui.CheckBox) self._add_setting_widget("Use Hydra BlendShape", "/app/usdrt/scene_delegate/useHydraBlendShape", omni.ui.CheckBox) self._add_setting_widget("Number of IO threads", "/app/usdrt/population/utils/ioBoundThreadCount", omni.ui.IntSlider, min=1, max=16) def _build_section(self, name, build_func): with omni.ui.CollapsableFrame(name, height=0): with omni.ui.HStack(): omni.ui.Spacer(width=20, height=5) with omni.ui.VStack(): build_func() def _build_ui(self): with omni.ui.ScrollingFrame(horizontal_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED): with omni.ui.VStack(): self._build_section("Settings (requires stage reload)", self._build_settings_ui) self._build_section("USDRT Hydra Settings", self._build_usdrt_settings_ui)
9,531
Python
63.405405
210
0.676634