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.viewport_widgets_manager/omni/kit/viewport_widgets_manager/manager.py
import asyncio import carb import weakref import omni.usd import omni.timeline import omni.ui as ui import omni.kit.app as app from omni.kit.viewport.utility import ( get_active_viewport_window, get_ui_position_for_prim, ViewportPrimReferencePoint ) from typing import List from pxr import Tf, Usd, Sdf, UsdGeom, Trace from .widget_provider import WidgetProvider class WidgetAlignment: CENTER = 0 BOTTOM = 1 TOP = 2 class WidgetWrapper: def __init__( self, usd_context, viewport_window, viewport_canvas, prim_path: Sdf.Path, widget_provider: WidgetProvider, alignment=WidgetAlignment.CENTER ): self._prim_path = prim_path self._widget_provider = widget_provider self._window = viewport_window self._canvas = viewport_canvas self._viewport_placer = None self._alignment = alignment self._layout = None self._anchoring = True self._usd_context = usd_context self._timeline = omni.timeline.get_timeline_interface() @property def alignment(self): return self._alignment @property def prim_path(self) -> Sdf.Path: return self._prim_path @property def visible(self): return self._viewport_placer and self._viewport_placer.visible @visible.setter def visible(self, value): if self._viewport_placer: self._viewport_placer.visible = value def clear(self): self._anchoring = False if self._layout: self._layout.clear() self._layout.destroy() self._layout = None if self._viewport_placer: self._viewport_placer.clear() self._viewport_placer.destroy() self._viewport_placer = None @Trace.TraceFunction def update_widget_position(self, cached_position=None): viewport_window = self._window if not viewport_window: return False alignment = { WidgetAlignment.TOP: ViewportPrimReferencePoint.BOUND_BOX_TOP, WidgetAlignment.BOTTOM: ViewportPrimReferencePoint.BOUND_BOX_BOTTOM }.get(self._alignment, ViewportPrimReferencePoint.BOUND_BOX_CENTER) if cached_position: ui_pos, in_viewport = cached_position else: ui_pos, in_viewport = get_ui_position_for_prim(viewport_window, str(self.prim_path), alignment=alignment) if not in_viewport: return False dpi = ui.Workspace.get_dpi_scale() dpi = dpi if (dpi > 0) else 1.0 prim_window_pos_x, prim_window_pos_y = ui_pos self._viewport_placer.offset_x = prim_window_pos_x / dpi - self._window.position_x self._viewport_placer.offset_y = prim_window_pos_y / dpi - self._window.position_y computed_width = self._layout.computed_width comuted_height = self._layout.computed_height offset_x = -float(computed_width) * 0.5 offset_y = -float(comuted_height) * 0.5 self._viewport_placer.offset_x += offset_x self._viewport_placer.offset_y += offset_y return True def create_or_update_widget(self, cached_position=None): viewport_window = self._window if (viewport_window is None) or (not viewport_window.visible): self.clear() return stage = viewport_window.viewport_api.stage if not stage: self.clear() return prim = stage.GetPrimAtPath(self.prim_path) if not prim: self.clear() return # If prim is hidden, clearing the widget. if ( not self._is_prim_visible(stage, prim) or not self._is_camera_mesh_visible(stage, prim) ): self.clear() return if not self._viewport_placer: self._anchoring = True with self._canvas: self._viewport_placer = ui.Placer() with self._viewport_placer: self._layout = ui.HStack(width=0, height=0) with self._layout: self._widget_provider.build_widget(viewport_window) elif not self.update_widget_position(cached_position): self.clear() def _is_prim_visible(self, stage, prim): imageable = UsdGeom.Imageable(prim) if not imageable: return False visibility_attr = imageable.GetVisibilityAttr() time_sampled = visibility_attr.GetNumTimeSamples() > 1 curr_time = self._timeline.get_current_time() if time_sampled: curr_time_code = curr_time * stage.GetTimeCodesPerSecond() else: curr_time_code = Usd.TimeCode.Default() visibility = imageable.ComputeVisibility(curr_time_code) return visibility != UsdGeom.Tokens.invisible def _is_camera_mesh_visible(self, stage, prim): # Only handle camera prim, as camera prim except builtin ones will # include a mesh. if not prim.IsA(UsdGeom.Camera): return True display_predicate = Usd.TraverseInstanceProxies(Usd.PrimAllPrimsPredicate) for prim in Usd.PrimRange(prim, display_predicate): if prim.IsA(UsdGeom.Mesh): return self._is_prim_visible(stage, prim) return False def try_anchoring(self): if not self._window or not self._anchoring: return computed_width = self._layout.computed_width comuted_height = self._layout.computed_height if computed_width == 0 or comuted_height == 0: return False self._anchoring = False self.update_widget_position() class ViewportWidgetsManager: def __init__(self, usd_context_name=""): self._stage_event_subscription = None self._update_subscription = None self._last_active_camera_path = None self._stage_changed_subscription = None self._all_widgets: List[WidgetWrapper] = [] self._usd_context = omni.usd.get_context(usd_context_name) self._pending_update_all = False self._pending_update_prim_paths = set([]) self._viewport_frame = None self._viewport_window = None self._frame_canvas = None self._current_wait_frames = 0 self._all_widgets_hidden = False def _initialize(self): self._viewport_window = get_active_viewport_window(window_name="Viewport") self._viewport_frame = self._viewport_window.get_frame(f"omni.kit.viewport_widgets_manager") self._viewport_frame.set_computed_content_size_changed_fn(self._update_all_widgets) # Stores position and size for comparing. if self._viewport_window: self._last_active_camera_path = self._viewport_window.viewport_api.camera_path with self._viewport_frame: self._frame_canvas = ui.ZStack() else: self._last_active_camera_path = None def _reset(self): if self._viewport_frame: self._viewport_frame.set_computed_content_size_changed_fn(None) self._viewport_frame.clear() self._viewport_frame = None self._frame_canvas.clear() self._frame_canvas = None self._viewport_window = None self._last_active_camera_path = None for widget in self._all_widgets: widget.clear() self._all_widgets.clear() def start(self): self._initialize() events = self._usd_context.get_stage_event_stream() self._stage_event_subscription = events.create_subscription_to_pop( self._on_stage_event, name="Viewport Widgets Manager Watch" ) self._start_update_subscription() def stop(self): self._stage_event_subscription = None self._stop_update_subscrioption() self._reset() @Trace.TraceFunction def _on_objects_changed(self, notice, stage): if stage != self._usd_context.get_stage(): return for path in notice.GetResyncedPaths(): if path == Sdf.Path.absoluteRootPath: self._pending_update_all = True self._current_wait_frames = 0 # TRICK: Hides all widgets to delay the refresh # to avoid let user be aware of the delay. self._hide_all_widgets() else: self._pending_update_prim_paths.add(path) for path in notice.GetChangedInfoOnlyPaths(): prim_path = path.GetPrimPath() # self._last_active_camera_path may be None, so make sure an # implicit Sdf.Path isn't constructed for equality comparison if ( prim_path == Sdf.Path.absoluteRootPath or ( self._last_active_camera_path and prim_path == self._last_active_camera_path ) ): self._pending_update_all = True self._current_wait_frames = 0 self._hide_all_widgets() else: self._pending_update_prim_paths.add(prim_path) def _handle_pending_updates(self): if self._pending_update_all: self._update_all_widgets() elif self._pending_update_prim_paths: update_widgets = [] for prim_path in self._pending_update_prim_paths: for widget in self._all_widgets: if prim_path.HasPrefix(widget.prim_path): update_widgets.append(widget) self._update_all_widgets_internal(update_widgets) self._pending_update_all = False self._pending_update_prim_paths.clear() def _update_all_widgets_internal(self, widgets: List[WidgetWrapper]): # TODO: How to speed up this to batch the ui pos calculation. def get_ui_position(widget: WidgetWrapper): alignment = { WidgetAlignment.TOP: ViewportPrimReferencePoint.BOUND_BOX_TOP, WidgetAlignment.BOTTOM: ViewportPrimReferencePoint.BOUND_BOX_BOTTOM }.get(widget.alignment, ViewportPrimReferencePoint.BOUND_BOX_CENTER) return get_ui_position_for_prim( self._viewport_window, str(widget.prim_path), alignment=alignment ) for widget in widgets: ui_pos = get_ui_position(widget) widget.create_or_update_widget(ui_pos) def _update_all_widgets(self): update_widgets = [] for widget in self._all_widgets: # Don't draw widget for current active camera path. if not self._last_active_camera_path or widget.prim_path != self._last_active_camera_path: update_widgets.append(widget) else: widget.clear() self._update_all_widgets_internal(update_widgets) def _trying_anchoring_all_widgets(self): for widget in self._all_widgets: widget.try_anchoring() def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.OPENED): self._start_update_subscription() elif event.type == int(omni.usd.StageEventType.CLOSED): self._stop_update_subscrioption() def _stop_update_subscrioption(self): self._update_subscription = None self._last_active_camera_path = None for widget in self._all_widgets: widget.clear() self._all_widgets.clear() if self._stage_changed_subscription: self._stage_changed_subscription.Revoke() self._stage_changed_subscription = None def _start_update_subscription(self): self._update_subscription = app.get_app().get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.kit.viewport_widgets_manager update" ) self._stage_changed_subscription = Tf.Notice.Register( Usd.Notice.ObjectsChanged, self._on_objects_changed, self._usd_context.get_stage() ) def _hide_all_widgets(self): for widget in self._all_widgets: widget.visible = False self._all_widgets_hidden = True def _show_all_widgets(self): if not self._all_widgets_hidden: return self._all_widgets_hidden = False for widget in self._all_widgets: widget.visible = True def _on_update(self, dt): # Puts some delay to avoid refreshing prims frequently self._current_wait_frames += 1 if self._current_wait_frames <= 3: return else: self._current_wait_frames = 0 self._show_all_widgets() viewport_window = get_active_viewport_window() if not viewport_window and self._viewport_window: self._reset() return elif viewport_window and not self._viewport_window: self._initialize() self._trying_anchoring_all_widgets() # Handle pending updates self._handle_pending_updates() # Checks changed camera active_camera_path = viewport_window.viewport_api.camera_path if (not active_camera_path) or (not self._last_active_camera_path) or (self._last_active_camera_path != active_camera_path): self._last_active_camera_path = active_camera_path self._update_all_widgets() def add_widget(self, prim_path: Sdf.Path, widget: WidgetProvider, alignment=WidgetAlignment.CENTER): usd_context = self._viewport_window.viewport_api.usd_context stage = usd_context.get_stage() usd_prim = stage.GetPrimAtPath(prim_path) if stage else False if usd_prim: xformable_prim = UsdGeom.Xformable(usd_prim) else: xformable_prim = None if not xformable_prim: carb.warn(f"Cannot add viewport widget for non-xformable prim.") return None carb.log_info(f"Adding prim widget for {prim_path}") widget_wrapper = WidgetWrapper( self._usd_context, self._viewport_window, self._frame_canvas, prim_path, widget, alignment ) self._all_widgets.append(widget_wrapper) if not self._last_active_camera_path or prim_path != self._last_active_camera_path: widget_wrapper.create_or_update_widget() return weakref.ref(widget_wrapper) def remove_widget(self, widget_id): if not widget_id: return try: local_wiget = widget_id() if widget_id and local_wiget: if local_wiget in self._all_widgets: local_wiget.clear() self._all_widgets.remove(local_wiget) except Exception: pass
15,018
Python
33.685912
132
0.596085
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/omni/kit/viewport_widgets_manager/tests/__init__.py
from .test_widgets_manager import TestWidgetsManagerUI
55
Python
26.999987
54
0.872727
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/omni/kit/viewport_widgets_manager/tests/test_widgets_manager.py
import asyncio import os import carb.settings import omni.usd import omni.kit.commands import omni.client import omni.kit.test import omni.ui as ui import omni.kit.viewport_widgets_manager as wm from omni.kit.viewport.utility.tests import setup_viewport_test_window from omni.kit.test.teamcity import is_running_in_teamcity import sys import unittest from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import Usd, UsdGeom, Gf CURRENT_PATH = Path(__file__).parent.joinpath("../../../../data") CAMERA_WIDGET_STYLING = { "Rectangle::background": {"background_color": 0x7F808080, "border_radius": 5} } class LabelWidget(wm.WidgetProvider): def __init__(self, text): self._text = text def build_widget(self, window): with ui.ZStack(width=0, height=0, style=CAMERA_WIDGET_STYLING): ui.Rectangle(name="background") with ui.VStack(width=0, height=0): ui.Spacer(height=4) with ui.HStack(width=0, height=0): ui.Spacer(width=4) ui.Label(self._text, width=0, height=0, name="user_name") ui.Spacer(width=4) ui.Spacer(height=4) class TestWidgetsManagerUI(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # viewport_next golden images are different vp_window_name = carb.settings.get_settings().get('/exts/omni.kit.viewport.window/startup/windowName') if not (vp_window_name and (vp_window_name == 'Viewport')): self._golden_img_dir = self._golden_img_dir.joinpath("viewport_1") self._all_widgets = [] await omni.usd.get_context().new_stage_async() await self.wait_frames() # After running each test async def tearDown(self): self._golden_img_dir = None for widget_id in self._all_widgets: wm.remove_widget(widget_id) await super().tearDown() async def wait_frames(self, n_frame: int = 10): app = omni.kit.app.get_app() while n_frame > 0: await app.next_update_async() n_frame = n_frame - 1 async def create_text_widget(self, text, alignment, width: int = 320, height: int = 240): try: from omni.kit.mainwindow import get_main_window get_main_window().get_main_menu_bar().visible = False except (ImportError, AttributeError): pass # Create test area await self.create_test_area(width, height) # Fill the area with the Viewport viewport_window = await setup_viewport_test_window(width, height) # Add scene objects usd_context = viewport_window.viewport_api.usd_context stage = usd_context.get_stage() prim_path = "/World/widget_prim" prim = UsdGeom.Xform.Define(stage, prim_path) await self.wait_frames() usd_context.get_selection().clear_selected_prim_paths() self._all_widgets.append(wm.add_widget(prim_path, LabelWidget(text), alignment)) # Sleep 1s to wait for drawing await asyncio.sleep(1.0) return prim @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_create_widget_top(self): await self.create_text_widget("Sphere", wm.WidgetAlignment.TOP) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_create_widget_top.png") @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_create_widget_bottom(self): await self.create_text_widget("Cone", wm.WidgetAlignment.BOTTOM) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_create_widget_bottom.png") @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_create_widget_center(self): await self.create_text_widget("Cube", wm.WidgetAlignment.CENTER) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_create_widget_center.png") @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_widget_translate(self): prim = await self.create_text_widget("Sphere", wm.WidgetAlignment.TOP) translation = Gf.Vec3d(-200, 0.0, 0.0) common_api = UsdGeom.XformCommonAPI(prim) common_api.SetTranslate(translation) await self.wait_frames() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_widget_translate.png") @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_widget_out_of_viewport(self): prim = await self.create_text_widget("Sphere", wm.WidgetAlignment.TOP) translation = Gf.Vec3d(-200000, 0.0, 0.0) common_api = UsdGeom.XformCommonAPI(prim) common_api.SetTranslate(translation) await self.wait_frames() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_widget_out_of_viewport.png")
5,263
Python
40.448819
120
0.6597
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/docs/CHANGELOG.md
# Changelog ## [1.0.6] - 2022-06-02 ### Changed - Remove usage of RTX for test in favor of Storm. - Update image threshold for differencce in title-bar when running with Viewport Next. ## [1.0.5] - 2022-05-23 ### Changed - Add dependency on omni.kit.viewport.utility ### Fixes - Fix widget positioning for Viewport Legacy and Next ## [1.0.4] - 2021-12-20 ### Fixes - Fix widget positioning issue if stage units are meters. - Fix empty Sdf.Path comparison issue. ## [1.0.3] - 2021-08-21 ### Fixes - Fix perf issue to query duplicate prim path, and add trace for usd notice. ## [1.0.0] - 2021-03-09 ### Changed - Initial extension.
638
Markdown
23.576922
86
0.689655
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/docs/README.md
# Viewport Widgets Mnager [omni.kit.viewport_widgets_manager] This extension provides simple interface to create/manager viewport widgets. It will help to maintain the viewport resize, and active camera movement.
213
Markdown
70.33331
150
0.826291
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/docs/index.rst
omni.kit.viewport_widgets_manager ################################# Viewport Widgets Manager .. toctree:: :maxdepth: 1 CHANGELOG Introduction ============ This extension provides simple interface to create/manager viewport widgets. It will help to maintain the viewport resize, and active camera movement. .. automodule:: omni.kit.viewport_widgets_manager :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: :imported-members:
493
reStructuredText
20.47826
150
0.673428
omniverse-code/kit/exts/omni.kit.window.title/PACKAGE-LICENSES/omni.kit.window.title-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.title/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.1.2" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "Title Bar" description="Extension to control title bar behavior." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Internal" # Keywords for the extension keywords = ["kit", "title"] # Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content # of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # We only depend on testing framework currently: [dependencies] "omni.appwindow" = {} "omni.usd" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.window.title" [settings] exts."omni.kit.window.title".pollIntervalMS = 500.0 [[test]] args = [ "--/exts/omni.kit.window.title/pollIntervalMS=0.0", ] dependencies = [ "omni.kit.stage_templates", ]
1,683
TOML
30.185185
118
0.73678
omniverse-code/kit/exts/omni.kit.window.title/omni/kit/window/title/title.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.events import carb.settings import carb.windowing import omni.appwindow import omni.ext import omni.kit.app import omni.usd import time import urllib.parse main_window_title = None def get_main_window_title(): return main_window_title class WindowTitle(omni.ext.IExt): def on_startup(self, ext_id): self._app_name = "" self._app_version = "" self._title = "" self._title_decor = "" self._full_title = "" self._listener = None self._app = omni.kit.app.get_app() # We don't have a way to acquire interface without throwing on missing implementation in Carbonite, # so for now we have to work this around with try/except block. try: self._windowing = carb.windowing.acquire_windowing_interface() except: self._windowing = None self._settings = carb.settings.get_settings() self._window = omni.appwindow.get_default_app_window().get_window() self._usd_context = omni.usd.get_context() self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="Window title bar" ) if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._update_title() # default value self._app_name = self._settings.get("/app/window/title") self._app_version = self._app.get_build_version() self._apply() # Default polling interval is 500ms (or 0.5s) self._settings.set_default("/exts/omni.kit.window.title/pollIntervalMS", 500.0) self._poll_interval_s = self._settings.get("/exts/omni.kit.window.title/pollIntervalMS") / 1000.0 global main_window_title main_window_title = self def on_shutdown(self): global main_window_title main_window_title = None self._stage_event_sub = None def set_app_name(self, name: str): """ Sets app name on title bar. This is the first element on the title bar string. Args: name: app name to be set to. """ if self._app_name != name: self._app_name = name self._apply() def set_app_version(self, version: str): """ Sets app version on title bar. This is the second element on the title bar string, after app name. Args: version: app version to be set to. """ if self._app_version != version: self._app_version = version self._apply() def set_title(self, title: str): """ Sets title text on title bar. This is the third element on the title bar string, after app name and version. Args: title: app title to be set to. """ # OM-64018: need to unquote the chars in the title string title = urllib.parse.unquote(title) if self._title != title: self._title = title self._apply() def set_title_decor(self, title_decor: str): """ Sets title decor on title bar. This is at the end of the title string. Args: title_decor: title decor to be set to. """ if self._title_decor != title_decor: self._title_decor = title_decor self._apply() def get_full_title(self): """ Gets the full title. """ return self._full_title def _apply(self): self._full_title = f"{self._app_name} {self._app_version}" if len(self._title) > 0: self._full_title += f" - {self._title}{self._title_decor}" if self._window is not None: self._windowing.set_window_title(self._window, self._full_title) def _on_stage_event(self, event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.OPENED): self._update_title() elif event.type == int(omni.usd.StageEventType.CLOSING): self._on_stage_closing() elif event.type == int(omni.usd.StageEventType.DIRTY_STATE_CHANGED): self._update_title() def set_title_url(self): title = "New Stage" if self._usd_context.is_new_stage() else self._usd_context.get_stage_url() if not self._usd_context.is_writable(): title += " (read-only)" self.set_title(title) def _on_stage_closing(self): self.set_title("") self.set_title_decor("") def _update_title(self): self.set_title_url() dirty = self._usd_context.has_pending_edit() if dirty and self._title_decor != "*": self.set_title_decor("*") elif not dirty and self._title_decor == "*": self.set_title_decor("")
5,213
Python
32.210191
116
0.603108
omniverse-code/kit/exts/omni.kit.window.title/omni/kit/window/title/__init__.py
from .title import *
21
Python
9.999995
20
0.714286
omniverse-code/kit/exts/omni.kit.window.title/omni/kit/window/title/tests/tests.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.test import os import stat import tempfile import carb.settings import omni.kit.app import omni.kit.commands import omni.kit.window.title import omni.usd class TestTitleBar(omni.kit.test.AsyncTestCase): async def test_title(self): import omni.kit.stage_templates title_bar = omni.kit.window.title.get_main_window_title() settings = carb.settings.get_settings() app = omni.kit.app.get_app() usd_context = omni.usd.get_context() ## Test new stage title await omni.kit.stage_templates.new_stage_async() # make sure new stage event is handled by title extension await app.next_update_async() # Ideally we should get title from OS Window, but GLFW does not have getter for window title. title = title_bar.get_full_title() app_name = settings.get("/app/window/title") app_version = app.get_build_version() new_stage_title = f"{app_name} {app_version} - New Stage" self.assertTrue(title == new_stage_title) ## Test set app name and version test_app_name = "title extension test" test_version = "1.0" title_bar.set_app_name(test_app_name) title_bar.set_app_version(test_version) title = title_bar.get_full_title() self.assertTrue(title == f"{test_app_name} {test_version} - New Stage") ## Restore app name and version title_bar.set_app_name(app_name) title_bar.set_app_version(app_version) ## Test open USD file with tempfile.TemporaryDirectory() as dir_name: tmp_file_path = os.path.join(dir_name, "tmp.usda") await usd_context.save_as_stage_async(tmp_file_path) # make sure new stage event is handled by title extension await app.next_update_async() title = title_bar.get_full_title() title = os.path.normpath(title) tmp_file_path = os.path.normpath(tmp_file_path) # Save As should not result in dirty mark (*) on the title self.assertEqual(title, f"{app_name} {app_version} - {tmp_file_path}") ## Make an edit stage = usd_context.get_stage() stage.DefinePrim("/test") # make sure new stage event is handled by title extension await app.next_update_async() await app.next_update_async() # check the dirty mark (*) title = title_bar.get_full_title() title = os.path.normpath(title) self.assertEqual(title, f"{app_name} {app_version} - {tmp_file_path}*") ## Save the stage await usd_context.save_stage_async() await app.next_update_async() # check the dirty mark (*) is removed title = title_bar.get_full_title() title = os.path.normpath(title) self.assertEqual(title, f"{app_name} {app_version} - {tmp_file_path}") ## Make read-only await usd_context.close_stage_async() mode = os.stat(tmp_file_path).st_mode os.chmod(tmp_file_path, stat.S_IREAD | stat.S_IRGRP | stat.S_IROTH) await usd_context.open_stage_async(tmp_file_path) await app.next_update_async() await app.next_update_async() title = title_bar.get_full_title() title = os.path.normpath(title) self.assertEqual(title, f"{app_name} {app_version} - {tmp_file_path} (read-only)") await usd_context.close_stage_async() # restore file permission so it can be cleaned up os.chmod(tmp_file_path, mode)
4,103
Python
36.651376
101
0.622959
omniverse-code/kit/exts/omni.kit.window.title/omni/kit/window/title/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .tests import *
449
Python
43.999996
76
0.804009
omniverse-code/kit/exts/omni.kit.window.title/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``omni.kit.window.title`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [1.1.2] - 2022-10-10 ### Added - Fix OM-64018: unquote the char (like %020 in title). ## [1.1.1] - 2021-12-28 ### Added - Using stage event to drive dirtiness update. ## [1.1.0] - 2021-02-26 ### Added - Added tests. ## [1.0.0] - 2020-10-22 ### Added - Initial window title extension
459
Markdown
16.692307
81
0.657952
omniverse-code/kit/exts/omni.kit.window.title/docs/README.md
# Python Extension Example [omni.example.hello] This is an example of pure python Kit extesnion. It is intended to be copied and serve as a template to create new ones.
171
Markdown
33.399993
120
0.777778
omniverse-code/kit/exts/omni.kit.window.title/docs/index.rst
omni.kit.window.title ########################### .. toctree:: :maxdepth: 1 CHANGELOG
96
reStructuredText
8.699999
27
0.447917
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/extension.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.ext import omni.client import carb.settings import pydantic from typing import List, Tuple, Optional from datetime import datetime from urllib import parse from carb import events, log_warn from collections import OrderedDict from omni.kit.helper.file_utils import asset_types from . import FILE_OPENED_EVENT, FILE_SAVED_EVENT, FILE_EVENT_QUEUE_UPDATED g_singleton = None class FileEventModel(pydantic.BaseModel): url: str asset_type: Optional[str] is_folder: Optional[bool] = False event_type: Optional[int] tag: Optional[str] datetime: Optional[datetime] class FileEventHistoryExtension(omni.ext.IExt): FILE_EVENT_QUEUE_SETTING = "/persistent/app/omniverse/fileEventHistory" def __init__(self, max_queue_size: int = 100): super().__init__() self._event_subs = [] self._event_queue = None self._max_queue_size = max_queue_size # set up singleton global g_singleton g_singleton = self def on_startup(self, ext_id: str): # Listen for file open and file save events import omni.kit.app event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._event_subs = [ event_stream.create_subscription_to_pop_by_type(FILE_OPENED_EVENT, self._on_file_event), event_stream.create_subscription_to_pop_by_type(FILE_SAVED_EVENT, self._on_file_event) ] @property def event_queue(self): if self._event_queue is None: self._event_queue = self._load_queue_from_settings() return self._event_queue def _load_queue_from_settings(self) -> OrderedDict: queue = OrderedDict() settings = carb.settings.get_settings() for uri in settings.get(self.FILE_EVENT_QUEUE_SETTING) or []: url, file_event = self._deserialize_uri(uri) if url and file_event: queue[url] = file_event queue.move_to_end(url, last=True) self._adjust_queue_size(queue) return queue def _save_queue_to_settings(self, queue: OrderedDict): uris = [] for url, file_event in queue.items(): uri = self._serialize_uri(file_event) if not uri in uris: uris.append(uri) settings = carb.settings.get_settings() if settings: settings.set_string_array(self.FILE_EVENT_QUEUE_SETTING, uris) def _serialize_uri(self, file_event: FileEventModel) -> str: url_parts = omni.client.break_url(file_event.url) params = { 'is_folder': file_event.is_folder, 'event_type': file_event.event_type, 'tag': file_event.tag or "" } uri = omni.client.make_url( scheme=url_parts.scheme or "file", host=url_parts.host, path=url_parts.path, query=parse.urlencode(params)) return uri def _deserialize_uri(self, uri: str) -> Tuple[str, FileEventModel]: url_parts = omni.client.break_url(uri) url = omni.client.make_url( scheme=url_parts.scheme, host=url_parts.host, path=url_parts.path ) file_event = None try: params = parse.parse_qs(url_parts.query, strict_parsing=False, keep_blank_values=False) file_event = FileEventModel( url=url, asset_type=asset_types.get_asset_type(url), is_folder=params.get('is_folder', ["False"])[0] == "True", event_type=int(params.get('event_type', ["0"])[0]), tag=params.get('tag', [None])[0], datetime=datetime.utcnow(), ) except pydantic.ValidationError as e: log_warn(f"Error parsing file event payload: {str(e)}") except Exception as e: log_warn(f"Failed to deserialize file event uri: {str(e)}") return url, file_event def _adjust_queue_size(self, queue: OrderedDict): while len(queue) > self._max_queue_size: # Delete items from the tail end queue.popitem(last=True) def _on_file_event(self, event: events.IEvent): if event.type != FILE_OPENED_EVENT and event.type != FILE_SAVED_EVENT: # Sanity check return event_queue = self.event_queue try: # Ensure payload fits expected data model payload = event.payload.get_dict() url = payload.get('url') file_event = FileEventModel( url=url, asset_type=asset_types.get_asset_type(url), is_folder=payload.get('is_folder', False), event_type=event.type, tag=payload.get('tag', None), datetime=datetime.utcnow(), ) except (pydantic.ValidationError, Exception) as e: log_warn(f"Error parsing file event payload: {str(e)}") return # Insert at head of queue event_queue[url] = file_event event_queue.move_to_end(url, last=False) self._adjust_queue_size(event_queue) self._save_queue_to_settings(event_queue) omni.kit.app.get_app().get_message_bus_event_stream().push(FILE_EVENT_QUEUE_UPDATED) def get_latest_urls_from_event_queue(self, num_latest: int = 1, asset_type: str = None, event_type: int = 0, tag: str = None) -> List[str]: urls = [] for url, file_event in self.event_queue.items(): if asset_type and file_event.asset_type != asset_type: continue elif event_type and file_event.event_type != event_type: continue elif tag and file_event.tag != tag: continue urls.append(url) if len(urls) >= num_latest: break return urls def clear_event_queue(self): queue = self.event_queue queue.clear() self._save_queue_to_settings(queue) omni.kit.app.get_app().get_message_bus_event_stream().push(FILE_EVENT_QUEUE_UPDATED) def on_shutdown(self): self._save_queue_to_settings(self.event_queue) self._event_queue = None self._event_subs.clear() global g_singleton g_singleton = None def get_instance(): return g_singleton
6,817
Python
35.459893
104
0.601878
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/__init__.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """Keeps a history of file events that is made available via an API to other extensions""" __all__ = [ "FileEventHistoryExtension", "FileEventModel", "get_latest_urls_from_event_queue", "get_last_url_visited", "get_last_url_opened", "get_last_url_saved" ] import carb.events FILE_OPENED_EVENT: int = carb.events.type_from_string("omni.kit.helper.file_utils.FILE_OPENED") FILE_SAVED_EVENT: int = carb.events.type_from_string("omni.kit.helper.file_utils.FILE_SAVED") FILE_EVENT_QUEUE_UPDATED: int = carb.events.type_from_string("omni.kit.helper.file_utils.FILE_EVENT_QUEUE_UPDATED") from typing import List from .extension import get_instance, FileEventHistoryExtension, FileEventModel def get_latest_urls_from_event_queue(num_latest: int = 1, asset_type: str = None, event_type: int = 0, tag: str = None) -> List[str]: ext = get_instance() if ext: return ext.get_latest_urls_from_event_queue(num_latest=num_latest, asset_type=asset_type, event_type=event_type, tag=tag) return [] def get_last_url_visited(asset_type: str = None, tag: str = None) -> str: urls = get_latest_urls_from_event_queue(num_latest=1, asset_type=asset_type, tag=tag) if urls: return urls[0] else: return None def get_last_url_opened(asset_type: str = None, tag: str = None) -> str: urls = get_latest_urls_from_event_queue(num_latest=1, asset_type=asset_type, event_type=FILE_OPENED_EVENT, tag=tag) if urls: return urls[0] else: return None def get_last_url_saved(asset_type: str = None, tag: str = None) -> str: urls = get_latest_urls_from_event_queue(num_latest=1, asset_type=asset_type, event_type=FILE_SAVED_EVENT, tag=tag) if urls: return urls[0] else: return None def reset_file_event_queue(): ext = get_instance() if ext: return ext.clear_event_queue()
2,300
Python
40.836363
133
0.709565
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/asset_types.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Dict, List from collections import namedtuple from pathlib import Path AssetTypeDef = namedtuple("AssetTypeDef", "glyph thumbnail matching_exts") # The known list of asset types, stored in this singleton variable _known_asset_types: Dict = None # Default Asset types ASSET_TYPE_ANIM_USD = "anim_usd" ASSET_TYPE_CACHE_USD = "cache_usd" ASSET_TYPE_CURVE_ANIM_USD = "curve_anim_usd" ASSET_TYPE_GEO_USD = "geo_usd" ASSET_TYPE_MATERIAL_USD = "material_usd" ASSET_TYPE_PROJECT_USD = "project_usd" ASSET_TYPE_SEQ_USD = "seq_usd" ASSET_TYPE_SKEL_USD = "skel_usd" ASSET_TYPE_SKEL_ANIM_USD = "skel_anim_usd" ASSET_TYPE_USD_SETTINGS = "settings_usd" ASSET_TYPE_USD = "usd" ASSET_TYPE_FBX = "fbx" ASSET_TYPE_OBJ = "obj" ASSET_TYPE_MATERIAL = "material" ASSET_TYPE_IMAGE = "image" ASSET_TYPE_SOUND = "sound" ASSET_TYPE_SCRIPT = "script" ASSET_TYPE_VOLUME = "volume" ASSET_TYPE_FOLDER = "folder" ASSET_TYPE_ICON = "icon" ASSET_TYPE_HIDDEN = "hidden" ASSET_TYPE_UNKNOWN = "unknown" def init_asset_types(): global _known_asset_types _known_asset_types = {} try: import carb.settings theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") except Exception: theme = None finally: theme = theme or "NvidiaDark" import omni.kit.app ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) icon_path = Path(ext_path).joinpath("icons").joinpath(theme).absolute() thumbnail_path = Path(ext_path).joinpath(f"data").joinpath("thumbnails").absolute() _known_asset_types[ASSET_TYPE_USD_SETTINGS] = AssetTypeDef( f"{icon_path}/settings_usd.svg", f"{thumbnail_path}/settings_usd_256.png", [".settings.usd", ".settings.usda", ".settings.usdc", ".settings.usdz"], ) _known_asset_types[ASSET_TYPE_ANIM_USD] = AssetTypeDef( f"{icon_path}/anim_usd.svg", f"{thumbnail_path}/anim_usd_256.png", [".anim.usd", ".anim.usda", ".anim.usdc", ".anim.usdz"], ) _known_asset_types[ASSET_TYPE_CACHE_USD] = AssetTypeDef( f"{icon_path}/cache_usd.svg", f"{thumbnail_path}/cache_usd_256.png", [".cache.usd", ".cache.usda", ".cache.usdc", ".cache.usdz"], ) _known_asset_types[ASSET_TYPE_CURVE_ANIM_USD] = AssetTypeDef( f"{icon_path}/anim_usd.svg", f"{thumbnail_path}/curve_anim_usd_256.png", [".curveanim.usd", ".curveanim.usda", ".curveanim.usdc", ".curveanim.usdz"], ) _known_asset_types[ASSET_TYPE_GEO_USD] = AssetTypeDef( f"{icon_path}/geo_usd.svg", f"{thumbnail_path}/geo_usd_256.png", [".geo.usd", ".geo.usda", ".geo.usdc", ".geo.usdz"], ) _known_asset_types[ASSET_TYPE_MATERIAL_USD] = AssetTypeDef( f"{icon_path}/material_usd.png", f"{thumbnail_path}/material_usd_256.png", [".material.usd", ".material.usda", ".material.usdc", ".material.usdz"], ) _known_asset_types[ASSET_TYPE_PROJECT_USD] = AssetTypeDef( f"{icon_path}/project_usd.svg", f"{thumbnail_path}/project_usd_256.png", [".project.usd", ".project.usda", ".project.usdc", ".project.usdz"], ) _known_asset_types[ASSET_TYPE_SEQ_USD] = AssetTypeDef( f"{icon_path}/sequence_usd.svg", f"{thumbnail_path}/sequence_usd_256.png", [".seq.usd", ".seq.usda", ".seq.usdc", ".seq.usdz"], ) _known_asset_types[ASSET_TYPE_SKEL_USD] = AssetTypeDef( f"{icon_path}/skel_usd.svg", f"{thumbnail_path}/skel_usd_256.png", [".skel.usd", ".skel.usda", ".skel.usdc", ".skel.usdz"], ) _known_asset_types[ASSET_TYPE_SKEL_ANIM_USD] = AssetTypeDef( f"{icon_path}/anim_usd.svg", f"{thumbnail_path}/skel_anim_usd_256.png", [".skelanim.usd", ".skelanim.usda", ".skelanim.usdc", ".skelanim.usdz"], ) _known_asset_types[ASSET_TYPE_FBX] = AssetTypeDef( f"{icon_path}/usd_stage.svg", f"{thumbnail_path}/fbx_256.png", [".fbx"] ) _known_asset_types[ASSET_TYPE_OBJ] = AssetTypeDef( f"{icon_path}/usd_stage.svg", f"{thumbnail_path}/obj_256.png", [".obj"] ) _known_asset_types[ASSET_TYPE_MATERIAL] = AssetTypeDef( f"{icon_path}/mdl.svg", f"{thumbnail_path}/mdl_256.png", [".mdl", ".mtlx"] ) _known_asset_types[ASSET_TYPE_IMAGE] = AssetTypeDef( f"{icon_path}/image.svg", f"{thumbnail_path}/image_256.png", [".bmp", ".gif", ".jpg", ".jpeg", ".png", ".tga", ".tif", ".tiff", ".hdr", ".dds", ".exr", ".psd", ".ies", ".tx"], ) _known_asset_types[ASSET_TYPE_SOUND] = AssetTypeDef( f"{icon_path}/sound.svg", f"{thumbnail_path}/sound_256.png", [".wav", ".wave", ".ogg", ".oga", ".flac", ".fla", ".mp3", ".m4a", ".spx", ".opus", ".adpcm"], ) _known_asset_types[ASSET_TYPE_SCRIPT] = AssetTypeDef( f"{icon_path}/script.svg", f"{thumbnail_path}/script_256.png", [".py"] ) _known_asset_types[ASSET_TYPE_VOLUME] = AssetTypeDef( f"{icon_path}/volume.svg", f"{thumbnail_path}/volume_256.png", [".nvdb", ".vdb"], ) _known_asset_types[ASSET_TYPE_ICON] = AssetTypeDef(None, None, [".svg"]) _known_asset_types[ASSET_TYPE_HIDDEN] = AssetTypeDef(None, None, [".thumbs"]) try: # avoid dependency on USD in this extension and only use it when available import omni.usd usd_exts = omni.usd.readable_usd_dotted_file_exts() except ImportError: usd_exts = ('.live', '.omni', '.usd', '.usda', '.usdc', '.usdz') # readable_usd_dotted_file_exts() is auto-generated by querying USD; # however, it includes some items that we've assigned more specific # roles (ie, .mdl). So do this last, and subtract out any already- # known types. known_exts = set() for asset_type_def in _known_asset_types.values(): known_exts.update(asset_type_def.matching_exts) usd_exts = [ x for x in usd_exts if x not in known_exts ] _known_asset_types[ASSET_TYPE_USD] = AssetTypeDef( f"{icon_path}/usd_stage.svg", f"{thumbnail_path}/usd_stage_256.png", usd_exts, ) def known_asset_types(): global _known_asset_types if _known_asset_types is None: init_asset_types() return _known_asset_types def clear_asset_types(): known_asset_types().clear() def register_file_extensions(asset_type: str, exts: [str], replace: bool = False): """ Adds an asset type to the recognized list. Args: asset_type (str): Name of asset type. exts ([str]): List of extensions to associate with this asset type, e.g. [".usd", ".usda"]. replace (bool): If True, replaces extensions in the existing definition. Otherwise, append to the existing list. """ if not asset_type or exts == None: return asset_types = known_asset_types() if asset_type in asset_types: glyph = asset_types[asset_type].glyph thumbnail = asset_types[asset_type].thumbnail if replace: asset_types[asset_type] = AssetTypeDef(glyph, thumbnail, exts) else: exts.extend(asset_types[asset_type].matching_exts) asset_types[asset_type] = AssetTypeDef(glyph, thumbnail, exts) else: asset_types[asset_type] = AssetTypeDef(None, None, exts) def asset_type_exts(asset_type: str) -> List[str]: asset_types = known_asset_types() return asset_types[asset_type].matching_exts def is_asset_type(filename: str, asset_type: str) -> bool: """ Returns True if given filename is of specified type. Args: filename (str) asset_type (str): Tested type name. Returns: bool """ asset_types = known_asset_types() if not (filename and asset_type): return False elif asset_type not in asset_types: return False return any([filename.lower().endswith(ext.lower()) for ext in asset_types[asset_type].matching_exts]) def is_udim_sequence(filename: str): return "<UDIM>" in filename and is_asset_type(filename, ASSET_TYPE_IMAGE) def get_asset_type(filename: str) -> str: """ Returns asset type, based on extension of given filename. Args: filename (str) Returns: str """ if not filename: return None asset_types = known_asset_types() for asset_type in asset_types: if is_asset_type(filename, asset_type): return asset_type return ASSET_TYPE_UNKNOWN def get_icon(filename: str) -> str: """ Returns icon for specified file. Args: filename (str) Returns: str: Fullpath to the icon file, None if not found. """ if not filename: return None icon = None asset_type = get_asset_type(filename) asset_types = known_asset_types() if asset_type in asset_types: icon = asset_types[asset_type].glyph return icon def get_thumbnail(filename: str) -> str: """ Returns thumbnail for specified file. Args: filename (str) Returns: str: Fullpath to the thumbnail file, None if not found. """ if not filename: return None thumbnail = None asset_type = get_asset_type(filename) asset_types = known_asset_types() if asset_type == ASSET_TYPE_ICON: thumbnail = filename else: if asset_type in asset_types: thumbnail = asset_types[asset_type].thumbnail import omni.kit.app ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) thumbnail_path = Path(ext_path).joinpath(f"data").joinpath("thumbnails").absolute() return thumbnail or f"{thumbnail_path}/unknown_file_256.png"
10,207
Python
33.140468
122
0.627902
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/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_asset_types import * from .test_event_queue import *
505
Python
44.999996
77
0.788119
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/tests/test_event_queue.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.app from unittest.mock import Mock from omni.kit.test.async_unittest import AsyncTestCase from omni.kit.helper.file_utils import asset_types from .. import ( FILE_OPENED_EVENT, FILE_SAVED_EVENT, FileEventModel, get_instance, get_latest_urls_from_event_queue, get_last_url_opened, get_last_url_saved ) class TestOpenedQueue(AsyncTestCase): """Testing Opened Queue""" async def setUp(self): pass async def tearDown(self): get_instance().clear_event_queue() async def test_get_latest_urls_opened_succeeds(self): """Test saving and retrieving url's from the saved queue""" test_events = [ (FILE_OPENED_EVENT, "omniverse://ov-test/stage.usd", "tag-1"), (FILE_OPENED_EVENT, "omniverse://ov-test/image.jpg", None), (FILE_SAVED_EVENT, "omniverse://ov-baz/folder/", "tag-1"), (FILE_SAVED_EVENT, "omniverse://ov-foo/last_image.png", None), (FILE_OPENED_EVENT, "omniverse://ov-bar/last_material.mdl", "tag-1"), (FILE_OPENED_EVENT, "omniverse://ov-baz/last_url.usd", "tag-2"), ] under_test = get_instance() under_test.clear_event_queue() # Add test urls to queue via event stream event_stream = omni.kit.app.get_app().get_message_bus_event_stream() for event_type, url, tag in test_events: file_event = FileEventModel(url=url, is_folder=url.endswith('/'), tag=tag) event_stream.push(event_type, payload=file_event.dict()) for _ in range(10): await omni.kit.app.get_app().next_update_async() self.assertEqual(len(test_events), len(under_test._event_queue)) self.assertEqual(4, len(get_latest_urls_from_event_queue(num_latest=10, event_type=FILE_OPENED_EVENT))) self.assertEqual(2, len(get_latest_urls_from_event_queue(num_latest=10, event_type=FILE_SAVED_EVENT))) self.assertEqual(3, len(get_latest_urls_from_event_queue(num_latest=10, tag="tag-1"))) self.assertEqual(1, len(get_latest_urls_from_event_queue(num_latest=10, asset_type=asset_types.ASSET_TYPE_USD, tag="tag-1"))) self.assertTrue("last_url" in get_last_url_opened()) self.assertTrue("last_material" in get_last_url_opened(asset_type=asset_types.ASSET_TYPE_MATERIAL)) self.assertTrue("last_image" in get_last_url_saved(asset_type=asset_types.ASSET_TYPE_IMAGE)) # Confirm queue was properly saved into user settings expected = test_events[::-1] # LIFO list matches the order of the event queue self._event_queue = under_test._load_queue_from_settings() # Reload queue from settings self.assertEqual(len(under_test.event_queue), len(expected)) for i, entry in enumerate(under_test.event_queue.items()): file_event = entry[1] test_url = expected[i] self.assertEqual(file_event.url, test_url[1]) self.assertEqual(file_event.tag, test_url[2]) self.assertEqual(file_event.is_folder, test_url[1].endswith('/'))
3,506
Python
47.708333
133
0.669994
omniverse-code/kit/exts/omni.kit.helper.file_utils/omni/kit/helper/file_utils/tests/test_asset_types.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 .. import asset_types class TestAssetTypes(omni.kit.test.AsyncTestCase): """Testing FilePickerModel.*asset_type""" async def setUp(self): self.test_filenames = [ ("test.settings.usd", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.settings.usda", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.settings.usdc", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.settings.usdz", asset_types.ASSET_TYPE_USD_SETTINGS), ("test.fbx", asset_types.ASSET_TYPE_FBX), ("test.obj", asset_types.ASSET_TYPE_OBJ), ("test.mdl", asset_types.ASSET_TYPE_MATERIAL), ("test.mtlx", asset_types.ASSET_TYPE_MATERIAL), ("test.bmp", asset_types.ASSET_TYPE_IMAGE), ("test.gif", asset_types.ASSET_TYPE_IMAGE), ("test.jpg", asset_types.ASSET_TYPE_IMAGE), ("test.jpeg", asset_types.ASSET_TYPE_IMAGE), ("test.png", asset_types.ASSET_TYPE_IMAGE), ("test.tga", asset_types.ASSET_TYPE_IMAGE), ("test.tif", asset_types.ASSET_TYPE_IMAGE), ("test.tiff", asset_types.ASSET_TYPE_IMAGE), ("test.hdr", asset_types.ASSET_TYPE_IMAGE), ("test.dds", asset_types.ASSET_TYPE_IMAGE), ("test.exr", asset_types.ASSET_TYPE_IMAGE), ("test.psd", asset_types.ASSET_TYPE_IMAGE), ("test.ies", asset_types.ASSET_TYPE_IMAGE), ("test.wav", asset_types.ASSET_TYPE_SOUND), ("test.wav", asset_types.ASSET_TYPE_SOUND), ("test.wave", asset_types.ASSET_TYPE_SOUND), ("test.ogg", asset_types.ASSET_TYPE_SOUND), ("test.oga", asset_types.ASSET_TYPE_SOUND), ("test.flac", asset_types.ASSET_TYPE_SOUND), ("test.fla", asset_types.ASSET_TYPE_SOUND), ("test.mp3", asset_types.ASSET_TYPE_SOUND), ("test.m4a", asset_types.ASSET_TYPE_SOUND), ("test.spx", asset_types.ASSET_TYPE_SOUND), ("test.opus", asset_types.ASSET_TYPE_SOUND), ("test.adpcm", asset_types.ASSET_TYPE_SOUND), ("test.py", asset_types.ASSET_TYPE_SCRIPT), ("test.nvdb", asset_types.ASSET_TYPE_VOLUME), ("test.vdb", asset_types.ASSET_TYPE_VOLUME), ("test.svg", asset_types.ASSET_TYPE_ICON), (".thumbs", asset_types.ASSET_TYPE_HIDDEN), ("test.usd", asset_types.ASSET_TYPE_USD), ("test.usda", asset_types.ASSET_TYPE_USD), ("test.usdc", asset_types.ASSET_TYPE_USD), ("test.usdz", asset_types.ASSET_TYPE_USD), ("test.live", asset_types.ASSET_TYPE_USD), ] async def tearDown(self): pass async def test_is_asset_type(self): """Testing asset_types.is_asset_type returns expected result""" for test_filename in self.test_filenames: filename, expected = test_filename self.assertTrue(asset_types.is_asset_type(filename, expected)) async def test_get_asset_type(self): """Testing asset_types.get_asset_type returns expected result""" for test_filename in self.test_filenames: filename, expected = test_filename self.assertEqual(asset_types.get_asset_type(filename), expected) # Test unknown file type self.assertEqual(asset_types.get_asset_type("test.unknown"), asset_types.ASSET_TYPE_UNKNOWN) async def test_get_icon(self): """Testing asset_types.get_icon returns expected icon for asset type""" for test_filename in self.test_filenames: filename, asset_type = test_filename if asset_type not in [asset_types.ASSET_TYPE_ICON, asset_types.ASSET_TYPE_HIDDEN]: expected = asset_types._known_asset_types[asset_type].glyph self.assertEqual(asset_types.get_icon(filename), expected) async def test_get_thumbnail(self): """Testing FilePickerModel.get_thumbnail returns correct thumbnail for asset type""" for test_filename in self.test_filenames: filename, asset_type = test_filename if asset_type not in [asset_types.ASSET_TYPE_ICON, asset_types.ASSET_TYPE_HIDDEN]: expected = asset_types._known_asset_types[asset_type].thumbnail self.assertEqual(asset_types.get_thumbnail(filename), expected) async def test_register_file_extensions(self): """Testing FilePickerModel.register_file_extensions""" # Add to existing type asset_types.register_file_extensions("usd", [".test", "testz"]) self.assertTrue(asset_types.is_asset_type("file.testz", "usd")) # Register new type test_type = "test" asset_types.register_file_extensions(test_type, [".test", "testz"]) self.assertTrue(asset_types.is_asset_type("file.test", test_type)) self.assertTrue(asset_types.is_asset_type("file.testz", test_type))
5,417
Python
49.635514
100
0.625623
omniverse-code/kit/exts/omni.kit.helper.file_utils/docs/index.rst
omni.kit.helper.file_utils ########################## .. toctree:: :maxdepth: 1 CHANGELOG
98
reStructuredText
11.374999
26
0.479592
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/style.py
__all__ = ["ActionsWindowStyle"] from omni.ui import color as cl from pathlib import Path CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("icons") VIEW_ROW_HEIGHT = 28 """Style colors""" # https://confluence.nvidia.com/pages/viewpage.action?pageId=1218553472&preview=/1218553472/1359943485/image2022-6-7_13-20-4.png cl.actions_column_header_background = cl.shade(cl("#323434")) cl.actions_text = cl.shade(cl("#848484")) cl.actions_background = cl.shade(cl("#1F2123")) cl.actions_background_hovered = cl.shade(cl("#2A2B2C")) cl.actions_background_selected = cl.shade(cl("#77878A")) cl.actions_item_icon_expand_background = cl.shade(cl('#9E9E9E')) cl.actions_row_background = cl.shade(cl('#444444')) ACTIONS_WINDOW_STYLE = { "ActionsView": { "background_color": cl.actions_background, "scrollbar_size": 10, "background_selected_color": 0x109D905C, # Same in stage window "secondary_selected_color": 0xFFB0703B, # column resize "secondary_color": cl.actions_text, # column splitter }, "ActionsView:selected": { "background_color": cl.actions_background_selected, }, "ActionsView.Row.Background": {"background_color": cl.actions_row_background}, "ActionsView.Header.Background": {"background_color": cl.actions_column_header_background}, "ActionsView.Header.Text": {"color": cl.actions_text, "margin": 4}, "ActionsView.Item.Text": {"color": cl.actions_text, "margin": 4}, "ActionsView.Item.Text:selected": {"color": cl.actions_background}, "ActionsView.Item.Icon.Background": {"background_color": cl.actions_item_icon_expand_background, "border_radius": 2}, "ActionsView.Item.Icon.Background:selected": {"background_color": cl.actions_background}, "ActionsView.Item.Icon.Text": {"color": cl.actions_background}, "ActionsView.Item.Icon.Text:selected": {"color": cl.actions_text}, } HIGHLIGHT_LABEL_STYLE = { "HStack": {"margin": 4}, "Label": {"color": cl.actions_text}, "Label:selected": {"color": cl.actions_background}, }
2,104
Python
43.787233
128
0.696293
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/extension.py
__all__ = ["ActionsExtension"] from functools import partial import carb.settings import omni.ext import omni.ui as ui import omni.kit.ui from omni.kit.actions.core import get_action_registry from .window import ActionsWindow SETTING_SHOW_STARTUP = "/exts/omni.kit.actions.window/showStartup" class ActionsExtension(omni.ext.IExt): WINDOW_NAME = "Actions" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): self._actions_window = None ui.Workspace.set_show_window_fn( ActionsExtension.WINDOW_NAME, partial(self.show_window, ActionsExtension.MENU_PATH), ) show_startup = carb.settings.get_settings().get(SETTING_SHOW_STARTUP) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(ActionsExtension.MENU_PATH, self.show_window, toggle=True, value=show_startup) if show_startup: ui.Workspace.show_window(ActionsExtension.WINDOW_NAME) def on_shutdown(self): if self._actions_window: self._actions_window.destroy() self._actions_window = None ui.Workspace.set_show_window_fn(ActionsExtension.WINDOW_NAME, None) def show_window(self, menu_path: str, visible: bool): if visible: self._actions_window = ActionsWindow(ActionsExtension.WINDOW_NAME) self._actions_window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._actions_window: self._actions_window.visible = False def _set_menu(self, checked: bool): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ActionsExtension.MENU_PATH, checked) def _visiblity_changed_fn(self, visible): self._set_menu(visible)
1,887
Python
32.122806
124
0.660307
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/__init__.py
__all__ = [ "ActionsExtension", "AbstractActionItem", "ActionExtItem", "AbstractActionsModel", "ColumnRegistry", "ActionsView", "AbstractColumnDelegate", "StringColumnDelegate", "ActionsDelegate", "ActionsPicker", "ACTIONS_WINDOW_STYLE", ] from .extension import * from .model.abstract_actions_model import AbstractActionItem, ActionExtItem, AbstractActionsModel from .column_registry import ColumnRegistry from .widget.actions_view import ActionsView from .delegate.abstract_column_delegate import AbstractColumnDelegate from .delegate.string_column_delegate import StringColumnDelegate from .delegate.actions_delegate import ActionsDelegate from .picker import ActionsPicker from .style import ACTIONS_WINDOW_STYLE
761
Python
32.130433
97
0.780552
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/picker.py
__all__ = ["ActionColumnDelegate", "ActionsPicker"] import omni.ui as ui from typing import List, Callable from omni.kit.actions.core import Action from .window import ActionsWindow from .model.actions_item import AbstractActionItem, ActionDetailItem from .delegate.string_column_delegate import StringColumnDelegate class ActionColumnDelegate(StringColumnDelegate): """ A simple delegate to display a action in column. Kwargs: get_value_fn (Callable[[ui.AbstractItem], str]): Callback function to get item display string. Default using item.id width (ui.Length): Column width. Default ui.Fraction(1). """ def get_value(self, item: ActionDetailItem): if self._get_value_fn: return self._get_value_fn(item) else: if isinstance(item, ActionDetailItem): # Show action display name instead action id return item.action.display_name else: return item.id class ActionsPicker(ActionsWindow): def __init__(self, width=0, height=600, on_selected_fn: Callable[[Action],None]=None, expand_all: bool=True, focus_search: bool=True ): super().__init__("###ACTION_PICKER", width=width, height=height) self.flags = ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_POPUP self.__on_selected_fn = on_selected_fn self.__expand_all = expand_all self.__focus_search = focus_search def _register_column_delegates(self): self._column_registry.register_delegate(ActionColumnDelegate("Action", width=200)) def _build_ui(self): super()._build_ui() self._actions_view.set_selection_changed_fn(self._on_selection_changed) if self.__expand_all: self._actions_view.set_expanded(None, True, True) if self.__focus_search and self._search_field: self._search_field._search_field.focus_keyboard() def _on_selection_changed(self, selections: List[AbstractActionItem]): for item in selections: if isinstance(item, ActionDetailItem): if self.__on_selected_fn: self.__on_selected_fn(item.action) def _on_search_action(self, action: Action, word: str) -> bool: # In pick mode, only display extension id and display name # So we only search in these two fields if word.lower() in action.extension_id.lower() \ or word.lower() in action.display_name.lower(): return True return False
2,623
Python
38.164179
127
0.64125
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/column_registry.py
__all__ = ["ColumnRegistry"] from typing import Optional, Dict import carb from .delegate.abstract_column_delegate import AbstractColumnDelegate class ColumnRegistry: """ Registry for action columns. """ def __init__(self): self._max_column_id = -1 self._delegates: Dict[int, AbstractColumnDelegate] = {} @property def max_column_id(self) -> int: """ Max column id registered. """ return self._max_column_id def register_delegate(self, delegate: AbstractColumnDelegate, column_id: int=-1, overwrite_if_exists: bool=True) -> bool: """ Register a delegate for a column. Args: delegate (AbstractColumnDelegate): Delegate to show a column. Kwargs: column_id (int): Column id. Default -1 means auto generation. overwrite_if_exists (bool): Overwrite exising delegate if True. Otherwise False. """ if column_id < 0: column_id = self._max_column_id + 1 if column_id in self._delegates: if not overwrite_if_exists: carb.log_warn(f"A delegate already registered for column {column_id}!") return False self._delegates[column_id] = delegate self._max_column_id = column_id return True def unregister_delegate(self, column_id: int) -> bool: """ Unregister a delegate for a column. Args: column_id (int): Column id to unregister. """ if column_id in self._delegates: self._delegates.pop(column_id) if column_id == self._max_column_id: self._max_column_id -= 1 def get_delegate(self, column_id: int) -> Optional[AbstractColumnDelegate]: """ Retrieve a delegate for a column. Args: column_id (int): Column id. """ if column_id in self._delegates: return self._delegates[column_id] else: return None
2,034
Python
29.833333
126
0.576205
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/window.py
__all__ = ["ActionsWindow"] from .model.actions_model import ActionsModel, ActionDetailItem from .column_registry import ColumnRegistry from .widget.actions_view import ActionsView from .delegate.actions_delegate import ActionsDelegate from .delegate.string_column_delegate import StringColumnDelegate from .style import ACTIONS_WINDOW_STYLE import omni.ui as ui from omni.kit.actions.core import Action from typing import List, Optional class ActionsWindow(ui.Window): """ Window to show registered actions. """ def __init__(self, title: str, width=1200, height=600): self._search_field = None super().__init__(title, width=width, height=height) self.frame.set_style(ACTIONS_WINDOW_STYLE) self.frame.set_build_fn(self._build_ui) def destroy(self): self.visible = False if self._search_field: self._search_field.destroy() self._actions_view = None def _register_column_delegates(self): self._column_registry.register_delegate(StringColumnDelegate("Action", width=200)) self._column_registry.register_delegate( StringColumnDelegate( "Display Name", get_value_fn=lambda item: item.action.display_name if isinstance(item, ActionDetailItem) else "", width=300 ) ) self._column_registry.register_delegate( StringColumnDelegate( "Tag", get_value_fn=lambda item: item.action.tag if isinstance(item, ActionDetailItem) else "", width=160, ) ) self._column_registry.register_delegate( StringColumnDelegate( "Icon Url", lambda item: item.action.icon_url if isinstance(item, ActionDetailItem) else "", width=120, ) ) self._column_registry.register_delegate( StringColumnDelegate( "Description", lambda item: item.action.description if isinstance(item, ActionDetailItem) else "", width=200, ) ) def _build_ui(self): self._column_registry = ColumnRegistry() self._register_column_delegates() self._actions_model = ActionsModel(self._column_registry, on_search_action_fn=self._on_search_action) self._actions_delegate = ActionsDelegate(self._actions_model, self._column_registry) with self.frame: with ui.VStack(spacing=4): try: from omni.kit.widget.searchfield import SearchField self._search_field = SearchField( on_search_fn=self._on_search, subscribe_edit_changed=True, style=ACTIONS_WINDOW_STYLE, show_tokens=False, ) except ImportError: self._search_field = None with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="ActionsView", ): self._actions_view = ActionsView(self._actions_model, self._actions_delegate) def _on_search(self, search_words: Optional[List[str]]) -> None: self._actions_model.search(search_words) # Auto expand on searching self._actions_view.set_expanded(None, True, True) def _on_search_action(self, action: Action, word: str) -> bool: if word.lower() in action.extension_id.lower() \ or word.lower() in action.id.lower() \ or word.lower() in action.display_name.lower() \ or word.lower() in action.description.lower() \ or word.lower() in action.tag.lower() \ or word.lower() in action.icon_url.lower(): return True return False
4,048
Python
37.932692
113
0.589427
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/widget/actions_view.py
__all__ = ["ActionsView"] import omni.ui as ui from ..model.abstract_actions_model import AbstractActionsModel from ..delegate.actions_delegate import ActionsDelegate class ActionsView(ui.TreeView): def __init__(self, model: AbstractActionsModel, delegate: ActionsDelegate): super().__init__( model, delegate=delegate, root_visible=False, header_visible=True, columns_resizable=True, style_type_name_override="ActionsView" ) self.column_widths = delegate.column_widths
571
Python
30.777776
79
0.646235
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/delegate/actions_delegate.py
__all__ = ["ActionsDelegate"] from typing import List import omni.ui as ui from typing import Optional from .abstract_column_delegate import AbstractColumnDelegate from ..model.abstract_actions_model import AbstractActionsModel from ..column_registry import ColumnRegistry from ..style import ICON_PATH, VIEW_ROW_HEIGHT class ActionsDelegate(ui.AbstractItemDelegate): """ General action delegate to show action item in treeview. Args: column_registry (ColumnRegistry): Registry to get column delegate. """ def __init__(self, model: AbstractActionsModel, column_registry: ColumnRegistry): self._model = model self._column_registry = column_registry self.__context_menu: Optional[ui.Menu] = None self.__execute_menuitem: Optional[ui.MenuItem] = None super().__init__() @property def column_widths(self) -> List[ui.Length]: """ Column widths for treeview. """ widths = [] for i in range(self._column_registry.max_column_id): delegate = self._column_registry.get_delegate(i) if delegate: widths.append(delegate.width) return widths def build_branch(self, model: ui.AbstractItemModel, item: ui.AbstractItem, column_id: int=0, level: int = 0, expanded: bool = False): """ Build branch for column. Refer to ui.AbstractItemDelegate.build_branch for detail. """ if column_id == 0: with ui.HStack(width=20 * (level + 1), height=0): if model.can_item_have_children(item): with ui.ZStack(): with ui.VStack(height=VIEW_ROW_HEIGHT): ui.Spacer() ui.Rectangle(height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() with ui.VStack(): ui.Spacer() self.__build_expand_icon(expanded) super().build_branch(model, item, column_id, level, expanded) ui.Spacer() else: ui.Spacer() def build_widget(self, model: ui.AbstractItemModel, item: ui.AbstractItem, column_id: int=0, level: int=0, expanded: bool=False): """ Build widget for column. Refer to ui.AbstractItemDelegate.build_widget for detail. """ delegate = self._column_registry.get_delegate(column_id) if delegate: widget = delegate.build_widget(model, item, level, expanded) if widget: widget.set_mouse_pressed_fn(lambda x, t, b, f, i=item, d=delegate: self.on_mouse_pressed(b, i, d)) widget.set_mouse_double_clicked_fn(lambda x, y, b, f, i=item, d=delegate: self.on_mouse_double_click(b, i, d)) def build_header(self, column_id): """ Build header for column. Refer to ui.AbstractItemDelegate.build_header for detail. """ delegate = self._column_registry.get_delegate(column_id) if delegate: delegate.build_header() def on_mouse_double_click(self, button: int, item: ui.AbstractItem, column_delegate: AbstractColumnDelegate): if button == 0: self._model.execute(item) def on_mouse_pressed(self, button: int, item: ui.AbstractItem, column_delegate: AbstractColumnDelegate): if button == 1: if self.__context_menu is None: self.__context_menu = ui.Menu(f"ACTION CONTEXT MENU##{hash(self)}") with self.__context_menu: self.__execute_menuitem = ui.MenuItem("Execute") self.__execute_menuitem.set_triggered_fn(lambda i=item: self._model.execute(item)) self.__context_menu.show() def __build_expand_icon(self, expanded: bool): # Draw the +/- icon with ui.HStack(): ui.Spacer() image_name = "Minus" if expanded else "Plus" ui.Image( f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style_type_name_override="TreeView.Item" ) ui.Spacer(width=5)
4,241
Python
40.588235
137
0.581938
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/delegate/string_column_delegate.py
__all__ = ["StringColumnDelegate"] from .abstract_column_delegate import AbstractColumnDelegate from ..model.actions_item import ActionExtItem, AbstractActionItem from ..model.abstract_actions_model import AbstractActionsModel from ..style import HIGHLIGHT_LABEL_STYLE import omni.ui as ui from omni.kit.widget.highlight_label import HighlightLabel from typing import Callable class StringColumnDelegate(AbstractColumnDelegate): """ A simple delegate to display a string in column. Kwargs: get_value_fn (Callable[[ui.AbstractItem], str]): Callback function to get item display string. Default using item.id width (ui.Length): Column width. Default ui.Fraction(1). """ def __init__(self, name: str, get_value_fn: Callable[[AbstractActionItem], str]=None, width: ui.Length=ui.Fraction(1)): self._get_value_fn = get_value_fn super().__init__(name, width=width) def build_widget(self, model: AbstractActionsModel, item: AbstractActionItem, level: int, expand: bool): if isinstance(item, ActionExtItem): container = ui.ZStack() with container: with ui.VStack(): ui.Spacer() ui.Rectangle(height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() HighlightLabel(self.get_value(item), highlight=item.highlight, style=HIGHLIGHT_LABEL_STYLE, alignment=ui.Alignment.LEFT_TOP) return container if isinstance(item, ActionExtItem) or isinstance(item, AbstractActionItem): label = HighlightLabel(self.get_value(item), highlight=item.highlight, style=HIGHLIGHT_LABEL_STYLE) return label.widget else: return None def get_value(self, item: AbstractActionItem): if self._get_value_fn: return self._get_value_fn(item) else: return item.id
1,932
Python
42.931817
140
0.668219
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/delegate/abstract_column_delegate.py
__all__ = ["AbstractColumnDelegate"] import omni.ui as ui import abc class AbstractColumnDelegate: """ Represent a column delegate in actions Treeview. Args: name (str): Column name. width (ui.Length): Column width. Default ui.Fraction(1). """ def __init__(self, name: str, width: ui.Length=ui.Fraction(1)): self._name = name if isinstance(width, int) or isinstance(width, float): width = ui.Pixel(width) self._width = width @property def width(self) -> ui.Length: """ Column width. """ return self._width def execute(self, item: ui.AbstractItem): """ Execute model item. Args: item (ui.AbstractItem): Item to show. """ pass @abc.abstractmethod def build_widget(self, model: ui.AbstractItemModel, item: ui.AbstractItem, level: int, expand: bool) -> ui.Widget: """ Build a custom column widget in TreeView. Return created widget. Args: model (ui.AbstractItemModel): Actions model. item (ui.AbstractItem): Item to show. level (int): Level in treeview. expand (bool): Iten expand or not. """ return None def build_header(self): """ Build header widget in TreeView, default ui.Label(name) """ with ui.ZStack(): ui.Rectangle(style_type_name_override="ActionsView.Header.Background") ui.Label(self._name, style_type_name_override="ActionsView.Header.Text")
1,593
Python
26.482758
118
0.576899
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/tests/__init__.py
from .test_actions_window import *
35
Python
16.999992
34
0.771429
omniverse-code/kit/exts/omni.kit.actions.window/omni/kit/actions/window/tests/test_actions_window.py
from ast import Import import omni.kit.test import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from omni.kit.actions.core import get_action_registry import omni.ui as ui import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 from pathlib import Path CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") ACTION_SHOW_WINDOW = "Show Actions Window" ACTION_HIDE_WINDOW = "Hide Actions Window" class TestActionsWindow(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._ext_id = "omni.kit.actions.window.tests" self.__register_test_actions() window = ui.Workspace.get_window("Actions") await self.docked_test_window(window=window, width=1280, height=400, block_devices=False) async def tearDown(self): # Deregister all the test actions. self._action_registry.deregister_action(self._ext_id, ACTION_SHOW_WINDOW) self._action_registry.deregister_action(self._ext_id, ACTION_HIDE_WINDOW) self._action_registry = None async def test_1_general_window(self): # When startup, no actions loaded result_name = "test_action_window_general" try: from omni.kit.widget.searchfield import SearchField result_name += "_with_search" # Wait for serach icon loaded for i in range(5): await omni.kit.app.get_app().next_update_async() except ImportError: pass await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"{result_name}.png") async def test_2_search(self): try: from omni.kit.widget.searchfield import SearchField # Actions reloaded, we can see register actions now # Focus on search bar await ui_test.emulate_mouse_move_and_click(Vec2(50, 17)) # Search "Show" await ui_test.emulate_char_press("Show\n") await ui_test.emulate_mouse_move_and_click(Vec2(0, 0)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_action_window_search.png") except ImportError: pass async def test_3_search_clean(self): try: from omni.kit.widget.searchfield import SearchField # Focus on search bar await ui_test.emulate_mouse_move_and_click(Vec2(50, 17)) # Clean search await ui_test.emulate_mouse_move_and_click(Vec2(1263, 17)) await ui_test.emulate_mouse_move_and_click(Vec2(0, 0)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_action_window_search_clean.png") except ImportError: pass def __register_test_actions(self): self._action_registry = get_action_registry() self._action_registry.register_action( self._ext_id, ACTION_SHOW_WINDOW, lambda: None, display_name=ACTION_SHOW_WINDOW, description=ACTION_SHOW_WINDOW, tag="Actions", ) self._action_registry.register_action( self._ext_id, ACTION_HIDE_WINDOW, lambda: None, display_name=ACTION_HIDE_WINDOW, description=ACTION_HIDE_WINDOW, tag="Actions", )
3,530
Python
36.563829
128
0.630312
omniverse-code/kit/exts/omni.kit.actions.window/docs/CHANGELOG.rst
********** CHANGELOG ********** This document records all notable changes to ``omni.kit.actions.window`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`. ## [1.1.0] - 2022-10-17 ### Changed - OM-65822: Also search for Action display name without case sensitive - Update UI to use same style as Hotkeys window ## [1.0.4] - 2022-09-20 ### Added - Add args for auto expand and focus search for ActionsPicker ## [1.0.3] - 2022-09-02 ### Changed - Export more APIs for hotkeys window ### Added - Add ActionsPicker ## [1.0.2] - 2022-09-01 ### Changed - Default not show window when startup ## [1.0.1] - 2022-08-23 ### Added - Execute action from list - Auto expand on searching ## [1.0.0] - 2022-07-06 - First version
750
reStructuredText
21.088235
83
0.673333
omniverse-code/kit/exts/omni.kit.actions.window/docs/index.rst
omni.kit.actions.window ########################### Window to show actions. .. toctree:: :maxdepth: 1 CHANGELOG
122
reStructuredText
10.181817
27
0.52459
omniverse-code/kit/exts/omni.kit.property.transform/PACKAGE-LICENSES/omni.kit.property.transform-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.property.transform/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.3.5" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Transform Property Widget" description="View and Edit Transform Property Values" feature = true # URL of the extension source repository. repository = "" # Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Keywords for the extension keywords = ["kit", "usd", "property", "transform"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.kit.widget.settings" = {} "omni.kit.window.property" = {} "omni.kit.property.usd" = {} "omni.kit.commands" = {} "omni.kit.usd_undo" = {} "omni.hydra.scene_api" = {} [[python.module]] name = "omni.kit.property.transform" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.ui_test", "omni.kit.test_suite.helpers" ] stdoutFailPatterns.exclude = [ "*Failed to acquire interface [omni::kit::renderer::IGpuFoundation v0.2]*", # Leak ]
1,705
TOML
26.079365
93
0.702053
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/__init__.py
from .scripts import *
23
Python
10.999995
22
0.73913
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/xform_op_utils.py
from pxr import Usd, Tf, Sdf, Gf, UsdGeom import carb from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload import omni.kit XFROM_OP_PREFIX = "xformOp:" INVERSE_PREFIX = "!invert!" INVERSE_XFORM_OP_PREFIX = "!invert!xformOp:" RESET_XFORM_STACK = UsdGeom.XformOpTypes.resetXformStack XFROM_OP_TYPE_NAME = [ "translate", "scale", "rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "orient", "transform", ] XFROM_OP_TYPE = [ UsdGeom.XformOp.TypeTranslate, UsdGeom.XformOp.TypeScale, UsdGeom.XformOp.TypeRotateX, UsdGeom.XformOp.TypeRotateY, UsdGeom.XformOp.TypeRotateZ, UsdGeom.XformOp.TypeRotateXYZ, UsdGeom.XformOp.TypeRotateXZY, UsdGeom.XformOp.TypeRotateYXZ, UsdGeom.XformOp.TypeRotateYZX, UsdGeom.XformOp.TypeRotateZXY, UsdGeom.XformOp.TypeRotateZYX, UsdGeom.XformOp.TypeOrient, UsdGeom.XformOp.TypeTransform, ] def is_inverse_op(op_name: str): return op_name.startswith(INVERSE_XFORM_OP_PREFIX) def is_reset_xform_stack_op(op_name: str): return op_name == RESET_XFORM_STACK def get_op_type_name(op_name: str): test_name = op_name if is_inverse_op(op_name): test_name = op_name.split(INVERSE_PREFIX, 1)[1] if test_name.startswith(XFROM_OP_PREFIX): names = test_name.split(":") if len(names) >= 2 and names[1] in XFROM_OP_TYPE_NAME: return names[1] return None def get_op_type(op_name: str): op_type_name = get_op_type_name(op_name) return XFROM_OP_TYPE[XFROM_OP_TYPE_NAME.index(op_type_name)] def get_op_name_suffix(op_name: str): test_name = op_name if is_inverse_op(op_name): test_name = op_name.split(INVERSE_PREFIX, 1)[1] if test_name.startswith(XFROM_OP_PREFIX): names = test_name.split(":", 2) if len(names) >= 3: return names[2] return None def is_pivot_op(op_name: str): op_suffix = get_op_name_suffix(op_name) if op_suffix != None: if op_suffix == "pivot": return True return False def is_valid_op_name(op_name: str): if is_reset_xform_stack_op(op_name): return True if get_op_type_name(op_name) is not None: return True return False def get_op_attr_name(op_name: str): if not is_valid_op_name(op_name): return None if is_reset_xform_stack_op(op_name): return None if is_inverse_op(op_name): return op_name.split(INVERSE_PREFIX, 1)[1] return op_name def get_inverse_op_Name(ori_op_name, desired_invert): if is_reset_xform_stack_op(ori_op_name): return ori_op_name if desired_invert and not is_inverse_op(ori_op_name): return INVERSE_PREFIX + ori_op_name if not desired_invert and is_inverse_op(ori_op_name): return ori_op_name.split(INVERSE_PREFIX, 1)[1] return ori_op_name def get_op_precision(attr_type_name: Sdf.ValueTypeName): if attr_type_name in [Sdf.ValueTypeNames.Float3, Sdf.ValueTypeNames.Quatf, Sdf.ValueTypeNames.Float]: return UsdGeom.XformOp.PrecisionFloat if attr_type_name in [ Sdf.ValueTypeNames.Double3, Sdf.ValueTypeNames.Quatd, Sdf.ValueTypeNames.Double, Sdf.ValueTypeNames.Matrix4d, ]: return UsdGeom.XformOp.PrecisionDouble if attr_type_name in [Sdf.ValueTypeNames.Half3, Sdf.ValueTypeNames.Quath, Sdf.ValueTypeNames.Half]: return UsdGeom.XformOp.PrecisionHalf return UsdGeom.XformOp.PrecisionDouble def _add_trs_op( payload: PrimSelectionPayload ): settings = carb.settings.get_settings() # Retrieve the default precision default_xform_op_precision = settings.get("/persistent/app/primCreation/DefaultXformOpPrecision") if default_xform_op_precision is None: settings.set_default_string( "/persistent/app/primCreation/DefaultXformOpPrecision", "Double" ) default_xform_op_precision = "Double" _precision = UsdGeom.XformOp.PrecisionDouble if default_xform_op_precision == "Double": _precision = UsdGeom.XformOp.PrecisionDouble elif default_xform_op_precision == "Float": _precision = UsdGeom.XformOp.PrecisionFloat elif default_xform_op_precision == "Half": _precision = UsdGeom.XformOp.PrecisionHalf # Retrieve the default rotation order default_rotation_order = settings.get("/persistent/app/primCreation/DefaultRotationOrder") if default_rotation_order is None: settings.set_default_string("/persistent/app/primCreation/DefaultRotationOrder", "XYZ") default_rotation_order = "XYZ" omni.kit.commands.execute("AddXformOp", payload=payload, precision=_precision, rotation_order = default_rotation_order, add_translate_op = True, add_rotateXYZ_op = True, add_orient_op=False, add_scale_op = True, add_transform_op = False, add_pivot_op = False)
4,957
Python
31.194805
148
0.680048
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_model.py
from typing import Callable import weakref import carb import omni.timeline import omni.ui as ui import omni.usd from pxr import Usd, Sdf, Tf, Gf from omni.kit.property.usd.usd_attribute_model import ( FloatModel, UsdBase, UsdAttributeModel, GfVecAttributeModel, ) # TODO: will add controlstate class VecAttributeModel(ui.AbstractItemModel): def __init__(self, default_value, begin_edit_callback: Callable[[None], None] = None, end_edit_callback: Callable[[Gf.Vec3d], None] = None): super().__init__() # We want to parse the values of this model to look for math operations, # so its items need to use string models instead of float models class StringModel(ui.SimpleStringModel): def __init__(self, parent, index): super().__init__() self._parent = weakref.ref(parent) self.index = index def begin_edit(self): parent = self._parent() parent.begin_edit(self) def end_edit(self): parent = self._parent() parent.end_edit(self) class VectorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model dimension = 3 self._items = [VectorItem(StringModel(self, i)) for i in range(dimension)] self._default_value = default_value self._begin_edit_callback = begin_edit_callback self._end_edit_callback = end_edit_callback for item in self._items: item.model.set_value(self._default_value) self._root_model = ui.SimpleStringModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._root_model return item.model def _on_value_changed(self, item): pass def begin_edit(self, item): index = item.index if self._begin_edit_callback: self._begin_edit_callback(index) def end_edit(self, model): text = model.get_value_as_string() index = model.index for item in self._items: item.model.set_value(self._default_value) if self._end_edit_callback: self._end_edit_callback(text, index)
2,443
Python
29.936708
144
0.598854
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_widget.py
import traceback import carb import omni.usd import omni.ui as ui from functools import lru_cache from pxr import UsdGeom, Tf, Usd, Sdf from pxr import Trace from collections import defaultdict from typing import Any, DefaultDict, Dict, List, Sequence, Set, Tuple from .transform_builder import TransformWidgets from omni.kit.property.usd import ADDITIONAL_CHANGED_PATH_EVENT_TYPE from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget, get_group_properties_clipboard, set_group_properties_clipboard from omni.kit.property.usd.usd_attribute_model import GfVecAttributeSingleChannelModel from omni.kit.window.property.templates import GroupHeaderContextMenuEvent, GroupHeaderContextMenu from omni.kit.widget.settings import get_style from .xform_op_utils import _add_trs_op @lru_cache() def _get_plus_glyph(): return ui.get_custom_glyph_code("${glyphs}/menu_context.svg") class TransformAttributeWidget(UsdPropertiesWidget): def __init__(self, title: str, collapsed: bool): super().__init__(title="Transform", collapsed=False) self._transform_widget = TransformWidgets(self) self._listener = None self._models = defaultdict(list) self._offset_mode = False self._link_scale = False def on_new_payload(self, payload): if not super().on_new_payload(payload): return False stage = self._payload.get_stage() if not stage or not len(self._payload): return False for path in self._payload: prim = stage.GetPrimAtPath(path) if not prim.IsA(UsdGeom.Xformable): return False return True def clean(self): """ See PropertyWidget.clean """ if self._transform_widget: self._transform_widget._clear_widgets() self._transform_widget = None super().clean() def build_items(self): self.reset() if len(self._payload) == 0: return last_prim = self._get_prim(self._payload[-1]) if not last_prim: return stage = last_prim.GetStage() if not stage: return self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage) self._bus_sub = self._message_bus.create_subscription_to_pop_by_type(ADDITIONAL_CHANGED_PATH_EVENT_TYPE, self._on_bus_event) # for prim_path in self._payload: if self._payload is not None: if self._offset_mode: self._models = self._transform_widget.build_transform_offset_frame(self._payload, self._collapsable_frame, stage) else: self._models, all_empty_xformop = self._transform_widget.build_transform_frame(self._payload, self._collapsable_frame, stage) if len(self._transform_widget._widgets) > 0: self._any_item_visible = True else: # OM-51604 When no xformOpOrder element nor xformOp attributes, a special widget and button for it label_style = {"font_size":18} with ui.VStack(spacing=8): if len(self._payload) == 1: ui.Label("This prim has no transforms", style=label_style, alignment=ui.Alignment.CENTER) ui.Button(f'{_get_plus_glyph()} Add Transforms', clicked_fn=self._on_add_transform) elif all_empty_xformop == False: ui.Label("The selected prims have no common transforms to display", style=label_style, alignment=ui.Alignment.CENTER) else: ui.Label("None of the selected prims has transforms", style=label_style, alignment=ui.Alignment.CENTER) ui.Button(f'{_get_plus_glyph()} Add Transforms', clicked_fn=self._on_add_transform) if self._models is None: self._models = defaultdict(list) # Register the Copy/Paste/Reset All content context menu self._build_header_context_menu('Tranform') @Trace.TraceFunction def _on_usd_changed(self, notice, stage): if stage != self._payload.get_stage(): return for path in notice.GetChangedInfoOnlyPaths(): # if anyone changes the xformOpOrder of the current prim rebuild the collapsable frame if str(path).split(".")[-1] == "xformOpOrder" and path.GetPrimPath() in self._payload: super().request_rebuild() return super()._on_usd_changed(notice, stage) def _build_frame_header(self, collapsed, text: str, id: str = None): """Custom header for CollapsableFrame""" if id is None: id = text if collapsed: alignment = ui.Alignment.RIGHT_CENTER width = 5 height = 7 else: alignment = ui.Alignment.CENTER_BOTTOM width = 7 height = 5 header_stack = ui.HStack(spacing=8) with header_stack: with ui.VStack(width=0): ui.Spacer() ui.Triangle( style_type_name_override="CollapsableFrame.Header", width=width, height=height, alignment=alignment ) ui.Spacer() ui.Label(text, style_type_name_override="CollapsableFrame.Header", width = ui.Fraction(1)) button_style = { "Button.Image": { "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER, }, } if self._offset_mode: defaultStyle = get_style() label_style = defaultStyle.get("CollapsableFrame.Header", {}) label_style.update({"color": 0xFFFFC734}) ui.Label("Offset", style=label_style, width = ui.Fraction(1)) ui.Spacer(width = ui.Fraction(5)) button_style["Button.Image"]["image_url"] = "${glyphs}/offset_active_dark.svg" else: ui.Spacer(width = ui.Fraction(6)) button_style["Button.Image"]["image_url"] = "${glyphs}/offset_dark.svg" with ui.ZStack(content_clipping = True, width=25, height=25): ui.Button("", style = button_style, clicked_fn = self._toggle_offset_mode, identifier = "offset_mode_toggle", tooltip = "Toggle offset mode") def show_attribute_context_menu(b): if b != 1: return event = GroupHeaderContextMenuEvent(group_id=id, payload=[]) GroupHeaderContextMenu.on_mouse_event(event) header_stack.set_mouse_pressed_fn(lambda x, y, b, _: show_attribute_context_menu(b)) def _toggle_offset_mode(self): self._offset_mode = not self._offset_mode self.request_rebuild() def _toggle_link_scale(self): self._link_scale = not self._link_scale self.request_rebuild() def _on_add_transform(self): _add_trs_op(self._payload) self.request_rebuild() def _build_header_context_menu(self, group_id: str): #------Copy All Context Menu-------- def can_copy(object): # Only support single selection copy return len(self._payload) == 1 def on_copy(object): prim = self._get_prim(self._payload[-1]) xformOpOrderAttr = prim.GetAttribute("xformOpOrder") if not xformOpOrderAttr: return xformOpOrder = xformOpOrderAttr.Get() visited_models = set() properties_to_copy: Dict[Sdf.Path, Any] = dict() for models in self._models.values(): for model in models: if model in visited_models: continue visited_models.add(model) # Skip "Mixed" if model.is_ambiguous(): continue paths = model.get_property_paths() if paths: # No need to copy single channel model. Each vector attribute also has a GfVecAttributeModel if isinstance(model, GfVecAttributeSingleChannelModel): continue properties_to_copy[paths[-1]] = model.get_value() if properties_to_copy: properties_to_copy[Sdf.Path(xformOpOrderAttr.GetName())] = xformOpOrder set_group_properties_clipboard(properties_to_copy) menu = { "name": f'Copy All Property Values in Transform', "show_fn": lambda object: True, "enabled_fn": can_copy, "onclick_fn": on_copy, } self._group_menu_entries.append(self._register_header_context_menu_entry(menu, 'Transform')) #------Paste All Context Menu-------- def can_paste(object): # Only support single selection copy properties_to_paste = get_group_properties_clipboard() if not properties_to_paste: return False # Can't paste if the copied content doesn't have xformOpOrder key sourceXformOpOrderValue = properties_to_paste[Sdf.Path("xformOpOrder")] if sourceXformOpOrderValue is None: return False prim = self._get_prim(self._payload[-1]) if not prim: return False xformOpOrderAttr = prim.GetAttribute("xformOpOrder") # Can't paste if the target prim doesn't have xformOpOrder if not xformOpOrderAttr: return False targetXformOpOrderValue = xformOpOrderAttr.Get() # Can't paste if the copied content and target prim's xformOpOrder doesn't match if not targetXformOpOrderValue or sourceXformOpOrderValue != targetXformOpOrderValue: return False return True def on_paste(object): properties_to_copy = get_group_properties_clipboard() if not properties_to_copy: return unique_model_prim_paths: Set[Sdf.Path] = set() for prop_path in self._models: unique_model_prim_paths.add(prop_path.GetPrimPath()) with omni.kit.undo.group(): try: for path, value in properties_to_copy.items(): for prim_path in unique_model_prim_paths: paste_to_model_path = prim_path.AppendProperty(path.name) models = self._models.get(paste_to_model_path, []) for model in models: # No need to paste single channel model. Each vector attribute also has a GfVecAttributeModel if isinstance(model, GfVecAttributeSingleChannelModel): continue else: model.set_value(value) except Exception as e: carb.log_error(f"on_paste error:{traceback.format_exc()}") menu = { "name": f'Paste All Property Values to Transform', "show_fn": lambda object: True, "enabled_fn": can_paste, "onclick_fn": on_paste, } self._group_menu_entries.append(self._register_header_context_menu_entry(menu, 'Transform')) #------Reset All Context Menu------ def can_reset(object): for models in self._models.values(): for model in models: if model.is_different_from_default(): return True return False def on_reset(object): for models in self._models.values(): for model in models: model.set_default() menu = { "name": f'Reset All Property Values in Transform', "show_fn": lambda object: True, "enabled_fn": can_reset, "onclick_fn": on_reset, } self._group_menu_entries.append(self._register_header_context_menu_entry(menu, 'Transform'))
12,429
Python
39.357143
145
0.561107
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_builder.py
from queue import Empty from re import T from typing import Any import weakref import asyncio import os, functools, sys from abc import ABC, abstractmethod from enum import Enum from functools import partial import carb import omni.ui as ui import omni.ext import omni.usd import omni.timeline import omni.kit.commands import carb.settings from omni.hydra.scene_api import * from pxr import Gf, Tf, Vt, Usd, Sdf, UsdGeom from pathlib import Path from collections import defaultdict from omni.kit.property.usd.usd_attribute_model import ( FloatModel, UsdBase, UsdAttributeModel, GfVecAttributeModel, GfVecAttributeSingleChannelModel, GfMatrixAttributeModel, GfQuatAttributeModel, GfQuatEulerAttributeModel, ) from .transform_model import VecAttributeModel from omni.kit.widget.highlight_label import HighlightLabel from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder from omni.kit.context_menu import * from .transform_commands import * from . import xform_op_utils # Settings constants from omni.kit.window.toolbar TRANSFORM_OP_SETTING = "/app/transform/operation" TRANSFORM_OP_MOVE = "move" TRANSFORM_OP_ROTATE = "rotate" TRANSFORM_OP_SCALE = "scale" TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode" TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode" TRANSFORM_MODE_GLOBAL = "global" TRANSFORM_MODE_LOCAL = "local" LABEL_PADDING = 128 ICON_PATH = "" quat_view_button_style = { "Button:hovered": {"background_color": 0xFF575757}, "Button": {"background_color": 0xFF333333, "padding": 0, "stack_direction": ui.Direction.RIGHT_TO_LEFT}, "Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Button.Tooltip": {"color": 0xFF9E9E9E}, "Button.Image": {"color": 0xFFFFCC99, "alignment": ui.Alignment.CENTER}, } euler_view_button_style = { "Button:hovered": {"background_color": 0xFF23211F}, "Button": {"background_color": 0xFF23211F, "padding": 0, "stack_direction": ui.Direction.RIGHT_TO_LEFT}, "Button.Label": {"color": 0xFFA07D4F, "alignment": ui.Alignment.LEFT_CENTER}, "Button.Tooltip": {"color": 0xFF9E9E9E}, "Button.Image": {"color": 0xFFFFCC99, "alignment": ui.Alignment.CENTER}, } class USDXformOpWidget: def __init__( self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs=None, ): self._prim_paths = prim_paths self._collapsable_frame = collapsable_frame self._stage = stage self._attr_path = attr_path self._op_name = op_name self._is_valid_op = is_valid_op self._op_order_attr_path = op_order_attr_path self._op_order_index = op_order_index self._model = None self._right_click_menu = None self._label_kwargs = label_kwargs if label_kwargs is not None else {} self.rebuild() def __del__(self): self._prim_paths = None self._collapsable_frame = None self._stage = None self._attr_path = None self._op_name = None self._is_valid_op = False self._op_order_attr_path = None self._op_order_index = -1 if self._model is not None: if isinstance(self._model, list): for model in self._model: model.clean() else: self._model.clean() self._model = None self._right_click_menu = None def rebuild(self): pass def _create_inverse_widgets(self): # Not create inverse widgets for non-op attribute. if self._op_name is None: return is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) if is_inverse_op: ui.Label("¯¹") ''' I don't think this is used def _inverse_op(self): if self._op_order_attr_path is not None and self._op_order_index > -1: order_attr = self._stage.GetObjectAtPath(self._op_order_attr_path) if order_attr: with Sdf.ChangeBlock(): op_order = order_attr.Get() if self._op_order_index < len(op_order): op_name = op_order.__getitem__(self._op_order_index) if op_name == self._op_name: is_inverse_op = xform_op_utils.is_inverse_op(op_name) inverse_op_name = xform_op_utils.get_inverse_op_Name(op_name, not is_inverse_op) self._op_name = inverse_op_name op_order.__setitem__(self._op_order_index, inverse_op_name) order_attr.Set(op_order) # self._window().rebuild_window() self._collapsable_frame.rebuild() ''' def _add_key(self): if self._attr_path is None or self._stage is None: return attr = self._stage.GetObjectAtPath(self._attr_path) if attr: timeline = omni.timeline.get_timeline_interface() current_time = timeline.get_current_time() current_time_code = Usd.TimeCode( omni.usd.get_frame_time_code(current_time, self._stage.GetTimeCodesPerSecond()) ) if omni.usd.attr_has_timesample_on_key(attr, current_time_code): return if attr: omni.usd.copy_timesamples_from_weaker_layer(self._stage, attr) curr_value = attr.Get(current_time_code) if not curr_value: type_name = attr.GetTypeName() value_type = type(type_name.defaultValue) curr_value = value_type(attr_default_value) new_target = self._stage.GetEditTargetForLocalLayer(self._stage.GetEditTarget().GetLayer()) with Usd.EditContext(self._stage, new_target): attr.Set(curr_value, current_time_code) def _delete_op_only(self): if self._op_order_attr_path is not None and self._op_order_index > -1: omni.kit.commands.execute( "RemoveXformOp", op_order_attr_path=self._op_order_attr_path, op_name=self._op_name, op_order_index=self._op_order_index, ) def _delete_op_and_attribute(self): if self._op_order_attr_path is not None and self._op_order_index > -1: omni.kit.commands.execute( "RemoveXformOpAndAttrbute", op_order_attr_path=self._op_order_attr_path, op_name=self._op_name, op_order_index=self._op_order_index, ) omni.kit.window.property.get_window()._window.frame.rebuild() def _delete_non_op_attribute(self): if self._stage is not None and self._op_name is None and self._attr_path is not None: omni.kit.commands.execute("RemoveProperty", prop_path=self._attr_path.pathString) omni.kit.window.property.get_window()._window.frame.rebuild() def _add_non_op_attribute_to_op(self): if self._stage is not None and self._op_name is None and self._attr_path is not None: omni.kit.commands.execute("EnableXformOp", op_attr_path=self._attr_path) # This is to toggle the value widgets for quaternion or euler angle def _on_display_orient_as_rotate(self): self._display_orient_as_rotate = not self._display_orient_as_rotate if self._settings: self._settings.set("/persistent/app/uiSettings/DisplayOrientAsRotate", self._display_orient_as_rotate) if self._display_orient_as_rotate is True: self._quat_view.visible = False self._euler_view.visible = True else: self._quat_view.visible = True self._euler_view.visible = False # The orient label(button) has a different style for two modes def _toggle_orient_button_style(self, button): # About to switch to raw mode if self._display_orient_as_rotate is True: button.set_style(euler_view_button_style) else: button.set_style(quat_view_button_style) def _on_orient_button_clicked(self, mouse_button, widget): if mouse_button != 0: return self._on_display_orient_as_rotate() self._toggle_orient_button_style(widget) def _show_right_click_menu(self, button): if button != 1: return if self._right_click_menu is None: self._right_click_menu = ui.Menu("Right Menu") self._right_click_menu.clear() with self._right_click_menu: # ResetXformStack if xform_op_utils.is_reset_xform_stack_op(self._op_name): text = "Disable" if self._is_valid_op else "Disable Invalid Op" ui.MenuItem(text, triggered_fn=lambda: self._delete_op_only()) # valid/invalid Op elif self._op_name is not None and self._attr_path is not None: # ui.MenuItem("Inverse", triggered_fn=lambda: self._inverse_op()) text_op_only = "Disable" if self._is_valid_op else "Disable Invalid Op" text_op_attr = "Delete" if self._is_valid_op else "Delete Invalid Op" ui.MenuItem(text_op_only, triggered_fn=lambda: self._delete_op_only()) ui.MenuItem(text_op_attr, triggered_fn=lambda: self._delete_op_and_attribute()) # non-op attribute elif self._op_name is None and self._attr_path is not None: ui.MenuItem("Delete", triggered_fn=lambda: self._delete_non_op_attribute()) ui.MenuItem("Enable", triggered_fn=lambda: self._add_non_op_attribute_to_op()) # no-attribute op elif self._op_name is not None and self._attr_path is None: ui.MenuItem("Disable Invalid Op", triggered_fn=lambda: self._delete_op_only()) self._right_click_menu.show() def _create_multi_float_drag_matrix_with_labels(self, model, comp_count, min, max, step, labels): # RECT_WIDTH = 13 SPACING = 4 with ui.ZStack(): with ui.HStack(): ui.Spacer(width=RECT_WIDTH) value_widget = ui.MultiFloatDragField( model, name="multivalue", min=min, max=max, step=step, h_spacing=RECT_WIDTH + SPACING, v_spacing=2 ) with ui.HStack(): for i in range(comp_count): if i != 0: ui.Spacer(width=SPACING) label = labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": label[1]}) ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() mixed_overlay = [] with ui.VStack(): for i in range(comp_count): with ui.HStack(): for i in range(comp_count): ui.Spacer(width=RECT_WIDTH) mixed_overlay.append(UsdPropertiesWidgetBuilder._create_mixed_text_overlay()) UsdPropertiesWidgetBuilder._create_control_state(model, value_widget, mixed_overlay) class TransformWatchModel(ui.AbstractValueModel): def __init__(self, component_index, stage): super(TransformWatchModel, self).__init__() self._usd_context = omni.usd.get_context() self._component_index = component_index self._value = 0.0 self._selection = self._usd_context.get_selection() self._prim_paths = self._selection.get_selected_prim_paths() self._on_usd_changed() self.usd_watcher = omni.usd.get_watcher() self._subscription = self.usd_watcher.subscribe_to_change_info_path( self._prim_paths[0], self._on_usd_changed ) def clean(self): """Should be called when the extension is unloaded or reloaded""" self._usd_context = None self._selection = None self._prim_paths = None self._subscription.unsubscribe() self._subscription = None def _on_usd_changed(self, path=None): #pragma no cover wgs_coords = get_wgs84_coords("", self._prim_paths[0]) if len(wgs_coords) > 0: self.set_value(wgs_coords[self._component_index]) def get_value_as_float(self) -> float: ''' Returns the value as a float ''' return self._value or 0.0 def get_value_as_string(self) -> str: ''' Returns the float value as a string ''' if self._value is None: return "" # General format. This prints the number as a fixed-point # number, unless the number is too large, in which case it # switches to 'e' exponent notation. return "{0:g}".format(self._value) def set_value(self, new_value: Any) -> None: ''' Attempts to cast new_value to a float and set it to the internal value ''' try: value = float(new_value) except ValueError: value = 0.0 if value != self._value: self._value = value self._value_changed() class USDXformOpTranslateWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Translate" if suffix: label_name = label_name + ":" + suffix return label_name def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:translate"): carb.log_warn(f"Object {self._path} is not an xformOp:translate attribute ") return is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) suffix = xform_op_utils.get_op_name_suffix(attr_name) if is_inverse_op and suffix == "pivot": return label_name = self.display_name(attr_name) # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) self._model = [] for i in range(3): self._model.append( GfVecAttributeSingleChannelModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], i, False, metadata, False, ) ) vec_model = GfVecAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 3, type_name.type, False, metadata, ) if len(self._prim_paths) == 1: setattr(vec_model,'transform_widget', self) label = None with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it to disable or delete it." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) ui.Spacer(width=2) self._create_inverse_widgets() with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) kwargs = {"min": range_min, "max": range_max, "step": 1.0} UsdPropertiesWidgetBuilder._create_float_drag_per_channel_with_labels_and_control( models = self._model, metadata = metadata, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], kwargs = kwargs ) #The vec_model is useful when we set the key for all three components together self._model.append(vec_model) UsdPropertiesWidgetBuilder._create_attribute_context_menu(label, vec_model) wgs_coord = get_wgs84_coords("", self._prim_paths[0].pathString) if len(wgs_coord) > 0: #pragma no cover OM-112507 with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("WGS84", name="title", tooltip=label_tooltip) ui.Spacer(width=2) with ui.HStack(): with ui.VStack(): all_axis = ["Lat", "Lon", "Alt"] colors = {"Lat": 0xFF5555AA, "Lon": 0xFF76A371, "Alt": 0xFFA07D4F} component_index = 0 for axis in all_axis: with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("", name="title", tooltip=label_tooltip) with ui.ZStack(width=20): ui.Rectangle( width=20, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, name="wgs84_label", alignment=ui.Alignment.CENTER) # NOTE: Updating the WGS84 values does not update the transform translation, # so make the input fields read-only for now. # See https://nvidia-omniverse.atlassian.net/browse/OM-64348 ui.FloatDrag(TransformWatchModel(component_index, self._stage), enabled=False) component_index = component_index + 1 super().rebuild() class USDXformOpRotateWidget(USDXformOpWidget): ROTATE_AXIS_ORDER_MAP = { "xformOp:rotateXYZ": ["X", "Y", "Z"], "xformOp:rotateXZY": ["X", "Z", "Y"], "xformOp:rotateYXZ": ["Y", "X", "Z"], "xformOp:rotateYZX": ["Y", "Z", "X"], "xformOp:rotateZXY": ["Z", "X", "Y"], "xformOp:rotateZYX": ["Z", "Y", "X"], } ROTATE_ORDERS = ["XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX"] @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Rotate" if suffix: label_name = label_name + ":" + suffix return label_name def __init__(self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs=None): self._rotate_order_drop_down_menu = None super().__init__(prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs) def __del__(self): super().__del__() self._rotate_order_drop_down_menu = None def get_rotation_order_index(order): return USDXformOpRotateWidget.ROTATE_ORDERS.index(order) def _change_rotation_order(self, desired_order_index): attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:rotate"): carb.log_warn(f"Object {self._path} is not an xformOp:rotate attribute ") return is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) suffix = xform_op_utils.get_op_name_suffix(attr_name) current_order_index = 5 rotate_names = attr.SplitName() if len(rotate_names) > 1: rotate_order = rotate_names[1].split("rotate", 1)[1] current_order_index = USDXformOpRotateWidget.get_rotation_order_index(rotate_order) if current_order_index == desired_order_index: return # desired_order = "XYZ" desired_order = USDXformOpRotateWidget.ROTATE_ORDERS[desired_order_index] desired_attr_name = "xformOp:rotate" + desired_order if suffix is not None: desired_attr_name += ":" + suffix desired_op_name = desired_attr_name if not is_inverse_op else "!invert!" + desired_attr_name omni.kit.commands.execute( "ChangeRotationOp", src_op_attr_path=self._attr_path, op_name=self._op_name, dst_op_attr_name=desired_attr_name, is_inverse_op=is_inverse_op, auto_target_layer = True ) # after we finish the rotation change "close" the rotation drop-down menu if self._rotate_order_drop_down_menu: self._rotate_order_drop_down_menu.visible = False # A callback to generate a drop-down-menu-like popup window i.e. self._rotate_order_drop_down_menu # it is used to select & update the rotation order, e.g. XYZ, XZY, ZYX etc. def _on_mouse_click(self,button,parent, order): #only suitable for mouse left click if button != 0: return #Use a popup window to act as a drop-down menu self._rotate_order_drop_down_menu = ui.Window("RotationOrder", width=60, height=130, position_x=parent.screen_position_x, position_y=parent.screen_position_y+parent.computed_height,flags = ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR) rotate_check_box_style = { "": {"background_color": 0x0, "image_url": f"{ICON_PATH}/radio_off.svg", "image_width":32, "image_height":32}, ":checked": {"image_url": f"{ICON_PATH}/radio_on.svg"} } with self._rotate_order_drop_down_menu.frame: collection = ui.RadioCollection() with ui.VStack(): for index in range(len(USDXformOpRotateWidget.ROTATE_ORDERS)): rotate_order = USDXformOpRotateWidget.ROTATE_ORDERS[index] #OM-94393 let the radio button decide the height and style with ui.HStack(mouse_pressed_fn=(lambda x, y, b, m, index=index: self._change_rotation_order(index)), height=0): ui.RadioButton(style=rotate_check_box_style, radio_collection=collection, aligment=ui.Alignment.LEFT, height=20) ui.Label(rotate_order) if rotate_order == order: collection.model.set_value(index) def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) # if attr.GetResolveInfo().ValueIsBlocked(): # return attr_name = attr.GetName() if not attr_name.startswith("xformOp:rotate"): carb.log_warn(f"Object {self._path} is not an xformOp:rotate attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) rotate_names = attr.SplitName() rotate_order = "ZYX" if len(rotate_names) > 1: rotate_order = rotate_names[1].split("rotate", 1)[1] # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = [] for i in range(3): self._model.append( GfVecAttributeSingleChannelModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], i, False, metadata, False, ) ) vec_model = GfVecAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 3, type_name.type, False, metadata, ) if len(self._prim_paths) == 1: setattr(vec_model,'transform_widget', self) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) label = None with ui.HStack(): if len(self._prim_paths) == 1: with ui.ZStack(width=LABEL_PADDING): label_tooltip = label_tooltip + "\nRight click it to disable or delete it. \nLeft click it to change the rotate order, default is XYZ." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) # We use a label + a triangle to hack a combo box that are closer to the design label_h_stack = ui.HStack(width=LABEL_PADDING) label_h_stack.set_mouse_pressed_fn(lambda x, y, b, m, order=rotate_order, parent_widget=label_h_stack: self._on_mouse_click(b,parent_widget,order)) with label_h_stack: label = HighlightLabel( label_name, name="title", tooltip=label_tooltip, width = 35, **self._label_kwargs, ) self._create_inverse_widgets() ui.Spacer(width=5) # use this triangle to simulate a combo box with ui.VStack(): ui.Spacer(height=10) ui.Triangle(name="default",width=8,height=6,style={"background_color":0xFF9E9E9E},alignment=ui.Alignment.CENTER_BOTTOM) else: with ui.HStack(width=LABEL_PADDING): label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) ui.Spacer() self._create_inverse_widgets() with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) kwargs = {"min": range_min, "max": range_max, "step": 1.0} UsdPropertiesWidgetBuilder._create_float_drag_per_channel_with_labels_and_control( models = self._model, metadata = metadata, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], kwargs = kwargs ) #The vec_model is useful when we set the key for all three components together self._model.append(vec_model) UsdPropertiesWidgetBuilder._create_attribute_context_menu(label, vec_model) #this class is used for rotateX, rotateY, rotateZ, but it's not working properly, and produce error when displayed. # https://omniverse-jirasw.nvidia.com/browse/OMFP-2491 #disabling coverage for this code class USDXformOpRotateScalarWidget(USDXformOpWidget): # pragma: no cover @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Rotate" if suffix: label_name = label_name + ":" + suffix return label_name def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) # if attr.GetResolveInfo().ValueIsBlocked(): # return attr_name = attr.GetName() if not attr_name.startswith("xformOp:rotate"): carb.log_warn(f"Object {self._path} is not an xformOp:rotate attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) rotate_names = attr.SplitName() rotate_order = "X" if len(rotate_names) > 1: rotate_order = rotate_names[1].split("rotate", 1)[1] # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = UsdAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], False, metadata ) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it to disable or delete it. " # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) self._create_inverse_widgets() ui.Spacer(width=2) stack_names = {"X":"rotate_scalar_stack_x", "Y":"rotate_scalar_stack_y", "Z":"rotate_scalar_stack_z"} rotate_scalar_stack = ui.HStack(identifier = stack_names[rotate_order]) with rotate_scalar_stack: colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F} with ui.ZStack(): with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) widget_kwargs = {"model": self._model, "step": 1} if range_min < range_max: widget_kwargs["min"] = range_min widget_kwargs["max"] = range_max UsdPropertiesWidgetBuilder._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs) UsdPropertiesWidgetBuilder._create_control_state(self._model) with ui.HStack(): with ui.ZStack(width=14): ui.Rectangle( name="vector_label", style={ "background_color": colors[rotate_order], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(rotate_order, name="vector_label", alignment=ui.Alignment.CENTER) class USDXformOpScaleWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Scale" if suffix: label_name = label_name + ":" + suffix return label_name def __init__( self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, parent_widget, label_kwargs=None ): self._parent_widget = parent_widget super().__init__( prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs ) def rebuild(self): # The scale widget uses a modified version of the single channel model that supports # scaling each component of the vector uniformly. # If link_channels is False, the single channel model behaves as usual. class GfVecLinkableModel(GfVecAttributeSingleChannelModel): def __init__( self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], channel_index: int, self_refresh: bool, metadata: dict, change_on_edit_end=False, link_channels=False, **kwargs ): self._link_channels = link_channels super().__init__(stage, attribute_paths, channel_index, self_refresh, metadata, change_on_edit_end, **kwargs) def set_value(self, value): if self._link_channels: vec_value = copy.copy(self._value) for i in range(3): vec_value[i] = value if UsdBase.set_value(self, vec_value, -1): self._value_changed() else: super().set_value(value) def set_default(self, comp=-1): if self._link_channels: value = self._default_value[self._channel_index] vec_value = copy.copy(self._value) for i in range(3): vec_value[i] = value if UsdBase.set_value(self, vec_value, -1): self._value_changed() else: super().set_default(comp) attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:scale"): carb.log_warn(f"Object {self._path} is not an xformOp:scale attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = [] for i in range(3): self._model.append( GfVecLinkableModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], i, False, metadata, False, self._parent_widget._link_scale ) ) vec_model = GfVecAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 3, type_name.type, False, metadata, ) if len(self._prim_paths) == 1: setattr(vec_model,'transform_widget', self) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) label = None with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it for more options." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: label = HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) self._create_inverse_widgets() if self._parent_widget._link_scale: button_style = { "color": 0xFF34B5FF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_on.svg"}, ":hovered": {"color": 0xFFACDCF9} } else: button_style = { "color": 0x66FFFFFF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_off.svg"}, ":hovered": {"color": 0xFFFFFFFF} } with ui.ZStack(content_clipping = True, width=25, height=25): ui.Button("", style = button_style, clicked_fn = self._parent_widget._toggle_link_scale, identifier = "toggle_link_scale", tooltip = "Toggle link scale") ui.Spacer(width=70) scale_stack = ui.HStack(identifier = "scale_t_stack") with scale_stack: range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) kwargs = {"min": range_min, "max": range_max, "step": 1.0} UsdPropertiesWidgetBuilder._create_float_drag_per_channel_with_labels_and_control( models = self._model, metadata = metadata, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], kwargs = kwargs ) #The vec_model is useful when we set the key for all three components together self._model.append(vec_model) UsdPropertiesWidgetBuilder._create_attribute_context_menu(label, vec_model) class USDXformOpOrientWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Orient" if suffix: label_name = label_name + ":" + suffix return label_name def __init__( self, prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs=None, ): self._settings = carb.settings.get_settings() if self._settings: if self._settings.get("/persistent/app/uiSettings/DisplayOrientAsRotate") is None: self._settings.set_default_bool("/persistent/app/uiSettings/DisplayOrientAsRotate", True) self._display_orient_as_rotate = self._settings.get_as_bool( "/persistent/app/uiSettings/DisplayOrientAsRotate" ) super().__init__( prim_paths, collapsable_frame, stage, attr_path, op_name, is_valid_op, op_order_attr_path, op_order_index, label_kwargs, ) def _build_orient_widgets(self, attr, attr_name, type_name, label_name, label_tooltip, metadata): self._model = GfQuatAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], type_name.type, False, metadata ) with ui.HStack(): kwargs = {"min": -1, "max": 1, "step": 0.01} value_widget, mixed_overlay = UsdPropertiesWidgetBuilder._create_multi_float_drag_with_labels( self._model, comp_count=4, labels=[("W", 0xFFAA5555), ("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], **kwargs, ) value_widget.identifier = f"orient_{attr_name}" UsdPropertiesWidgetBuilder._create_control_state(self._model, value_widget, mixed_overlay) def _build_euler_widgets(self, attr, attr_name, type_name, label_name, label_tooltip, metadata): self._euler_model = GfQuatEulerAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], type_name.type, False, metadata ) with ui.HStack(): kwargs = {"min": -360, "max": 360, "step": 1} value_widget, mixed_overlay = UsdPropertiesWidgetBuilder._create_multi_float_drag_with_labels( self._euler_model, comp_count=3, labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], **kwargs, ) value_widget.identifier = f"euler_{attr_name}" UsdPropertiesWidgetBuilder._create_control_state(self._euler_model, value_widget, mixed_overlay) def _build_header(self, attr, attr_name, type_name, label_name, label_tooltip, metadata): with ui.ZStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: label_tooltip = label_tooltip + "\nDisplay Orient As Euler Angles. \nRight click to disable or delete it. \nLeft click to switch between Orient & Euler Angles." # A black rect background indicates the Orient is not original data format _rect = ui.Rectangle( style={ "Rectangle:hovered": {"background_color": 0xFF444444}, "Rectangle": {"background_color": 0xFF333333}, }, tooltip=label_tooltip, ) # _rect = ui.Rectangle(tooltip=label_tooltip) _rect.set_mouse_pressed_fn(lambda x, y, b, m: self._show_right_click_menu(b)) # TODO: Replace this hack when OM-24290 is fixed with ui.ZStack(): _button = ui.Button( label_name, name="title", width=50, tooltip=label_tooltip if len(self._prim_paths) > 1 else "", style=euler_view_button_style if self._display_orient_as_rotate else quat_view_button_style, ) _button.set_mouse_pressed_fn( lambda x, y, b, m, widget=_button: self._on_orient_button_clicked(b, widget) ) self._create_inverse_widgets() with ui.HStack(): ui.Spacer(width=35) ui.Image(f"{ICON_PATH}/orient_button.svg", width=10, alignment=ui.Alignment.CENTER) def rebuild(self): # attr & attr_name attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:orient"): carb.log_warn(f"Object {self._path} is not an xformOp:orient attribute ") return # metadata metadata = attr.GetAllMetadata() # type_name type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) # label_name label_name = self.display_name(attr_name) # label_tooltip label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) with ui.HStack(): self._build_header(attr, attr_name, type_name, label_name, label_tooltip, metadata) # Create two views, Quaternion view & Euler Angle view # self._display_orient_as_rotate True: Euler Angle view, False: Quaternion view with ui.ZStack(): # Quaternion view is default on self._quat_view = ui.Frame(visible=False if self._display_orient_as_rotate else True) with self._quat_view: self._build_orient_widgets(attr, attr_name, type_name, label_name, label_tooltip, metadata) # Euler view is default off self._euler_view = ui.Frame(visible=True if self._display_orient_as_rotate else False) with self._euler_view: self._build_euler_widgets(attr, attr_name, type_name, label_name, label_tooltip, metadata) class USDXformOpTransformWidget(USDXformOpWidget): @classmethod def display_name(cls, attr_name: str) -> str: suffix = xform_op_utils.get_op_name_suffix(attr_name) label_name = "Transform" if suffix: label_name = label_name + ":" + suffix return label_name def rebuild(self): attr = self._stage.GetObjectAtPath(self._attr_path) attr_name = attr.GetName() if not attr_name.startswith("xformOp:transform"): carb.log_warn(f"Object {self._path} is not an xformOp:transform attribute ") return # is_inverse_op = False if self._op_name is None else xform_op_utils.is_inverse_op(self._op_name) label_name = self.display_name(attr_name) # label_tooltip = get_attribute_type_tooltip(attr) + " " + attr.GetName() metadata = attr.GetAllMetadata() type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey)) self._model = GfMatrixAttributeModel( self._stage, [path.AppendProperty(attr_name) for path in self._prim_paths], 4, type_name.type, False, metadata, ) label_tooltip = UsdPropertiesWidgetBuilder._generate_tooltip_string(attr.GetName(), metadata) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): if len(self._prim_paths) == 1: with ui.ZStack(): label_tooltip = label_tooltip + "\nRight click it to disable or delete it." # This rectangle is act as a hover hint helper ui.Rectangle( style={":hovered": {"background_color": 0xFF444444}, "background_color": 0xFF333333}, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) else: HighlightLabel(label_name, name="title", tooltip=label_tooltip, **self._label_kwargs) self._create_inverse_widgets() ui.Spacer(width=2) with ui.HStack(): range_min, range_max = UsdPropertiesWidgetBuilder._get_attr_value_range(metadata) # TODO: make step default to 1.0 before the adaptive stepping solution is available step = 1.0 self._create_multi_float_drag_matrix_with_labels( self._model, 4, range_min, range_max, step, [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFAA5555)], ) wgs_coord = get_wgs84_coords("", self._prim_paths[0].pathString) if len(wgs_coord) > 0: #pragma no cover OM-112507 with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("WGS84", name="title", tooltip=label_tooltip) ui.Spacer(width=2) with ui.HStack(): with ui.VStack(): all_axis = ["Lat", "Lon", "Alt"] colors = {"Lat": 0xFF5555AA, "Lon": 0xFF76A371, "Alt": 0xFFA07D4F} component_index = 0 for axis in all_axis: with ui.HStack(): with ui.HStack(width=LABEL_PADDING): label = ui.Label("", name="title", tooltip=label_tooltip) with ui.ZStack(width=20): ui.Rectangle( width=20, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, name="wgs84_label", alignment=ui.Alignment.CENTER) # NOTE: Updating the WGS84 values does not update the transform translation, # so make the input fields read-only for now. # See https://nvidia-omniverse.atlassian.net/browse/OM-64348 ui.FloatDrag(TransformWatchModel(component_index, self._stage), enabled=False) component_index = component_index + 1 class USDResetXformStackWidget(USDXformOpWidget): def rebuild(self): is_reset_xform_stack_op = xform_op_utils.is_reset_xform_stack_op(self._op_name) if not is_reset_xform_stack_op: return label_name = "ResetXformStack" label_tooltip = "Invalid all above xformOp and parent transform. Calulate world transform from the op below." self._model = None with ui.HStack(): with ui.HStack(width=LABEL_PADDING): ui.Label( label_name, name="title", tooltip=label_tooltip, mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b)), ) ui.Spacer(width=5) with ui.HStack(): with ui.VStack(): ui.Spacer() color = 0xFF888888 if self._is_valid_op else 0xFF444444 ui.Line( name="ResetXformStack", height=2, style={"color": color, "border_width": 0.5, "alignment": ui.Alignment.BOTTOM}, alignment=ui.Alignment.BOTTOM, ) ui.Spacer() class USDNoAttributeOpWidget(USDXformOpWidget): def rebuild(self): if self._op_name is None: return label_name = self._op_name self._model = None is_valid_op_name = xform_op_utils.is_valid_op_name(self._op_name) op_attr_name = xform_op_utils.get_op_attr_name(self._op_name) label_error = ( f"Could not find attribute {op_attr_name} for this xformOp." if is_valid_op_name else "Invalid xformOp name!" ) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): ui.Label(label_name, name="title", mouse_pressed_fn=(lambda x, y, b, m: self._show_right_click_menu(b))) ui.Spacer(width=5) with ui.HStack(): ui.Label(label_error, name="title") class OperationTypes(Enum): ADD = 0 MULTIPLY = 1 INVALID = 2 class TransformWidgets: def __init__(self, parent_widget): self._settings = carb.settings.get_settings() self._clear_widgets() self._parent_widget = parent_widget self._offset_index = -1 self._old_transform = "" self._active_fields = 0 self._dragging = False self._tab_swap = 0 def __del__(self): self._clear_widgets() def _clear_widgets(self): self._stage = None self._widgets = [] self._models = defaultdict(list) def _create_xform_op_widget( self, prim_paths, collapsable_frame, stage, attr, op_name=None, is_valid_op=False, op_order_attr=None, op_order_index=-1, ): op_order_path = op_order_attr.GetPath() if op_order_attr is not None and op_order_attr else None if xform_op_utils.is_reset_xform_stack_op(op_name): return USDResetXformStackWidget( prim_paths, collapsable_frame, stage, None, op_name, is_valid_op, op_order_path, op_order_index ) if not attr: return USDNoAttributeOpWidget( prim_paths, collapsable_frame, stage, None, op_name, is_valid_op, op_order_path, op_order_index ) attr_name = attr.GetName() def match(label): return self._parent_widget._filter.matches(label) highlight = self._parent_widget._filter.name label_kwargs = {"highlight": highlight} if attr_name.startswith("xformOp:translate") and match(USDXformOpTranslateWidget.display_name(attr_name)): return USDXformOpTranslateWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif attr_name.startswith("xformOp:rotate") and match(USDXformOpRotateWidget.display_name(attr_name)): op_type_name = xform_op_utils.get_op_type_name(attr_name) if len(op_type_name.split("rotate", 1)[1]) == 3: return USDXformOpRotateWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif len(op_type_name.split("rotate", 1)[1]) == 1: return USDXformOpRotateScalarWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif attr_name.startswith("xformOp:orient") and match(USDXformOpOrientWidget.display_name(attr_name)): return USDXformOpOrientWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) elif attr_name.startswith("xformOp:scale") and match(USDXformOpScaleWidget.display_name(attr_name)): return USDXformOpScaleWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, self._parent_widget, label_kwargs, ) elif attr_name.startswith("xformOp:transform") and match(USDXformOpTransformWidget.display_name(attr_name)): return USDXformOpTransformWidget( prim_paths, collapsable_frame, stage, attr.GetPath(), op_name, is_valid_op, op_order_path, op_order_index, label_kwargs, ) return None def _get_common_xformop(self, prim_paths): def _get_xformop_order(stage, prim_path): prim = stage.GetPrimAtPath(prim_path) if not prim: return [] order_attr = prim.GetAttribute("xformOpOrder") if not order_attr: return [] xform_op_order = order_attr.Get() if not xform_op_order: return [] return xform_op_order common_xformOp_order = [ \ "xformOp:translate","xformOp:scale","xformOp:rotateX", \ "xformOp:rotateY","xformOp:rotateZ","xformOp:rotateXYZ", \ "xformOp:rotateXZY","xformOp:rotateYXZ","xformOp:rotateYZX", \ "xformOp:rotateZXY","xformOp:rotateZYX","xformOp:orient","xformOp:transform" ] all_empty_xformOp = True for prim_path in prim_paths: xformOp_order = _get_xformop_order(self._stage, prim_path) common_xformOp_order = list(set(common_xformOp_order) & set(xformOp_order)) all_empty_xformOp &= (len(xformOp_order) == 0) return common_xformOp_order, all_empty_xformOp def _create_multi_string_with_labels(self, ui_widget, model, labels, comp_count): # This is similar to the multi_float_drag function above, but without USD backing and using a given single # field (draggable float and string, for offset mode we need to do some string parsing to look for math operations) RECT_WIDTH = 13 SPACING = 4 value_widget = [] with ui.ZStack(): with ui.HStack(): ui.Spacer(width=RECT_WIDTH) items = model.get_item_children(self) for i in range(comp_count): if i !=0: ui.Spacer(width=RECT_WIDTH) field = model.get_item_value_model(items[i], i) value_widget.append(ui_widget(field)) with ui.HStack(): for i in range(comp_count): if i != 0: ui.Spacer(width=SPACING) label = labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": label[1]}) ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() return value_widget # Two sets of fields are generated, FloatDrags are visible dragging and StringFields are visible during keyboard input # These functions ensure the correct fields are visible and active when single clicking, double clicking, and tab selecting def _on_double_click(self, transform): self._dragging = False float_widget = self._get_widget(transform)[0] string_widget = self._get_widget(transform)[1] for widget in float_widget: widget.visible = False for widget in string_widget: widget.visible = True async def focus(field): await omni.kit.app.get_app().next_update_async() field.focus_keyboard() string_widget[self._offset_index].focus_keyboard() asyncio.ensure_future(focus(string_widget[self._offset_index])) if self._tab_swap == 1: self._active_fields -= 1 def _on_press(self): self._dragging = True self._tab_swap = 0 if self._active_fields < 0: self._active_fields = 0 def _start_field_edit(self, index, transform): self._offset_index = index self._active_fields += 1 self._old_transform = transform self._settings.set(TRANSFORM_OP_SETTING, transform) float_widget = self._get_widget(transform)[0] if float_widget[index].visible == True and self._dragging == False: self._tab_swap += 1 self._on_double_click(transform) def _swapping(self, transform): if transform == self._old_transform: return False else: return True async def _end_string_edit(self, transform): self._active_fields -= 1 if self._swapping(transform): if self._get_widget(transform)[0][0].visible == False: for widget in self._get_widget(transform)[1]: widget.visible = False for widget in self._get_widget(transform)[0]: widget.visible = True # Swap back to FloatDrag fields if the user clicks off await asyncio.sleep(.3) if self._active_fields < 1: if self._get_widget(transform)[0][0].visible == False: for widget in self._get_widget(transform)[1]: widget.visible = False for widget in self._get_widget(transform)[0]: widget.visible = True def _get_widget(self, transform): if transform == TRANSFORM_OP_MOVE: return self._float_translate_widget, self._string_translate_widget elif transform == TRANSFORM_OP_ROTATE: return self._float_rotate_widget, self._string_rotate_widget else: return self._float_scale_widget, self._string_scale_widget def _get_offset_data(self, text: str): # See if input looks like "[op] [number]", for the four supported operations try: text = text.replace(" ", "") if len(text) > 0: operator = text[0] value = float(text[1:]) if operator == '*': return OperationTypes.MULTIPLY, value elif operator == '/': return OperationTypes.MULTIPLY, 1.0 / value elif operator == '+': return OperationTypes.ADD, value elif operator == '-': return OperationTypes.ADD, -value except ValueError: pass # If we didn't find an operation, see if the input is just a number try: value = float(text) return OperationTypes.ADD, value except ValueError: return OperationTypes.INVALID, 0.0 def _on_translate_offset(self, offset_text: str, index: int, stage: Usd.Stage, prim_paths: List[Sdf.Path]): operation, offset_value = self._get_offset_data(offset_text) if operation is OperationTypes.INVALID: carb.log_warn("Unrecognized input provided to offset field. No operation will be applied.") elif stage: with omni.kit.undo.group(): for path in prim_paths: prim = stage.GetPrimAtPath(path) prim_world_xform = omni.usd.get_world_transform_matrix(prim) success, scale_orient_mat, scale, rotation_mat, translation, persp_mat = prim_world_xform.Factor() scale_mat = Gf.Matrix4d().SetScale(scale) local = self._settings.get(TRANSFORM_MOVE_MODE_SETTING) is None or \ self._settings.get_as_string(TRANSFORM_MOVE_MODE_SETTING) != TRANSFORM_MODE_GLOBAL if operation is OperationTypes.ADD: if local: offset_vec = Gf.Vec3d([offset_value if i == index else 0 for i in range(3)]) offset_mat = Gf.Matrix4d().SetTranslate(offset_vec) translation_mat = Gf.Matrix4d().SetTranslate(translation) translation = (offset_mat * rotation_mat * translation_mat).ExtractTranslation() else: translation[index] += offset_value elif operation is OperationTypes.MULTIPLY: if local: offset_vec = Gf.Vec3d([offset_value if i == index else 1 for i in range(3)]) offset_mat = Gf.Matrix4d().SetScale(offset_vec) translation_mat = Gf.Matrix4d().SetTranslate(translation) # Rotate translation into local frame, apply the scale there, rotate back out translation = (translation_mat * rotation_mat.GetTranspose() * offset_mat * rotation_mat).ExtractTranslation() else: translation[index] *= offset_value translation_mat = Gf.Matrix4d().SetTranslate(translation) prim_world_xform = scale_orient_mat * scale_mat * scale_orient_mat.GetTranspose() * rotation_mat * translation_mat parent_world_xform = omni.usd.get_world_transform_matrix(prim.GetParent()) prim_local_xform = prim_world_xform * parent_world_xform.GetInverse() omni.kit.commands.execute("TransformPrimCommand", path = path, new_transform_matrix = prim_local_xform) asyncio.ensure_future(self._end_string_edit(TRANSFORM_OP_MOVE)) def _on_rotate_offset(self, offset_text: str, index: int, stage: Usd.Stage, prim_paths: List[Sdf.Path]): operation, offset_value = self._get_offset_data(offset_text) if operation is OperationTypes.INVALID: carb.log_warn("Unrecognized input provided to offset field. No operation will be applied.") elif stage: with omni.kit.undo.group(): for path in prim_paths: prim = stage.GetPrimAtPath(path) prim_world_xform = omni.usd.get_world_transform_matrix(prim) success, scale_orient_mat, scale, rotation_mat, translation, persp_mat = prim_world_xform.Factor() scale_mat = Gf.Matrix4d().SetScale(scale) local = self._settings.get(TRANSFORM_ROTATE_MODE_SETTING) is None or \ self._settings.get_as_string(TRANSFORM_ROTATE_MODE_SETTING) != TRANSFORM_MODE_GLOBAL if operation is OperationTypes.ADD: axis = Gf.Vec3d([1 if i == index else 0 for i in range(3)]) offset_r = Gf.Rotation(axis, offset_value) offset_mat = Gf.Matrix4d().SetRotate(offset_r.GetQuat()) if local: rotation_mat = offset_mat * rotation_mat else: rotation_mat = rotation_mat * offset_mat translation_mat = Gf.Matrix4d().SetTranslate(translation) prim_world_xform = scale_orient_mat * scale_mat * scale_orient_mat.GetTranspose() * rotation_mat * translation_mat parent_world_xform = omni.usd.get_world_transform_matrix(prim.GetParent()) prim_local_xform = prim_world_xform * parent_world_xform.GetInverse() omni.kit.commands.execute("TransformPrimCommand", path = path, new_transform_matrix = prim_local_xform) elif operation is OperationTypes.MULTIPLY: # rotation-multiply is unlike the other offsets because it we need to know the component of the # current rotation about a particular axis in order to scale it, but a rotation's component along # one axis can be different depending on the representation (e.g. different euler angle orderings). # Rather than deal with that, we'll just look for the prim's current rotation values # and scale the specified component. scale, rotation, order, translation = omni.usd.get_local_transform_SRT(prim) rotation[index] *= offset_value omni.kit.commands.execute("TransformPrimSRTCommand", path = path, new_rotation_euler = rotation) asyncio.ensure_future(self._end_string_edit(TRANSFORM_OP_ROTATE)) def _on_scale_offset(self, offset_text: str, index: int, stage: Usd.Stage, prim_paths: List[Sdf.Path]): operation, offset_value = self._get_offset_data(offset_text) if operation is OperationTypes.INVALID: carb.log_warn("Unrecognized input provided to offset field. No operation will be applied.") elif stage: with omni.kit.undo.group(): for path in prim_paths: prim = stage.GetPrimAtPath(path) prim_world_xform = omni.usd.get_world_transform_matrix(prim) success, scale_orient_mat, scale, rotation_mat, translation, persp_mat = prim_world_xform.Factor() if operation is OperationTypes.ADD: if self._parent_widget._link_scale: scale = ((scale[index] + offset_value) / scale[index]) * scale else: scale[index] += offset_value elif operation is OperationTypes.MULTIPLY: if self._parent_widget._link_scale: scale = offset_value * scale else: scale[index] *= offset_value scale_mat = Gf.Matrix4d().SetScale(scale) translation_mat = Gf.Matrix4d().SetTranslate(translation) prim_world_xform = scale_orient_mat * scale_mat * scale_orient_mat.GetTranspose() * rotation_mat * translation_mat parent_world_xform = omni.usd.get_world_transform_matrix(prim.GetParent()) prim_local_xform = prim_world_xform * parent_world_xform.GetInverse() omni.kit.commands.execute("TransformPrimCommand", path = path, new_transform_matrix = prim_local_xform) asyncio.ensure_future(self._end_string_edit(TRANSFORM_OP_SCALE)) def build_transform_frame(self, prim_paths, collapsable_frame, stage): self._clear_widgets() # Transform Frame if stage is None or len(prim_paths) <= 0 or prim_paths is None: return None, False prim_path = prim_paths[0] prim = stage.GetPrimAtPath(prim_path) if not prim or not prim.IsA(UsdGeom.Xformable): return None, False self._stage = stage xform = UsdGeom.Xformable(prim) # if xformOpOrder is absent or an empty array don't return # we may still have xformOp that are not listed in the xformOpOrder order_attr = prim.GetAttribute("xformOpOrder") if not order_attr: xform_op_order = [] xform_op_order = order_attr.Get() if xform_op_order is None: xform_op_order = [] # when select more than two prim, get common xformop to show if len(prim_paths) > 1: common_xformop, all_empty_xformop = self._get_common_xformop(prim_paths) for index, op_name in enumerate(common_xformop): attr_name = xform_op_utils.get_op_attr_name(op_name) attr = Usd.Attribute() if attr_name is not None: attr = prim.GetAttribute(attr_name) widget = self._create_xform_op_widget( prim_paths, collapsable_frame, stage, attr, op_name, True, order_attr, index ) if widget is not None: self._widgets.append(widget) model = widget._model #if it is a list the last one is the vector model if isinstance(model, list): for m in model: if m is not None: for sdf_path in m.get_attribute_paths(): self._models[sdf_path].append(m) elif model is not None: for sdf_path in model.get_attribute_paths(): self._models[sdf_path].append(model) if isinstance(widget, USDXformOpOrientWidget): if widget._euler_model is not None: for sdf_path in widget._euler_model.get_attribute_paths(): self._models[sdf_path].append(widget._euler_model) return self._models, all_empty_xformop attr_xform_op_order = xform.GetXformOpOrderAttr() xform_ops = xform.GetOrderedXformOps() has_reset_xform_stack = xform.GetResetXformStack() reset_index = -1 if has_reset_xform_stack: for i in range(len(xform_op_order) - 1, -1, -1): if xform_op_utils.is_reset_xform_stack_op(xform_op_order.__getitem__(i)): reset_index = i break attr_xform_ops = [] for index, op_name in enumerate(xform_op_order): attr_name = xform_op_utils.get_op_attr_name(op_name) if attr_name is not None: attr = prim.GetAttribute(attr_name) if attr: attr_xform_ops.append(attr) attrs_all = [attr for attr in prim.GetAttributes() if not attr.IsHidden()] attr_not_in_order_xform_ops = list( attr for attr in attrs_all if (attr.GetName().startswith("xformOp:") and not attr in attr_xform_ops) ) if len(xform_op_order) + len(attr_not_in_order_xform_ops) > 0: with ui.VStack(spacing=8, name="frame_v_stack"): ui.Spacer(height=0) for index, op_name in enumerate(xform_op_order): is_valid_op = index >= reset_index and xform_op_utils.is_valid_op_name(op_name) attr_name = xform_op_utils.get_op_attr_name(op_name) attr = Usd.Attribute() if attr_name is not None: attr = prim.GetAttribute(attr_name) widget = self._create_xform_op_widget( prim_paths, collapsable_frame, stage, attr, op_name, is_valid_op, order_attr, index ) if widget is not None: self._widgets.append(widget) # self._models.append(widget._model) model = widget._model if isinstance(model, list): for m in model: if m is not None: for sdf_path in m.get_attribute_paths(): self._models[sdf_path].append(m) elif model is not None: for sdf_path in model.get_attribute_paths(): self._models[sdf_path].append(model) if isinstance(widget, USDXformOpOrientWidget): if widget._euler_model is not None: for sdf_path in widget._euler_model.get_attribute_paths(): self._models[sdf_path].append(widget._euler_model) if len(attr_not_in_order_xform_ops) > 0: ui.Separator() for attr in attr_not_in_order_xform_ops: widget = self._create_xform_op_widget(prim_paths, collapsable_frame, stage, attr) if widget is not None: self._widgets.append(widget) ui.Spacer(height=0) return self._models, False def build_transform_offset_frame(self, prim_paths, collapsable_frame, stage): self._clear_widgets() translate_model = VecAttributeModel( default_value = "0.0", begin_edit_callback = functools.partial(self._start_field_edit, transform=TRANSFORM_OP_MOVE), end_edit_callback = functools.partial(self._on_translate_offset, stage=stage, prim_paths=prim_paths) ) rotate_model = VecAttributeModel( default_value = "0.0", begin_edit_callback = functools.partial(self._start_field_edit, transform=TRANSFORM_OP_ROTATE), end_edit_callback = functools.partial(self._on_rotate_offset, stage=stage, prim_paths=prim_paths) ) scale_model = VecAttributeModel( default_value = "0.0", begin_edit_callback = functools.partial(self._start_field_edit, transform=TRANSFORM_OP_SCALE), end_edit_callback = functools.partial(self._on_scale_offset, stage=stage, prim_paths=prim_paths) ) def match(label): return self._parent_widget._filter.matches(label) highlight = self._parent_widget._filter.name label_kwargs = {"highlight": highlight} HEIGHT_SPACE = 8 with ui.VStack(): if match("Translate"): self._parent_widget._any_item_visible = True ui.Spacer(height = HEIGHT_SPACE) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): HighlightLabel("Translate", name="title", **label_kwargs) ui.Spacer(width=2) translate_stack = ui.HStack(identifier = "translate_stack") with translate_stack: with ui.ZStack(): kwargs = {"step": 1.0} self._string_translate_widget = self._create_multi_string_with_labels( ui_widget = ui.StringField, model = translate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) for widget in self._string_translate_widget: widget.visible = False self._float_translate_widget = self._create_multi_string_with_labels( ui_widget = ui.FloatDrag, model = translate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) translate_stack.set_mouse_double_clicked_fn(lambda x, y, b, m: self._on_double_click(TRANSFORM_OP_MOVE)) translate_stack.set_mouse_pressed_fn(lambda x, y, b, m: self._on_press()) if match("Rotate"): self._parent_widget._any_item_visible = True ui.Spacer(height = HEIGHT_SPACE) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): HighlightLabel("Rotate", name="title", **label_kwargs) ui.Spacer(width=2) rotate_stack = ui.HStack(identifier = "rotate_stack") with rotate_stack: with ui.ZStack(): kwargs = {"step": 1.0} self._string_rotate_widget = self._create_multi_string_with_labels( ui_widget = ui.StringField, model = rotate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) for widget in self._string_rotate_widget: widget.visible = False self._float_rotate_widget = self._create_multi_string_with_labels( ui_widget = ui.FloatDrag, model = rotate_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) rotate_stack.set_mouse_double_clicked_fn(lambda x, y, b, m: self._on_double_click(TRANSFORM_OP_ROTATE)) rotate_stack.set_mouse_pressed_fn(lambda x, y, b, m: self._on_press()) if match("Scale"): self._parent_widget._any_item_visible = True ui.Spacer(height = HEIGHT_SPACE) with ui.HStack(): with ui.HStack(width=LABEL_PADDING): HighlightLabel("Scale", name="title", **label_kwargs) if self._parent_widget._link_scale: button_style = { "color": 0xFF34B5FF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_on.svg"}, ":hovered": {"color": 0xFFACDCF9} } else: button_style = { "color": 0x66FFFFFF, "background_color": 0x0, "Button.Image": {"image_url": f"{ICON_PATH}/link_off.svg"}, ":hovered": {"color": 0xFFFFFFFF} } with ui.ZStack(content_clipping = True, width=25, height=25): ui.Button("", style = button_style, clicked_fn = self._parent_widget._toggle_link_scale, identifier = "toggle_link_offset_scale", tooltip = "Toggle link scale") ui.Spacer(width=70) scale_stack = ui.HStack(identifier = "scale_stack") with scale_stack: with ui.ZStack(): kwargs = {"step": 1.0} self._string_scale_widget = self._create_multi_string_with_labels( ui_widget = ui.StringField, model = scale_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) for widget in self._string_scale_widget: widget.visible = False self._float_scale_widget = self._create_multi_string_with_labels( ui_widget = ui.FloatDrag, model = scale_model, labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F)], comp_count = 3 ) scale_stack.set_mouse_double_clicked_fn(lambda x, y, b, m: self._on_double_click(TRANSFORM_OP_SCALE)) scale_stack.set_mouse_pressed_fn(lambda x, y, b, m: self._on_press()) return None
83,413
Python
46.71968
309
0.534593
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/__init__.py
from .transform_properties import *
36
Python
17.499991
35
0.805556
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_properties.py
import os import carb import omni.ext from pxr import Sdf, UsdLux, UsdGeom, Gf from pathlib import Path from functools import partial from .transform_widget import TransformAttributeWidget from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload from . import transform_builder import omni.ui as ui from .transform_commands import * from . import xform_op_utils TEST_DATA_PATH = "" g_ext = None class TransformPropertyExtension(omni.ext.IExt): def __init__(self): self._registered = False super().__init__() def on_startup(self, ext_id): manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) transform_builder.ICON_PATH = Path(extension_path).joinpath("data").joinpath("icons") global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("test_data") self._register_widget() self._register_context_menu() from omni.kit.property.usd import PrimPathWidget self._add_button_menu = [] context_menu = omni.kit.context_menu.get_instance() if context_menu is None: carb.log_error("context_menu is disabled!") return None self._settings = carb.settings.get_settings() self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Translate, Rotate, Scale", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=True, add_rotateXYZ_op=True, add_orient_op=False, add_scale_op=True, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Translate, Orient, Scale", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=True, add_rotateXYZ_op=False, add_orient_op=True, add_scale_op=True, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Transform", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=False, add_transform_op=True) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Pivot", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=False, add_transform_op=False, add_pivot=True) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Translate", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=True, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=False, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Rotate", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=True, add_orient_op=False, add_scale_op=False, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Orient", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=True, add_scale_op=False, add_transform_op=False) ) ) self._add_button_menu.append( PrimPathWidget.add_button_menu_entry( "TransformOp/Scale", show_fn=partial(context_menu.prim_is_type, type=UsdGeom.Xformable), onclick_fn=partial(self._add_xform_op, add_translate_op=False, add_rotateXYZ_op=False, add_orient_op=False, add_scale_op=True, add_transform_op=False) ) ) # set ext global g_ext g_ext = self def on_shutdown(self): # pragma: no cover if self._registered: self._unregister_widget() # release menu item(s) from omni.kit.property.usd import PrimPathWidget for item in self._add_button_menu: PrimPathWidget.remove_button_menu_entry(item) # release context menu items self._unregister_context_menu() #clear global g_ext g_ext = None def _add_xform_op( self, payload: PrimSelectionPayload, add_translate_op: bool, add_rotateXYZ_op: bool, add_orient_op: bool, add_scale_op: bool, add_transform_op: bool, add_pivot = False ): # Retrieve the default precision default_xform_op_precision = self._settings.get("/persistent/app/primCreation/DefaultXformOpPrecision") if default_xform_op_precision is None: self._settings.set_default_string( "/persistent/app/primCreation/DefaultXformOpPrecision", "Double" ) default_xform_op_precision = "Double" _precision = None if default_xform_op_precision == "Double": _precision = UsdGeom.XformOp.PrecisionDouble elif default_xform_op_precision == "Float": _precision = UsdGeom.XformOp.PrecisionFloat elif default_xform_op_precision == "Half": _precision = UsdGeom.XformOp.PrecisionHalf # No operation is carried out if precision is not properly set if _precision is None: carb.log_error("The default xform op precision is not properly set! Please set it in the Edit/Preferences/Stage window!") return # Retrieve the default rotation order default_rotation_order = self._settings.get("/persistent/app/primCreation/DefaultRotationOrder") if default_rotation_order is None: self._settings.set_default_string("persistent/app/primCreation/DefaultRotationOrder", "XYZ") default_rotation_order = "XYZ" omni.kit.commands.execute("AddXformOp", payload=payload, precision=_precision, rotation_order = default_rotation_order, add_translate_op = add_translate_op, add_rotateXYZ_op = add_rotateXYZ_op, add_orient_op=add_orient_op, add_scale_op = add_scale_op, add_transform_op = add_transform_op, add_pivot_op = add_pivot) import omni.kit.window.property as p p.get_window()._window.frame.rebuild() def _register_widget(self): import omni.kit.window.property as p from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget, MultiSchemaPropertiesWidget w = p.get_window() if w: w.register_widget("prim", "transform", TransformAttributeWidget(title="Transform", collapsed=False)) self._registered = True def _unregister_widget(self): import omni.kit.window.property as p w = p.get_window() if w: w.unregister_widget("prim", "transform") self._registered = False #Context menu to Disable/Delete/Enable transform widgets def _register_context_menu(self): import omni.kit.context_menu menu_sep = { "name": "", } self._separator_menu = omni.kit.context_menu.add_menu(menu_sep, "attribute", "omni.kit.property.usd") # Disable Menu def _can_show_disable(object): model = object.get("model", None) if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if xform_op_utils.is_reset_xform_stack_op(builder_widget._op_name): return True elif builder_widget._op_name is not None and builder_widget._attr_path is not None: return True #This must be a Disalbe Invalid Op menu, a bug if not the case elif builder_widget._op_name is not None and builder_widget._attr_path is None: return True return False def _on_disable(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: builder_widget._delete_op_only() menu_disable = { "name": "Disable", "show_fn": _can_show_disable, "onclick_fn": _on_disable } self._on_disable_menu = omni.kit.context_menu.add_menu(menu_disable, "attribute", "omni.kit.property.usd") #Delete Menu def _can_show_delete(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if xform_op_utils.is_reset_xform_stack_op(builder_widget._op_name): return False elif builder_widget._attr_path is not None: return True return False def _on_delete(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if builder_widget._op_name is not None: builder_widget._delete_op_and_attribute() else: builder_widget._delete_non_op_attribute() menu_delete = { "name": "Delete", "show_fn": _can_show_delete, "onclick_fn": _on_delete } self._on_delete_menu = omni.kit.context_menu.add_menu(menu_delete, "attribute", "omni.kit.property.usd") #Enable Menu def _can_show_enable(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: if builder_widget._op_name is None and builder_widget._attr_path is not None: return True return False def _on_enable(object): model = object.get("model", None) if model: if hasattr(model, "transform_widget"): builder_widget = getattr(model, "transform_widget") if builder_widget: builder_widget._add_non_op_attribute_to_op() menu_enable = { "name": "Enable", "show_fn": _can_show_enable, "onclick_fn": _on_enable } self._on_enable_menu = omni.kit.context_menu.add_menu(menu_enable, "attribute", "omni.kit.property.usd") def _unregister_context_menu(self): self._separator_menu = None self._on_disable_menu = None self._on_delete_menu = None self._on_enable_menu = None
12,530
Python
41.767918
165
0.575499
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/scripts/transform_commands.py
import carb import omni.kit.commands import omni.usd from omni.kit.usd_undo import * from pxr import Gf, Vt, Sdf, Usd, UsdGeom, UsdUtils from . import xform_op_utils class EnableXformOpCommand(omni.kit.commands.Command): """ Add and attritube's corresponding XformOp to xformOpOrder **Command**. Args: op_attr_path (str): path of the xformOp attribute. Example: We might want to add xformOp:translate to the xformOpOrder token array Provided that xformOp:translate attribute exists and xformOp:translate is no in xformOpOrder """ def __init__(self, op_attr_path: str, enable=True): self._op_attr_path = Sdf.Path(op_attr_path) self._usd_context = omni.usd.get_context() self._prev_xform_ops = None self._layer_op_order_map = {} def do(self): stage = self._usd_context.get_stage() if stage: op_attr = stage.GetObjectAtPath(self._op_attr_path) if not op_attr: return precision = xform_op_utils.get_op_precision(op_attr.GetTypeName()) op_name = op_attr.GetName() op_type = xform_op_utils.get_op_type(op_name) if op_type is None: return prim = op_attr.GetPrim() if not prim.IsA(UsdGeom.Xformable): return op_suffix = xform_op_utils.get_op_name_suffix(op_name) if op_suffix == None: op_suffix = "" xform = UsdGeom.Xformable(prim) self._prev_xform_ops = xform.GetOrderedXformOps() new_target = stage.GetEditTargetForLocalLayer(stage.GetEditTarget().GetLayer()) with Usd.EditContext(stage, new_target): with Sdf.ChangeBlock(): added_op = xform.AddXformOp(opType=op_type, precision = precision, opSuffix=op_suffix) #for pivot, we should add its inverse op as well # if xform_op_utils.is_pivot_op(op_name): pivot_op = added_op #Assume that !invert!xformOp:translate:pivot is always a trailing op xform.AddTranslateOp(precision = precision, opSuffix="pivot", isInverseOp=True) #Move the pivot op infront of the transform op as a special case xform_ops = xform.GetOrderedXformOps() new_xform_ops = [] found_transform_op = False for op in xform_ops: #wrap the transform op with pivot op if op.GetOpType() == UsdGeom.XformOp.TypeTransform: new_xform_ops.append(pivot_op) new_xform_ops.append(op) found_transform_op = True continue # skip the pivot op if we insert it in front of transform op if found_transform_op and op.GetOpType() == UsdGeom.XformOp.TypeTranslate \ and xform_op_utils.is_pivot_op(str(op.GetOpName())) \ and not xform_op_utils.is_inverse_op(str(op.GetOpName())): continue new_xform_ops.append(op) xform.SetXformOpOrder(new_xform_ops, xform.GetResetXformStack()) def undo(self): stage = self._usd_context.get_stage() op_attr = stage.GetObjectAtPath(self._op_attr_path) if not op_attr: return prim = op_attr.GetPrim() if not prim.IsA(UsdGeom.Xformable): return xform = UsdGeom.Xformable(prim) with Sdf.ChangeBlock(): new_target = stage.GetEditTargetForLocalLayer(stage.GetEditTarget().GetLayer()) with Usd.EditContext(stage, new_target): xform.SetXformOpOrder(self._prev_xform_ops) class ChangeRotationOpCommand(omni.kit.commands.Command): """ Change the Rotation XformOp **Command**. Args: src_op_attr_path (str): path of the source xformOp attribute. dst_op_attr_name (str): path of the destination xformOp attribute is_inverse_op (bool): if it is an inverse op, add an !invert! in the xformOpOrder Example: We may want to change from xformOp:rotateZYX to xformOp:rotateXYZ. It will 1) update the xformOpOrder 2) delete xformOp:rotateZYX attribute 3) create xformOp:rotateXYZ attribute 4) copy the xformOp:rotateZYX to xfomOp:rotateXYZ """ def __init__(self, src_op_attr_path: str, op_name: str, dst_op_attr_name: str, is_inverse_op: bool, auto_target_layer: bool = True): self._src_op_attr_path = Sdf.Path(src_op_attr_path) self._op_name = op_name self._dst_op_attr_name = dst_op_attr_name self._is_inverse_op = is_inverse_op self._auto_target_layer = auto_target_layer self._usd_context = omni.usd.get_context() self._usd_undos = dict() def _get_undo(self, layer): if layer is not None: undo = self._usd_undos.get(layer) if undo is not None: return undo self._usd_undos[layer] = UsdLayerUndo(layer) return self._usd_undos[layer] def _change_rotation_op(self): stage = self._usd_context.get_stage() src_op_attr = stage.GetObjectAtPath(self._src_op_attr_path) if src_op_attr == None or not src_op_attr.IsValid(): return src_op_attr_name = src_op_attr.GetName() if src_op_attr_name is None or self._dst_op_attr_name is None or src_op_attr_name == self._dst_op_attr_name: return prim = src_op_attr.GetPrim() if not prim: return op_order_attr = prim.GetAttribute("xformOpOrder") if not op_order_attr: return with Sdf.ChangeBlock(): current_authoring_layer = stage.GetEditTarget().GetLayer() # change xforpOpOrder layer_info, layer = omni.usd.get_attribute_effective_defaultvalue_layer_info(stage, op_order_attr) auto_target_session_layer = omni.usd.get_prop_auto_target_session_layer(stage, op_order_attr.GetPath()) if self._auto_target_layer else None if (layer_info == omni.usd.Value_On_Layer.ON_CURRENT_LAYER or layer_info == omni.usd.Value_On_Layer.ON_WEAKER_LAYER or (layer_info == omni.usd.Value_On_Layer.ON_STRONGER_LAYER and auto_target_session_layer is not None and self._auto_target_layer == True ) ): if self._op_name: order = op_order_attr.Get() old_op_name = self._op_name new_op_name = self._dst_op_attr_name = ( self._dst_op_attr_name if not self._is_inverse_op else "!invert!" + self._dst_op_attr_name ) for i in range(len(order)): if order.__getitem__(i) == old_op_name: order.__setitem__(i, new_op_name) break if auto_target_session_layer: undo = self._get_undo(auto_target_session_layer) undo.reserve(op_order_attr.GetPath()) with Usd.EditContext(stage, auto_target_session_layer): op_order_attr.Set(order) else: undo = self._get_undo(current_authoring_layer) undo.reserve(op_order_attr.GetPath()) op_order_attr.Set(order) # copy to new attribute old_dst_op_attr = prim.GetAttribute(self._dst_op_attr_name) # the dst_op_attr may already exist if old_dst_op_attr: layer_info, layer = omni.usd.get_attribute_effective_value_layer_info(stage, old_dst_op_attr) auto_target_session_layer = omni.usd.get_prop_auto_target_session_layer(stage, old_dst_op_attr.GetPath()) if self._auto_target_layer else None value_on_session_OK = layer_info == omni.usd.Value_On_Layer.ON_STRONGER_LAYER and self._auto_target_layer == True and auto_target_session_layer is not None value_update_OK = (layer_info == omni.usd.Value_On_Layer.ON_CURRENT_LAYER or layer_info == omni.usd.Value_On_Layer.ON_WEAKER_LAYER or value_on_session_OK) if value_update_OK: if auto_target_session_layer is not None: undo = self._get_undo(auto_target_session_layer) undo.reserve(old_dst_op_attr.GetPath()) with Usd.EditContext(stage, auto_target_session_layer): src_op_attr.FlattenTo(prim, self._dst_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(old_dst_op_attr.GetPath()) src_op_attr.FlattenTo(prim, self._dst_op_attr_name) source_auto_target_sessiolayer = omni.usd.get_prop_auto_target_session_layer(stage, self._src_op_attr_path) if self._auto_target_layer else None if source_auto_target_sessiolayer is not None: undo = self._get_undo(source_auto_target_sessiolayer) undo.reserve(self._src_op_attr_path) with Usd.EditContext(stage, source_auto_target_sessiolayer): prim.RemoveProperty(src_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(self._src_op_attr_path) prim.RemoveProperty(src_op_attr_name) else: carb.log_warn(f"{self._dst_op_attr_name} has value authoring in stronger layer, cannot overwrite it! ") else: dst_op_attr_path = prim.GetPath().AppendProperty(self._dst_op_attr_name) if dst_op_attr_path: auto_target_session_layer = omni.usd.get_prop_auto_target_session_layer(stage, old_dst_op_attr.GetPath()) if self._auto_target_layer else None if auto_target_session_layer is not None: undo = self._get_undo(auto_target_session_layer) undo.reserve(dst_op_attr_path) with Usd.EditContext(stage, auto_target_session_layer): src_op_attr.FlattenTo(prim, self._dst_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(dst_op_attr_path) src_op_attr.FlattenTo(prim, self._dst_op_attr_name) source_auto_target_sessiolayer = omni.usd.get_prop_auto_target_session_layer(stage, self._src_op_attr_path) if self._auto_target_layer else None if source_auto_target_sessiolayer is not None: undo = self._get_undo(source_auto_target_sessiolayer) undo.reserve(self._src_op_attr_path) with Usd.EditContext(stage, source_auto_target_sessiolayer): prim.RemoveProperty(src_op_attr_name) else: undo = self._get_undo(current_authoring_layer) undo.reserve(self._src_op_attr_path) prim.RemoveProperty(src_op_attr_name) else: carb.log_error(f"Invalid dst_op_attr_name {self._dst_op_attr_name}. Note this is the attribute name.") else: carb.log_warn("xformOpOrder has value authoring a stronger persistent layer, cannot authoring rotate order! ") def do(self): stage = self._usd_context.get_stage() if not stage: return self._change_rotation_op() def undo(self): for undo in self._usd_undos.values(): undo.undo() class RemoveXformOpCommand(omni.kit.commands.Command): """ Remove XformOp Only **Command**. Args: op_order_attr_path (str): path of the xformOpOrder attribute. op_name (str): name of the xformOp to be removed Example: We might want to remove xformOp:translate from the xformOpOrder token array But we still keep the xformOp:translate attribute itself """ def __init__(self, op_order_attr_path: str, op_name: str, op_order_index: int): self._op_order_attr_path = Sdf.Path(op_order_attr_path) self._op_order_index = op_order_index self._op_name = op_name self._usd_context = omni.usd.get_context() self._usd_undo = None def do(self): stage = self._usd_context.get_stage() if not stage: return usd_undo = UsdLayerUndo(stage.GetEditTarget().GetLayer()) usd_undo.reserve(self._op_order_attr_path) order_attr = stage.GetObjectAtPath(self._op_order_attr_path) if order_attr: with Sdf.ChangeBlock(): op_order = order_attr.Get() if self._op_order_index < len(op_order): op_name = op_order.__getitem__(self._op_order_index) # when remove pivot op also need to remove invert pivot op is_pivot_op = xform_op_utils.is_pivot_op(op_name) inv_op_name = xform_op_utils.get_inverse_op_Name(op_name, True) if is_pivot_op else None if op_name == self._op_name: new_order = [] for i in range(len(op_order)): if i != self._op_order_index: if is_pivot_op and inv_op_name == op_order.__getitem__(i): continue new_order.append(op_order.__getitem__(i)) order_attr.Set(new_order) self._usd_undo = usd_undo def undo(self): if self._usd_undo is None: return self._usd_undo.undo() class RemoveXformOpAndAttrbuteCommand(omni.kit.commands.Command): """ Remove XformOp And Attribute **Command**. Args: op_order_attr_path (str): path of the xformOpOrder attribute. op_name (str): name of the xformOp to be removed Example: We might want to remove xformOp:translate from the xformOpOrder token array But we still keep the xformOp:translate attribute itself """ def __init__(self, op_order_attr_path: str, op_name: str, op_order_index: int): self._op_order_attr_path = Sdf.Path(op_order_attr_path) # the xformOpOrder attribute path self._op_name = op_name # xformOpName self._op_order_index = op_order_index self._usd_context = omni.usd.get_context() self._usd_undo = None def do(self): stage = omni.usd.get_context().get_stage() if stage: usd_undo = UsdLayerUndo(stage.GetEditTarget().GetLayer()) self._usd_undo = usd_undo order_attr = stage.GetObjectAtPath(self._op_order_attr_path) if order_attr: with Sdf.ChangeBlock(): op_order = order_attr.Get() if self._op_order_index < len(op_order): op_name = op_order.__getitem__(self._op_order_index) if op_name == self._op_name: # if it is an pivot op to remove, we'd also remove it's companion inverse pivot op is_pivot_op = xform_op_utils.is_pivot_op(op_name) inverse_pivot_op_name = xform_op_utils.get_inverse_op_Name(op_name, True) if is_pivot_op else None attr_name = xform_op_utils.get_op_attr_name(op_name) can_delete_attr = True new_order = [] for i in range(len(op_order)): #exclude the op if i != self._op_order_index: #if it is a pivot also exclude the inverse op if is_pivot_op and op_order.__getitem__(i) == inverse_pivot_op_name: continue other_op_name = op_order.__getitem__(i) new_order.append(other_op_name) if attr_name == xform_op_utils.get_op_attr_name(other_op_name): can_delete_attr = False new_token_order = Vt.TokenArray(new_order) usd_undo.reserve(self._op_order_attr_path) order_attr.Set(new_order) if can_delete_attr: prim = order_attr.GetPrim() if prim: usd_undo.reserve(prim.GetPath().AppendProperty(attr_name)) prim.RemoveProperty(attr_name) def undo(self): if self._usd_undo is None: return self._usd_undo.undo() class AddXformOpCommand(omni.kit.commands.Command): """ Add and attritube's corresponding XformOp to xformOpOrder **Command**. Args: op_attr_path (str): path of the xformOp attribute. Example: We might want to add xformOp:translate to the xformOpOrder token array Provided that xformOp:translate attribute exists and xformOp:translate is no in xformOpOrder """ def __init__(self, payload, precision, rotation_order, add_translate_op, add_rotateXYZ_op, add_orient_op, add_scale_op, add_transform_op, add_pivot_op): self._payload = payload self._precision = precision self._rotation_op_name = "xformOp:rotate" + rotation_order self._add_translate_op = add_translate_op self._add_rotate_op = add_rotateXYZ_op self._add_orient_op=add_orient_op self._add_scale_op = add_scale_op self._add_transform_op = add_transform_op self._add_pivot_op = add_pivot_op self._usd_undo = None self._prv_xform_op_order = {} self._translate_attr_added = {} self._rotate_attr_added = {} self._orient_attr_added = {} self._scale_attr_added = {} self._transform_attr_added = {} self._pivot_attr_added = {} def do(self): stage = self._payload.get_stage() if not stage: return # check precision first and return if self._precision != UsdGeom.XformOp.PrecisionHalf and self._precision != UsdGeom.XformOp.PrecisionDouble and self._precision != UsdGeom.XformOp.PrecisionFloat: carb.log_error("Illegal value precision setting! Precision setting can be UsdGeom.XformOp.PrecisionDouble OR UsdGeom.XformOp.PrecisionFloat OR UsdGeom.XformOp.PrecisionHalf.") return for path in self._payload: if path: selected_prim = stage.GetPrimAtPath(path) selected_xformable = UsdGeom.Xformable(selected_prim) # if not xform, skip if not selected_xformable: carb.log_error(f"Illegal prim {path}: this is not an UsdGeom.Xformable prim.") continue path_string = path.pathString translate_attr = selected_prim.GetAttribute("xformOp:translate") rotate_attr = selected_prim.GetAttribute(self._rotation_op_name) scale_attr = selected_prim.GetAttribute("xformOp:scale") orient_attr = selected_prim.GetAttribute("xformOp:orient") transform_attr = selected_prim.GetAttribute("xformOp:transform") pivot_attr = selected_prim.GetAttribute("xformOp:translate:pivot") translate_attr_exist = True if translate_attr.IsValid() else False rotate_attr_exist = True if rotate_attr.IsValid() else False scale_attr_exist = True if scale_attr.IsValid() else False orient_attr_exist = True if orient_attr.IsValid() else False transform_attr_exist = True if transform_attr.IsValid() else False pivot_attr_exist = True if pivot_attr.IsValid() else False translate_attr_type = xform_op_utils.get_op_precision(translate_attr.GetTypeName()) if translate_attr_exist else None rotate_attr_type = xform_op_utils.get_op_precision(rotate_attr.GetTypeName()) if rotate_attr_exist else None scale_attr_type = xform_op_utils.get_op_precision(scale_attr.GetTypeName()) if scale_attr_exist else None orient_attr_type = xform_op_utils.get_op_precision(orient_attr.GetTypeName()) if orient_attr_exist else None pivot_attr_type = xform_op_utils.get_op_precision(pivot_attr.GetTypeName()) if pivot_attr_exist else None def does_match_precision(self, attr_type): if attr_type and self._precision != attr_type: return False return True xform_op_order_attr = selected_xformable.GetXformOpOrderAttr() translate_op_exist = rotate_op_exist = scale_op_exist = orient_op_exist = transform_op_exist = pivot_op_exist = False self._translate_attr_added[path_string] = self._rotate_attr_added[path_string] = False self._orient_attr_added[path_string] = self._scale_attr_added[path_string] = self._transform_attr_added[path_string] = False self._pivot_attr_added[path_string] = False with Sdf.ChangeBlock(): #In a rare case, there is no xformOpOrder attribute if not xform_op_order_attr: xform_op_order_attr = selected_xformable.CreateXformOpOrderAttr() xform_op_order = xform_op_order_attr.Get() ordered_xform_op = selected_xformable.GetOrderedXformOps() for op in ordered_xform_op: if op.GetOpName() == 'xformOp:translate': translate_op_exist = True elif op.GetOpName() == self._rotation_op_name: rotate_op_exist = True elif op.GetOpName() == 'xformOp:scale': scale_op_exist = True elif op.GetOpName() == 'xformOp:orient': orient_op_exist = True elif op.GetOpName() == 'xformOp:transform': transform_op_exist = True elif op.GetOpType() == UsdGeom.XformOp.TypeTranslate and "pivot" in op.SplitName(): pivot_op_exist = True self._prv_xform_op_order[path_string] = xform_op_order #Translate Op if self._add_translate_op == True: if translate_attr_exist and translate_op_exist: carb.log_warn(f"The translate Op in prim {path} already exist!") # There is already translate attribute exist elif translate_op_exist == False: if does_match_precision(self, translate_attr_type): selected_xformable.AddTranslateOp(precision = self._precision) if translate_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(0, 0, 0)) self._translate_attr_added[path_string] = True else: carb.log_error("Illegal translate value precision setting!") #Rotate Op if self._add_rotate_op == True: if rotate_attr_exist and rotate_op_exist: carb.log_warn(f"The rotate Op in prim {path} already exist!") # There is already translate attribute exist elif rotate_op_exist == False: if does_match_precision(self, rotate_attr_type): rotation_op_type = xform_op_utils.get_op_type(self._rotation_op_name) if rotation_op_type: selected_xformable.AddXformOp(rotation_op_type,precision = self._precision) if rotate_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute(self._rotation_op_name, Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute(self._rotation_op_name, Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(0, 0, 0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute(self._rotation_op_name, Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(0, 0, 0)) self._rotate_attr_added[path_string] = True else: carb.log_error("Illegal rotate value precision setting!") #Orient Op if self._add_orient_op == True: if orient_attr_exist and orient_op_exist: carb.log_warn(f"The orient Op in prim {path} already exist!") # There is already translate attribute exist elif orient_op_exist == False: if does_match_precision(self, orient_attr_type): selected_xformable.AddOrientOp(precision = self._precision) if orient_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatd,False).Set(Gf.Quatd(1.0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quatf,False).Set(Gf.Quatf(1.0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:orient", Sdf.ValueTypeNames.Quath,False).Set(Gf.Quath(1.0)) self._orient_attr_added[path_string] = True else: carb.log_error("Illegal orient value precision setting!") #Scale Op if self._add_scale_op == True: if scale_attr_exist and scale_op_exist: carb.log_warn(f"The scale Op in prim {path} already exist!") # There is already translate attribute exist elif scale_op_exist == False: if does_match_precision(self, scale_attr_type): selected_xformable.AddScaleOp(precision = self._precision) if scale_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(1.0, 1.0, 1.0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(1.0, 1.0, 1.0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(1.0, 1.0, 1.0)) self._scale_attr_added[path_string] = True else: carb.log_error("Illegal scale value precision setting!") #Transform Op if self._add_transform_op == True: if transform_attr_exist and transform_op_exist: carb.log_warn(f"The transform Op in prim {path} already exist!") # There is already transform attribute exist elif transform_op_exist == False: #'Matrix transformations can only be encoded in double precision. Overriding precision to double.' #transform has to be double selected_xformable.AddTransformOp(UsdGeom.XformOp.PrecisionDouble) if transform_attr_exist == False: # there is only Matrix4d type selected_prim.CreateAttribute("xformOp:transform", Sdf.ValueTypeNames.Matrix4d,False).Set(Gf.Matrix4d(1.0)) self._transform_attr_added[path_string] = True #refresh to make sure pivot is inserted in the right place ordered_xform_op = selected_xformable.GetOrderedXformOps() #Pivot Op if self._add_pivot_op == True: if pivot_attr_exist and pivot_op_exist: carb.log_warn(f"The pivot Op in the prim {path} already exist!") elif pivot_op_exist == False: if does_match_precision(self, pivot_attr_type): # Parse the xformOpOrder to find out the rotateion-related & scale-related op's index # there might be multiple rotation & scale op to consider xform_op_size = len(ordered_xform_op) rotate_or_transform_start_index = rotate_or_transform_end_index = scale_start_index = scale_end_index = xform_op_size for index in range(xform_op_size): op = ordered_xform_op[index] op_type = op.GetOpType() # Suffixed op doesn't count if op_type > UsdGeom.XformOp.TypeInvalid and \ len(op.GetOpName().split(":"))>2: continue if op_type >= UsdGeom.XformOp.TypeRotateX \ and op_type <= UsdGeom.XformOp.TypeTransform: rotate_or_transform_end_index = index if rotate_or_transform_start_index == xform_op_size: rotate_or_transform_start_index = index elif op_type == UsdGeom.XformOp.TypeScale: scale_end_index = index if scale_start_index == xform_op_size: scale_start_index = index if rotate_or_transform_start_index == xform_op_size and scale_start_index == xform_op_size: carb.log_warn("There is no rotate, orient, transform or scale Op for this prim. No rotation Pivot is added.") return #Add the pivot op and invert pivot op and then reorder it pivot_op = selected_xformable.AddTranslateOp(precision = self._precision, opSuffix="pivot") inv_pivot_op = selected_xformable.AddTranslateOp(precision = self._precision, opSuffix="pivot", isInverseOp=True) #pivot and inv pivot to wrap the rotate & scale op. pivot heading inv pivot trailing pivot_index = min(rotate_or_transform_start_index, scale_start_index) inv_pivot_index = max(rotate_or_transform_end_index, scale_end_index) inv_pivot_index = inv_pivot_index + 1 #insert after # if the inverse pivot op is at the tail, just append it if inv_pivot_index >= len(ordered_xform_op): ordered_xform_op.append(inv_pivot_op) else: ordered_xform_op.insert(inv_pivot_index, inv_pivot_op) #It is important to insert pivot_op after inv_pivot_op ordered_xform_op.insert(pivot_index, pivot_op) selected_xformable.SetXformOpOrder(ordered_xform_op, selected_xformable.GetResetXformStack()) #Create xformOp:translate:pivot attribute if pivot_attr_exist == False: if self._precision == UsdGeom.XformOp.PrecisionDouble: selected_prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0.0, 0.0, 0.0)) elif self._precision == UsdGeom.XformOp.PrecisionFloat: selected_prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Float3,False).Set(Gf.Vec3f(0.0, 0.0, 0.0)) elif self._precision == UsdGeom.XformOp.PrecisionHalf: selected_prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Half3,False).Set(Gf.Vec3h(0.0, 0.0, 0.0)) self._pivot_attr_added[path_string] = True else: carb.log_error("Illegal pivot value precision setting!") def undo(self): stage = self._payload.get_stage() if not stage: return for path in self._payload: if path: selected_prim = stage.GetPrimAtPath(path) selected_xformable = UsdGeom.Xformable(selected_prim) path_string = path.pathString with Sdf.ChangeBlock(): xform_op_order_attr = selected_xformable.GetXformOpOrderAttr() if xform_op_order_attr: xform_op_order_attr.Set(self._prv_xform_op_order[path_string]) if self._translate_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:translate") self._translate_attr_added[path_string] = False if self._rotate_attr_added[path_string]: selected_prim.RemoveProperty(self._rotation_op_name) self._rotate_attr_added[path_string] = False if self._orient_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:orient") self._orient_attr_added[path_string] = False if self._scale_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:scale") self._scale_attr_added[path_string] = False if self._transform_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:transform") self._transform_attr_added[path_string] = False if self._pivot_attr_added[path_string]: selected_prim.RemoveProperty("xformOp:translate:pivot") self._pivot_attr_added[path_string] = False omni.kit.commands.register_all_commands_in_module(__name__)
37,809
Python
55.181278
187
0.525536
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_builder.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 weakref import omni.kit.app import omni.kit.test import omni.kit.commands import omni.ui as ui from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, select_prims from omni.ui.tests.test_base import OmniUiTest from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload from pathlib import Path from pxr import UsdGeom, Sdf from ..scripts.transform_builder import TransformWidgets, TransformWatchModel, USDXformOpWidget from ..scripts.transform_widget import TransformAttributeWidget from ..scripts.transform_properties import g_ext class TestTransformBuilder(OmniUiTest): xform_op_names = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:orient", "xformOp:scale", "xformOp:translate:pivot", "xformOp:transform"] # Before running each test async def setUp(self): await super().setUp() extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") # After running each test async def tearDown(self): await super().tearDown() def get_index_op_code(self, xform : UsdGeom.Xformable, op_name): xform_ops = xform.GetOrderedXformOps() for i, op in enumerate(xform_ops): if op.GetOpName() == op_name: return i return -1 async def test_builder_widgets(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() prim_path = '/World/Capsule' prim = stage.GetPrimAtPath(prim_path) xform = UsdGeom.Xformable(prim) transformWidget = TransformAttributeWidget("Test", True) await select_prims([prim_path]) collapsable_frame = ui.Frame(height=0, style={"Frame": {"padding": 0}}) # widget delete test widgets = [] op_order_attr = prim.GetAttribute('XformOpOrder') for op_name in self.xform_op_names: #valid means disabled or not widget = transformWidget._transform_widget._create_xform_op_widget( [Sdf.Path(prim_path)], collapsable_frame, stage, prim.GetAttribute(op_name), op_name, True, op_order_attr, self.get_index_op_code(xform, op_name) ) widgets.append(widget) await ui_test.human_delay(3) transformWidget = None widgets = [] transformWidget = TransformAttributeWidget("Test2", True) collapsable_frame = ui.Frame(height=0, style={"Frame": {"padding": 0}}) widgets = [] op_order_attr = prim.GetAttribute('XformOpOrder') for op_name in self.xform_op_names: #valid means disabled or not widget = transformWidget._transform_widget._create_xform_op_widget( [Sdf.Path(prim_path)], collapsable_frame, stage, prim.GetAttribute(op_name), op_name, False, op_order_attr, self.get_index_op_code(xform, op_name) ) widgets.append(widget) await ui_test.human_delay(3) transformWidget = None widgets = [] #watch model watch_model = TransformWatchModel(0, stage) await ui_test.human_delay(3) watch_model.set_value(0.3) self.assertTrue(watch_model.get_value_as_float() == 0.3) self.assertTrue(watch_model.get_value_as_string() == "0.3") watch_model.clean() watch_model = None # USD Xform Op Widget for op_name in self.xform_op_names: #valid means disabled or not widget = USDXformOpWidget( [Sdf.Path(prim_path)], collapsable_frame, stage, prim.GetAttribute(op_name).GetPath(), op_name, True, op_order_attr, self.get_index_op_code(xform, op_name)) #widget._inverse_op() widget._add_key() widget._show_right_click_menu(button=1) async def test_add_buttons(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() prim_paths =["/World/Capsule", "/World/Sphere", "/World/Cube", "/World/Cylinder", "/World/Cone"] for prim_path in prim_paths: await select_prims([prim_path]) prim = stage.GetObjectAtPath(prim_path) payload = PrimSelectionPayload( weakref.ref(stage), [prim.GetPath()]) for button_menu in g_ext._add_button_menu: if button_menu.onclick_fn: button_menu.onclick_fn(payload) await ui_test.human_delay(2)
5,548
Python
37.534722
146
0.637167
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_transform.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.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading from omni.ui.tests.test_base import OmniUiTest from pxr import Kind, Sdf, Gf, UsdGeom from pathlib import Path import carb from carb.input import KeyboardInput def equal_eps(a, b, esp = 0.0001): return abs(a - b) < esp def equal_scale_eps(t, s): m = Gf.Vec3d(0.0) m[0] = t.GetRow(0).GetLength() m[1] = t.GetRow(1).GetLength() m[2] = t.GetRow(2).GetLength() #print (m) return equal_eps(m[0], s[0]) and equal_eps(m[1], s[1]) and equal_eps(m[2], s[2]) class TestTransformWidget(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._golden_img_dir = extension_root_folder.joinpath("data/test_data/golden_img") self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): await super().tearDown() async def test_transform_property_srt(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_srt.png") async def test_transform_property_srt_filter(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) try: self._w._searchfield._search_field.model.as_string = "tr" self._w._searchfield._set_in_searching(True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_srt_filter.png") finally: self._w._searchfield._search_field.model.as_string = "" self._w._searchfield._set_in_searching(False) async def test_transform_property_sqt(self): usd_context = omni.usd.get_context() # golden image expects the UI to be switched to "orient as rotate" settings = carb.settings.get_settings() doar_path = "/persistent/app/uiSettings/DisplayOrientAsRotate" doar_val = settings.get_as_bool(doar_path) settings.set(doar_path, True) try: await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) finally: carb.settings.get_settings().set(doar_path, doar_val) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_sqt.png") async def test_transform_property_sqt2(self): usd_context = omni.usd.get_context() # golden image expects the UI to be switched to "orient as rotate" settings = carb.settings.get_settings() doar_path = "/persistent/app/uiSettings/DisplayOrientAsRotate" doar_val = settings.get_as_bool(doar_path) settings.set(doar_path, True) try: await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM, block_devices=False) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) #now find a button for orient and click it to swap to test swapping widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Button[*].text=='Orient'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) finally: await self.capture_and_compare(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_sqt2.png") # add another test to click it back widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Button[*].text=='Orient'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_sqt3.png") carb.settings.get_settings().set(doar_path, doar_val) async def test_transform_property_matrix(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cylinder"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_matrix.png") async def test_transform_property_pivot(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=280, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cone"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_pivot.png") async def test_transform_property_disabled_translate_op(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=260, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Sphere"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_disabled_translate_op.png") async def test_transform_property_euler_to_quat_sync(self): usd_context = omni.usd.get_context() usd_context.new_stage() settings = carb.settings.get_settings() doar_path = "/persistent/app/uiSettings/DisplayOrientAsRotate" doar_val = settings.get_as_bool(doar_path) carb.settings.get_settings().set(doar_path, True) try: await self.docked_test_window( window=self._w._window, width=640, height=480, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # we actually want mouse and keyboard to be active omni.appwindow.get_default_app_window().set_input_blocking_state(carb.input.DeviceType.MOUSE, False) omni.appwindow.get_default_app_window().set_input_blocking_state(carb.input.DeviceType.KEYBOARD, False) await ui_test.wait_n_updates(10) path = "/Cube" cube_geom = UsdGeom.Cube.Define(usd_context.get_stage(), path) cube_geom.AddOrientOp().Set(Gf.Quatf(1.0)) usd_context.get_selection().set_selected_prim_paths([path], False) await ui_test.find("Property").focus() transform_euler = ui_test.find("Property//Frame/**/*.identifier=='euler_xformOp:orient'") # change Y axis to 180 digit by digit as a user would do await transform_euler.double_click(human_delay_speed=10) for s in "180": await ui_test.emulate_char_press(s) await ui_test.wait_n_updates(10) await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER) finally: await self.finalize_test_no_image() carb.settings.get_settings().set(doar_path, doar_val) orient = Gf.Quatf(1.0) for op in cube_geom.GetOrderedXformOps(): if op.GetOpType() == UsdGeom.XformOp.TypeOrient: orient = op.Get() self.assertTrue(orient.imaginary[1] != 0) async def test_transform_property_multi(self): usd_context = omni.usd.get_context() # golden image expects the UI to be switched to "orient as rotate" try: await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule", "/World/Cube", "/World/Cylinder"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) finally: await self.capture_and_compare(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_multi.png") # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Capsule", "/World/Cube"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) #text of mixed is moving and it's causing very unstable result for testing, so increasing threshold to be 2. await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_multi2.png", threshold=2) async def test_transform_scale(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) prim = stage.GetPrimAtPath("/World/Cube") # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='scale_t_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 2.0, 1.0))) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 4.0, 1.0))) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 30 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 7.0, 1.0))) await self.finalize_test_no_image() await ui_test.wait_n_updates(20) async def test_transform_toggle_scale(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) prim = stage.GetPrimAtPath("/World/Cube") # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Button[*].identifier=='toggle_link_scale'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) #enable toggle mode await button.click(pos=button.position+ui_test.Vec2(button.widget.computed_content_width/2, 5)) await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='scale_t_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(2.0, 2.0, 2.0))) await self.finalize_test_no_image() await ui_test.wait_n_updates(20) async def test_transform_reset_stack(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=280, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/World/Cube") # Get the XformCommonAPI xform_api = UsdGeom.XformCommonAPI(prim) #Set the ResetXformStack. UI should responds accordingly xform_api.SetResetXformStack(True) usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_reset.png") async def test_transform_rotate_scalar(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/World/Cube_2"], True) prim = stage.GetPrimAtPath("/World/Cube_2") # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) # Now we're in offset mode. x_stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='rotate_scalar_stack_x'") self.assertIsNotNone(x_stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. rotate_attr = prim.GetAttribute("xformOp:rotateX") self.assertIsNotNone(rotate_attr) self.assertTrue(rotate_attr.Get() == -30.0) # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await x_stack.click() await x_stack.double_click() await ui_test.human_delay(10) for _ in range(5): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("20") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) self.assertTrue(rotate_attr.Get() == 20.0) y_stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='rotate_scalar_stack_y'") self.assertIsNotNone(y_stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. rotate_attr = prim.GetAttribute("xformOp:rotateY") self.assertIsNotNone(rotate_attr) self.assertTrue(rotate_attr.Get() == 0.0) # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await y_stack.click() await y_stack.double_click() await ui_test.human_delay(10) for _ in range(5): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("30") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) self.assertTrue(rotate_attr.Get() == 30.0) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 35.92772)) #test transform await self.finalize_test_no_image() await ui_test.wait_n_updates(20) ''' #this test doesn't work because the kit has a way to enter xformOp:translate to trigger #build widget, where test won't be able to do this. OM-112507 #https://nvidia.slack.com/archives/CURCH7KU2/p1697658671468429?thread_ts=1697204512.040859&cid=CURCH7KU2 async def test_transform_property_wgs84(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=640, height=480, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) test_file_path = self._usd_path.joinpath("wgs84/deutschebahn-rails.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/RootGeoReference/World/CurveXform26Geo"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) try: self._w._searchfield._search_field.model.as_string = "tr" self._w._searchfield._set_in_searching(True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_transform_property_wgs84.png") finally: self._w._searchfield._search_field.model.as_string = "" self._w._searchfield._set_in_searching(False) '''
26,141
Python
43.84048
140
0.642669
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/__init__.py
from .test_transform import * from .test_offset import * from .test_transform_context_menu import * from .test_commands import * from .test_builder import *
157
Python
25.333329
42
0.764331
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_offset.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 carb.input import KeyboardInput import omni.kit.test import omni.kit.ui_test as ui_test import omni.ui as ui import omni.usd from omni.ui.tests.test_base import OmniUiTest from pxr import Gf def equal_eps(a, b, esp = 0.0001): return abs(a - b) < esp class TestTransformOffset(OmniUiTest): async def setUp(self): await super().setUp() from omni.kit.property.transform.scripts.transform_properties import TEST_DATA_PATH self._usd_path = TEST_DATA_PATH.absolute() from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() async def tearDown(self): await super().tearDown() async def test_offset_mode_rotate(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("offset_test.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) prim = stage.GetPrimAtPath(f"{stage.GetDefaultPrim().GetPath()}/Cube") self.assertTrue(prim.IsValid()) # Select the prim. usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/Button[*].identifier=='offset_mode_toggle'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) await button.click() await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='rotate_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("10") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 10.0)) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 20.0)) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 100 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_eps(transform.ExtractRotation().GetAngle(), 21.0)) await self.finalize_test_no_image() # Finally, toggle offset mode again so subsequent tests will not start in offset mode await button.click() await ui_test.wait_n_updates(20) async def test_offset_mode_translate(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("offset_test.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) prim = stage.GetPrimAtPath(f"{stage.GetDefaultPrim().GetPath()}/Cube") self.assertTrue(prim.IsValid()) # Select the prim. usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/Button[*].identifier=='offset_mode_toggle'") stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='translate_stack'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) self.assertIsNone(stack) await button.click() await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='translate_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("100") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(transform.ExtractTranslation() == Gf.Vec3d(0.0, 100.0, 0.0)) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(transform.ExtractTranslation() == Gf.Vec3d(0.0, 200.0, 0.0)) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 100 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(transform.ExtractTranslation() == Gf.Vec3d(0.0, 201.0, 0.0)) await self.finalize_test_no_image() # Finally, toggle offset mode again so subsequent tests will not start in offset mode await button.click() await ui_test.wait_n_updates(20) async def test_offset_mode_scale(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("offset_test.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await omni.kit.app.get_app().next_update_async() stage = usd_context.get_stage() self.assertIsNotNone(stage) prim = stage.GetPrimAtPath(f"{stage.GetDefaultPrim().GetPath()}/Cube") self.assertTrue(prim.IsValid()) # Select the prim. usd_context.get_selection().set_selected_prim_paths([str(prim.GetPath())], True) # Let UI build # (Note: I'm not sure why we need to wait more than a few frames, but empirically # this seems to be the case. So just wait 20 frames to make sure UI is there.) await ui_test.wait_n_updates(20) button = ui_test.find("Property//Frame/**/Button[*].identifier=='offset_mode_toggle'") # We should be able to find the mode toggle button, # but until we're in offset mode we should not have any offset fields self.assertIsNotNone(button) await button.click() await ui_test.wait_n_updates(20) # Now we're in offset mode. stack = ui_test.find("Property//Frame/**/HStack[*].identifier=='scale_stack'") self.assertIsNotNone(stack) # Here's a funny thing -- the double-click clicks the center of the ui element by default. # That amounts to setting offsets in Y. # Rather than work around that, we're just going to use the Y component for our offset. # XXX for some reason, using field.input doesn't give the desired results here -- # the field's text isn't selected after double-clicking, so we end up entering # "0.0100" instead of "100". # As a workaround, we'll just break input down into its components (double-click, enter characters, # hit enter), with the addition of three backspaces to clear the field's default "0.0" await stack.click() await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) def equal_scale_eps(t, s): m = Gf.Vec3d(0.0) m[0] = t.GetRow(0).GetLength() m[1] = t.GetRow(1).GetLength() m[2] = t.GetRow(2).GetLength() #print (m) return equal_eps(m[0], s[0]) and equal_eps(m[1], s[1]) and equal_eps(m[2], s[2]) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 3.0, 1.0))) # Apply another offset, then check the prim's translation await stack.double_click() await ui_test.human_delay(10) for _ in range(3): await ui_test.emulate_keyboard_press(KeyboardInput.BACKSPACE) await ui_test.emulate_char_press("*2") await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 6.0, 1.0))) # Click and drag field, the check the prim's translation drag_vector = stack.center drag_vector.x = drag_vector.x + 100 await ui_test.human_delay(30) await ui_test.emulate_mouse_drag_and_drop(stack.center, drag_vector) await ui_test.wait_n_updates(2) transform = omni.usd.get_world_transform_matrix(prim) self.assertTrue(equal_scale_eps(transform, Gf.Vec3d(1.0, 7.0, 1.0))) await self.finalize_test_no_image() # Finally, toggle offset mode again so subsequent tests will not start in offset mode await button.click() await ui_test.wait_n_updates(20)
12,486
Python
41.763698
107
0.653692
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_commands.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 weakref import omni.kit.app import omni.kit.commands import omni.kit.test from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from pxr import UsdGeom, Sdf, Gf from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload from ..scripts.xform_op_utils import get_op_type_name, _add_trs_op, get_op_name_suffix, get_op_precision, get_inverse_op_Name, RESET_XFORM_STACK, get_op_attr_name import carb import carb.settings class TestTransformCommands(OmniUiTest): xform_op_names = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:orient", "xformOp:scale", "xformOp:translate:pivot", "xformOp:transform"] prim_paths =["/World/Capsule", "/World/Cube", "/World/Cylinder", "/World/Cone"] # Before running each test async def setUp(self): await super().setUp() extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") # After running each test async def tearDown(self): await super().tearDown() def include_op_code(self, xform : UsdGeom.Xformable, op_name): return self.get_index_op_code(xform, op_name) != -1 def get_index_op_code(self, xform : UsdGeom.Xformable, op_name): xform_ops = xform.GetOrderedXformOps() for i, op in enumerate(xform_ops): if op.GetOpName() == op_name: return i return -1 async def add_xform_ops_test(self, stage, prim_path, precision, undo_after=True): prim = stage.GetObjectAtPath(prim_path) xform = UsdGeom.Xformable(prim) usd_context = omni.usd.get_context() usd_context.get_selection().set_selected_prim_paths([prim_path], True) await ui_test.human_delay(3) ops_exists = [] attr_exists = [] for op_name in self.xform_op_names: ops_exists.append(self.include_op_code(xform, op_name)) attr_exists.append(stage.GetObjectAtPath(prim_path + "." + op_name) != None) payload = PrimSelectionPayload( weakref.ref(stage), [prim.GetPath()]) omni.kit.commands.execute('AddXformOp', payload=payload, precision=precision, rotation_order='XYZ', add_translate_op=True, add_rotateXYZ_op=True, add_orient_op=True, add_scale_op=True, add_transform_op=True, add_pivot_op=True) await ui_test.human_delay(3) xform_ops = xform.GetOrderedXformOps() for op_name in self.xform_op_names: #make sure rotation order XYZ ops_exists self.assertTrue(self.include_op_code(xform, op_name)) attr = stage.GetObjectAtPath(prim_path + "." + op_name) self.assertTrue(attr) if undo_after: #undo omni.kit.commands.execute("Undo") await ui_test.human_delay(3) for i, op_name in enumerate(self.xform_op_names): if not ops_exists[i]: self.assertTrue(not self.include_op_code(xform, op_name)) async def remove_xform_ops_test(self, stage, prim_path): prim = stage.GetObjectAtPath(prim_path) xform = UsdGeom.Xformable(prim) usd_context = omni.usd.get_context() usd_context.get_selection().set_selected_prim_paths([prim_path], True) await ui_test.human_delay(3) for op_name in self.xform_op_names: index = self.get_index_op_code(xform, op_name) omni.kit.commands.execute('RemoveXformOpAndAttrbute', op_order_attr_path=Sdf.Path(prim_path + '.xformOpOrder'), op_name=op_name, op_order_index=index) await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op_name)) for op_name in self.xform_op_names: omni.kit.commands.execute("Undo") for op_name in self.xform_op_names: self.assertTrue(self.include_op_code(xform, op_name)) async def test_transform_add_remove_commands(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() precision_types = [UsdGeom.XformOp.PrecisionDouble, UsdGeom.XformOp.PrecisionFloat, UsdGeom.XformOp.PrecisionHalf] for prim_path in self.prim_paths: for precision in precision_types: await self.add_xform_ops_test(stage, prim_path, precision) for prim_path in self.prim_paths: for precision in precision_types: await self.add_xform_ops_test(stage, prim_path, precision, False) await self.remove_xform_ops_test(stage, prim_path) async def test_transform_add_remove_xformops_commands(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() #ops_exists = [] #for op_name in self.xform_op_names: # ops_exists.append(self.include_op_code(xform, op_name)) usd_context.get_selection().set_selected_prim_paths(["/World/Sphere"], True) await ui_test.human_delay(3) await self.add_xform_ops_test(stage, "/World/Sphere", UsdGeom.XformOp.PrecisionDouble, False) prim = stage.GetObjectAtPath("/World/Sphere") xform = UsdGeom.Xformable(prim) #disable all properties for op in self.xform_op_names: index = self.get_index_op_code(xform, op) omni.kit.commands.execute("RemoveXformOpCommand", op_order_attr_path="/World/Sphere.xformOpOrder", op_name=op, op_order_index=index) await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op)) #enable all properties for op in self.xform_op_names: omni.kit.commands.execute("EnableXformOpCommand", op_attr_path="/World/Sphere." + op) await ui_test.human_delay(3) self.assertTrue(self.include_op_code(xform, op)) #undo omni.kit.commands.execute("Undo") await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op)) #disable all properties for op in self.xform_op_names: omni.kit.commands.execute("EnableXformOpCommand", op_attr_path="/World/Sphere." + op) await ui_test.human_delay(3) self.assertTrue(self.include_op_code(xform, op)) index = self.get_index_op_code(xform, op) omni.kit.commands.execute("RemoveXformOpCommand", op_order_attr_path="/World/Sphere.xformOpOrder", op_name=op, op_order_index=index) await ui_test.human_delay(3) self.assertTrue(not self.include_op_code(xform, op)) #undo omni.kit.commands.execute("Undo") await ui_test.human_delay(3) self.assertTrue(self.include_op_code(xform, op)) async def test_chate_rotation_ops(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) await ui_test.human_delay(3) command_rotation_ops = ["rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] rotation_ops = ["rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] #FIXME: if you fix rotateX, rotateY, rotateZ UI issue, uncomment below #rotation_ops = ["rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] sphere_prim = stage.GetObjectAtPath("/World/Sphere") sphere_xform = UsdGeom.Xformable(sphere_prim) current = "rotateXYZ" for rotation_op in command_rotation_ops: omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Sphere.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=False, auto_target_layer=True) self.assertTrue(self.include_op_code(sphere_xform, "xformOp:" + rotation_op)) self.assertTrue(not self.include_op_code(sphere_xform, "xformOp:" + current)) current = rotation_op #change rotation ops cube_prim = stage.GetObjectAtPath("/World/Cube") cube_xform = UsdGeom.Xformable(cube_prim) current = "rotateXYZ" for rotation_op in rotation_ops: omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=False, auto_target_layer=True) await ui_test.human_delay(3) self.assertTrue(self.include_op_code(cube_xform, "xformOp:" + rotation_op)) self.assertTrue(not self.include_op_code(cube_xform, "xformOp:" + current)) current = rotation_op #first set current value first test_value = Gf.Vec3d(30, 60, 90) attr_name ='xformOp:' + current attr = cube_prim.GetAttribute(attr_name) attr.Set(test_value) for rotation_op in rotation_ops: #create dest attribute first #and set it dest_attr_name = 'xformOp:' + rotation_op cube_prim.CreateAttribute(dest_attr_name, Sdf.ValueTypeNames.Double3,False).Set(Gf.Vec3d(0, 0, 180)) omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=False, auto_target_layer=True) dest_attr = cube_prim.GetAttribute(dest_attr_name) # confirm the value is transferred diff = test_value - dest_attr.Get() self.assertTrue(diff.GetLength() < 0.1) # set new test value dest_attr.Set(test_value) current = rotation_op async def test_invalid_commands(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() usd_context.get_selection().set_selected_prim_paths(["/World/Cube"], True) await ui_test.human_delay(3) #rotation_ops = ["rotateX", "rotateY", "rotateZ", "rotateXYZ", "rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX"] rotation_ops = ["rotateXZY", "rotateYXZ", "rotateYZX", "rotateZXY", "rotateZYX", "rotateXYZ"] #change rotation ops cube_prim = stage.GetObjectAtPath("/World/Cube") cube_xform = UsdGeom.Xformable(cube_prim) current = "rotateXYZ" #now test failing cases below for rotation_op in rotation_ops: omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:'+current), op_name='xformOp:' + current, dst_op_attr_name='xformOp:' + rotation_op, is_inverse_op=True, auto_target_layer=False) omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:rotateXYZ'), op_name='xformOp:rotateXYZ', dst_op_attr_name='/World/Cube.xformOp:rotateZYX', is_inverse_op=False, auto_target_layer=True) omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/Cube.xformOp:rotateZYX'), op_name='xformOp:rotateZYX', dst_op_attr_name='xformOp:rotateXYZ', is_inverse_op=True, auto_target_layer=True) omni.kit.commands.execute("EnableXformOpCommand", op_attr_path="/World/Sphere.testAttribute") omni.kit.commands.execute('ChangeRotationOp', src_op_attr_path=Sdf.Path('/World/testAttribute.xformOp:rotateZYX'), op_name='xformOp:rotateG', dst_op_attr_name='xformOp:rotateL', is_inverse_op=False, auto_target_layer=False) payload = PrimSelectionPayload( weakref.ref(stage), [Sdf.Path("/World/Sphere")]) omni.kit.commands.execute('AddXformOp', payload=payload, precision=UsdGeom.XformOp.TypeInvalid, rotation_order='XYZ', add_translate_op=True, add_rotateXYZ_op=True, add_orient_op=True, add_scale_op=True, add_transform_op=True, add_pivot_op=True) async def test_xform_op_utils(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() #get prim for sphere stage = usd_context.get_stage() usd_context.get_selection().set_selected_prim_paths(["/World/Sphere"], True) await ui_test.human_delay(3) self.assertTrue(get_op_type_name("Dummy") == None) # test _add_trs_op payload = PrimSelectionPayload( weakref.ref(stage), [Sdf.Path("/World/Sphere")]) settings = carb.settings.get_settings() default_xform_op_precision = settings.get("/persistent/app/primCreation/DefaultXformOpPrecision") default_rotation_order = settings.get("/persistent/app/primCreation/DefaultRotationOrder") # set to double settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", "Double") _add_trs_op(payload) omni.kit.commands.execute('Undo') settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", "Float") _add_trs_op(payload) omni.kit.commands.execute('Undo') settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", "Half") _add_trs_op(payload) omni.kit.commands.execute('Undo') #fail test settings.destroy_item("/persistent/app/primCreation/DefaultXformOpPrecision") settings.destroy_item("/persistent/app/primCreation/DefaultRotationOrder") _add_trs_op(payload) omni.kit.commands.execute('Undo') #recover default settings.set("/persistent/app/primCreation/DefaultXformOpPrecision", default_xform_op_precision) settings.set("/persistent/app/primCreation/DefaultRotationOrder", default_rotation_order) #get_op_precision self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Quatf) == UsdGeom.XformOp.PrecisionFloat) self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Matrix4d) == UsdGeom.XformOp.PrecisionDouble) self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Half3) == UsdGeom.XformOp.PrecisionHalf) self.assertTrue(get_op_precision(Sdf.ValueTypeNames.Color3d) == UsdGeom.XformOp.PrecisionDouble) self.assertTrue(get_inverse_op_Name(RESET_XFORM_STACK, True) == RESET_XFORM_STACK) self.assertTrue(get_inverse_op_Name("Dummy", True) == "!invert!Dummy") self.assertTrue(get_inverse_op_Name("!invert!xformOp:Dummy", False) == "xformOp:Dummy") self.assertTrue(get_op_attr_name(RESET_XFORM_STACK) == None)
16,863
Python
41.910941
162
0.631264
omniverse-code/kit/exts/omni.kit.property.transform/omni/kit/property/transform/tests/test_transform_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. ## import omni.kit.test import os import sys import unittest import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd from pathlib import Path from omni.kit import ui_test from pxr import Gf, UsdGeom from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows ) def include_op_code(xform : UsdGeom.Xformable, op_name): xform_ops = xform.GetOrderedXformOps() for op in xform_ops: print(op.GetOpName()) if op.GetOpName() == op_name: return True return False class TransformContextMenu(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 64) extension_root_folder = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) self._usd_path = extension_root_folder.joinpath("data/test_data/test_map") # After running each test async def tearDown(self): await wait_stage_loading() @unittest.skipIf(sys.platform.startswith("linux"), "Pyperclip fails on some TeamCity agents") async def test_transform_context_menu(self): await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda")) await wait_stage_loading() usd_context = omni.usd.get_context() stage = usd_context.get_stage() # get prim attributes torus_translate = stage.GetPrimAtPath("/World/Torus").GetAttribute('xformOp:translate') cone_translate = stage.GetPrimAtPath("/World/Cone").GetAttribute('xformOp:translate') torus_rotate = stage.GetPrimAtPath("/World/Torus").GetAttribute('xformOp:rotateXYZ') cone_rotate = stage.GetPrimAtPath("/World/Cone").GetAttribute('xformOp:rotateXYZ') torus_scale = stage.GetPrimAtPath("/World/Torus").GetAttribute('xformOp:scale') cone_scale = stage.GetPrimAtPath("/World/Cone").GetAttribute('xformOp:scale') # verify transforms different self.assertNotEqual(torus_translate.Get(), cone_translate.Get()) self.assertNotEqual(torus_rotate.Get(), cone_rotate.Get()) self.assertNotEqual(torus_scale.Get(), cone_scale.Get()) # select torus await select_prims(["/World/Torus"]) await ui_test.human_delay() # right click on transform header widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Transform'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu copy await ui_test.select_context_menu("Copy All Property Values in Transform", offset=ui_test.Vec2(10, 10)) # select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() # right click on Transform header widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Transform'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu paste await ui_test.select_context_menu("Paste All Property Values to Transform", offset=ui_test.Vec2(10, 10)) # verify transforms same self.assertEqual(torus_translate.Get(), cone_translate.Get()) self.assertEqual(torus_rotate.Get(), cone_rotate.Get()) self.assertEqual(torus_scale.Get(), cone_scale.Get()) # select torus await select_prims(["/World/Torus"]) await ui_test.human_delay() # right click on Transform header widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Transform'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Reset All Property Values in Transform", offset=ui_test.Vec2(10, 10)) # verify transforms reset self.assertEqual(torus_translate.Get(), Gf.Vec3d(0, 0, 0)) self.assertEqual(torus_rotate.Get(), Gf.Vec3d(0, 0, 0)) self.assertEqual(torus_scale.Get(), Gf.Vec3d(1, 1, 1)) async def open_property_map(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("test_transform_property.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() async def test_translate_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test translate disable/enable/delete widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Disable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(not include_op_code(xform, "xformOp:translate")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Enable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(include_op_code(xform, "xformOp:translate")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate'") #now test delete await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Delete", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone attr = prim.GetAttribute("xformOp:translate") self.assertTrue(not attr) async def test_pivot_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test translate:pivot disable/enable/delete widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate:pivot'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Disable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(not include_op_code(xform, "xformOp:translate:pivot")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate:pivot'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu resety await ui_test.select_context_menu("Enable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(include_op_code(xform, "xformOp:translate:pivot")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Translate:pivot'") #now test delete await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Delete", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone attr = prim.GetAttribute("xformOp:translate:pivot") self.assertTrue(not attr) async def test_scale_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test translate:pivot disable/enable/delete widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Scale'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu reset await ui_test.select_context_menu("Disable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(not include_op_code(xform, "xformOp:scale")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Scale'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) # context menu resety await ui_test.select_context_menu("Enable", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone self.assertTrue(include_op_code(xform, "xformOp:scale")) widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Scale'") #now test delete await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True) await ui_test.select_context_menu("Delete", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay() #make sure transslate is gone attr = prim.GetAttribute("xformOp:scale") self.assertTrue(not attr) async def test_rotate_context_menu(self): await self.open_property_map() usd_context = omni.usd.get_context() stage = usd_context.get_stage() #test disable/delete #right click on translate #select cone await select_prims(["/World/Cone"]) await ui_test.human_delay() prim = stage.GetObjectAtPath("/World/Cone") xform = UsdGeom.Xformable(prim) #test rotate rotation order change widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Rotate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) #find ZYX label widget = ui_test.find("RotationOrder//Frame/**/Label[*].text=='ZYX'") #switch and make sure it's changed await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) self.assertTrue(not include_op_code(xform, "xformOp:rotateXYZ")) self.assertTrue(include_op_code(xform, "xformOp:rotateZYX")) #chgange it to YZX widget = ui_test.find("Property//Frame/**/CollapsableFrame[*]/**/Label[*].text=='Rotate'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) #find YZX label widget = ui_test.find("RotationOrder//Frame/**/Label[*].text=='YZX'") await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10)) self.assertTrue(not include_op_code(xform, "xformOp:rotateZYX")) self.assertTrue(include_op_code(xform, "xformOp:rotateYZX"))
12,428
Python
43.231317
123
0.661168
omniverse-code/kit/exts/omni.kit.property.transform/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.3.5] - 2023-02-08 ### Fixed - Add Transform button's error for prims constructed from reference layer and doesn't have xformOpOrder attribute ## [1.3.4] - 2022-09-20 ### Added - Added listener for `ADDITIONAL_CHANGED_PATH_EVENT_TYPE` event in message bus to trigger additional property invalidation. ## [1.3.3] - 2022-08-03 - Linked scaling now works for resetting to defaults - Linked scaling no longer breaks when value is zero ## [1.3.2] - 2022-06-16 - Support Reset all attributes for the Transform Widget - Updating link scale button icon ## [1.3.1] - 2022-05-27 ### Changed - Support Copy/Paste all attribute for the Transform Widget - ## [1.3.0] - 2022-05-12 ### Changed - Offset mode updated to consider add/multiply operations ## [1.2.0] - 2022-04-28 ### Added - Option to link scale components - offset mode test ## [1.1.0] - 2022-03-09 ### Added - Added offset mode ## [1.0.2] - 2020-12-09 ### Changes - Added extension icon - Added readme - Updated preview image ## [1.0.1] - 2020-10-22 ### Added - removed `TransformPrimDelegate` so its now controlled by omni.kit.property.bundle ## [1.0.0] - 2020-10-7 ### Added - Created
1,250
Markdown
23.057692
123
0.6968
omniverse-code/kit/exts/omni.kit.property.transform/docs/README.md
# omni.kit.property.transform ## Introduction Property window extensions are for viewing and editing Usd Prim Attributes ## This extension supports editing of XForm transforms
180
Markdown
19.111109
74
0.805556
omniverse-code/kit/exts/omni.kit.property.transform/docs/index.rst
omni.kit.property.transform ########################### Property Transform Values .. toctree:: :maxdepth: 1 CHANGELOG
129
reStructuredText
9.833333
27
0.55814
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/__init__.py
from .scripts import * def deferred_capture(viewport_window, callback, is_hdr=False, subscription_name=None): def _get_subs_name(): import sys frame = sys._getframe(1).f_back f_code = frame.f_code filepath = f_code.co_filename lineno = frame.f_lineno return "VP capt %s:%d" % (filepath[-40:], lineno) class CaptureHelper: def capture_function(self, event): self.deferred_capture_subs = None if is_hdr: viewport_rp_resource = viewport_window.get_drawable_hdr_resource() else: viewport_rp_resource = viewport_window.get_drawable_ldr_resource() callback(viewport_rp_resource) if subscription_name is None: subscription_name = _get_subs_name() capture_helper = CaptureHelper() capture_helper.deferred_capture_subs = viewport_window.get_ui_draw_event_stream().create_subscription_to_pop( capture_helper.capture_function, name=subscription_name )
1,031
Python
32.290322
113
0.629486
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/external_drag_drop_helper.py
import os import re import pathlib from pxr import Sdf, Tf from typing import List from omni.kit.window.drop_support import ExternalDragDrop external_drag_drop = None def setup_external_drag_drop(window_name :str): global external_drag_drop destroy_external_drag_drop() external_drag_drop = ExternalDragDrop(window_name=window_name, drag_drop_fn=_on_ext_drag_drop) def destroy_external_drag_drop(): global external_drag_drop if external_drag_drop: external_drag_drop.destroy() external_drag_drop = None def _on_ext_drag_drop(edd: ExternalDragDrop, payload: List[str]): import omni.usd import omni.kit.undo import omni.kit.commands default_prim_path = Sdf.Path("/") stage = omni.usd.get_context().get_stage() if stage.HasDefaultPrim(): default_prim_path = stage.GetDefaultPrim().GetPath() re_audio = re.compile(r"^.*\.(wav|wave|ogg|oga|flac|fla|mp3|m4a|spx|opus)(\?.*)?$", re.IGNORECASE) re_usd = re.compile(r"^.*\.(usd|usda|usdc|usdz)(\?.*)?$", re.IGNORECASE) for source_url in edd.expand_payload(payload): if re_usd.match(source_url): try: import omni.kit.window.file omni.kit.window.file.open_stage(source_url.replace(os.sep, '/')) except ImportError: import carb carb.log_warn(f'Failed to import omni.kit.window.file - Cannot open stage {source_url}') return with omni.kit.undo.group(): for source_url in edd.expand_payload(payload): if re_audio.match(source_url): stem = pathlib.Path(source_url).stem path = default_prim_path.AppendChild(Tf.MakeValidIdentifier(stem)) omni.kit.commands.execute( "CreateAudioPrimFromAssetPath", path_to=path, asset_path=source_url, usd_context=omni.usd.get_context(), )
1,973
Python
33.034482
104
0.618348
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/commands.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.commands import omni.kit.viewport_legacy import omni.usd from pxr import Sdf, UsdGeom, Usd from typing import Union def get_viewport_window_from_name(viewport_name: str): vp = omni.kit.viewport_legacy.get_viewport_interface() instance = vp.get_instance(viewport_name) if instance: return vp.get_viewport_window(instance) return None class SetActiveViewportCameraCommand(omni.kit.commands.Command): """ Sets Viewport's actively bound camera to given camera at give path. Args: new_active_cam_path (Union[str, Sdf.Path): new camera path to bind to viewport. viewport_name (str): name of the viewport to set active camera (for multi-viewport). """ def __init__(self, new_active_cam_path: Union[str, Sdf.Path], viewport_name: str = ""): self._new_active_cam_path = str(new_active_cam_path) self._viewport_window = get_viewport_window_from_name(viewport_name) if not viewport_name and not self._viewport_window: self._viewport_window = omni.kit.viewport_legacy.get_default_viewport_window() self._prev_active_camera = None def do(self): if not self._viewport_window: return self._prev_active_camera = self._viewport_window.get_active_camera() self._viewport_window.set_active_camera(self._new_active_cam_path) def undo(self): if not self._viewport_window: return self._viewport_window.set_active_camera(self._prev_active_camera) class DuplicateFromActiveViewportCameraCommand(omni.kit.commands.Command): """ Duplicates Viewport's actively bound camera and bind active camera to the duplicated one. Args: viewport_name (str): name of the viewport to set active camera (for multi-viewport). """ def __init__(self, viewport_name: str = ""): self._viewport_name = viewport_name self._viewport_window = get_viewport_window_from_name(viewport_name) if not viewport_name and not self._viewport_window: self._viewport_window = omni.kit.viewport_legacy.get_default_viewport_window() self._usd_context_name = "" self._usd_context = omni.usd.get_context("") # TODO get associated usd_context from Viewport itself self._prev_active_camera = None def do(self): if not self._viewport_window: return self._prev_active_camera = self._viewport_window.get_active_camera() if self._prev_active_camera: stage = self._usd_context.get_stage() target_path = omni.usd.get_stage_next_free_path(stage, "/Camera", True) old_prim = stage.GetPrimAtPath(self._prev_active_camera) omni.kit.commands.execute("CreatePrim", prim_path=target_path, prim_type="Camera") new_prim = stage.GetPrimAtPath(target_path) if old_prim and new_prim: # copy attributes timeline = omni.timeline.get_timeline_interface() timecode = timeline.get_current_time() * stage.GetTimeCodesPerSecond() for attr in old_prim.GetAttributes(): value = attr.Get(timecode) if value is not None: new_prim.CreateAttribute(attr.GetName(), attr.GetTypeName()).Set(value) default_prim = stage.GetDefaultPrim() # OM-35156: It's possible that transform of default prim is not identity. # And it tries to copy a camera that's outside of the default prim tree. # It needs to be transformed to the default prim space. if default_prim and default_prim.IsA(UsdGeom.Xformable): default_prim_world_mtx = omni.usd.get_world_transform_matrix(default_prim, timecode) old_camera_prim_world_mtx = omni.usd.get_world_transform_matrix(old_prim, timecode) new_camera_prim_local_mtx = old_camera_prim_world_mtx * default_prim_world_mtx.GetInverse() omni.kit.commands.execute( "TransformPrim", path=new_prim.GetPath(), new_transform_matrix=new_camera_prim_local_mtx ) omni.usd.editor.set_no_delete(new_prim, False) omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path=target_path, viewport_name=self._viewport_name ) def undo(self): pass omni.kit.commands.register_all_commands_in_module(__name__)
5,022
Python
42.301724
113
0.644166
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/__init__.py
from .context_menu import * from .viewport import * from .commands import *
75
Python
24.333325
27
0.76
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/context_menu.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import omni.ext import carb import carb.settings import omni.kit.ui from .viewport import get_viewport_interface from .external_drag_drop_helper import setup_external_drag_drop, destroy_external_drag_drop class Extension(omni.ext.IExt): def on_startup(self): # get window event stream viewport_win = get_viewport_interface().get_viewport_window() # on_mouse_event called when event dispatched if viewport_win: self._stage_event_sub = viewport_win.get_mouse_event_stream().create_subscription_to_pop(self.on_mouse_event) self._menu_path = "Window/New Viewport Window" self._editor_menu = omni.kit.ui.get_editor_menu() if self._editor_menu is not None: self._menu = self._editor_menu.add_item(self._menu_path, self._on_menu_click, False, priority=200) # external drag/drop if viewport_win: setup_external_drag_drop("Viewport") def on_shutdown(self): # remove event self._stage_event_sub = None destroy_external_drag_drop() def _on_menu_click(self, menu, toggled): async def new_viewport(): await omni.kit.app.get_app().next_update_async() viewportFactory = get_viewport_interface() viewportHandle = viewportFactory.create_instance() window = viewportFactory.get_viewport_window(viewportHandle) window.set_window_size(350, 350) asyncio.ensure_future(new_viewport()) def on_mouse_event(self, event): # check its expected event if event.type == int(omni.kit.ui.MenuEventType.ACTIVATE): if carb.settings.get_settings().get("/exts/omni.kit.window.viewport/showContextMenu"): self.show_context_menu(event.payload) def show_context_menu(self, payload: dict): viewport_win = get_viewport_interface().get_viewport_window() usd_context_name = viewport_win.get_usd_context_name() #This is actuall world-position ! world_position = payload.get('mouse_pos_x', None) if world_position is not None: world_position = ( world_position, payload['mouse_pos_y'], payload['mouse_pos_z'] ) try: from omni.kit.context_menu import ViewportMenu ViewportMenu.show_menu( usd_context_name, payload.get('prim_path', None), world_position ) except ImportError: carb.log_error('omni.kit.context_menu must be loaded to use the context menu') @staticmethod def add_menu(menu_dict): """ Add the menu to the end of the context menu. Return the object that should be alive all the time. Once the returned object is destroyed, the added menu is destroyed as well. """ return omni.kit.context_menu.add_menu(menu_dict, "MENU", "omni.kit.window.viewport") @staticmethod def add_create_menu(menu_dict): """ Add the menu to the end of the stage context create menu. Return the object that should be alive all the time. Once the returned object is destroyed, the added menu is destroyed as well. """ return omni.kit.context_menu.add_menu(menu_dict, "CREATE", "omni.kit.window.viewport")
3,774
Python
39.159574
121
0.653683
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/viewport.py
# Because ExtensionWindowHandle is used, we should get rid of it really: import omni.kit.extensionwindow import asyncio import carb import copy from .._viewport_legacy import * from omni.hydra.engine.stats import HydraEngineStats, get_mem_stats import warnings def get_viewport_interface(): """Returns cached :class:`omni.kit.viewport_legacy.IViewport` interface""" if not hasattr(get_viewport_interface, "viewport"): get_viewport_interface.viewport = acquire_viewport_interface() return get_viewport_interface.viewport def get_default_viewport_window(): """Returns default (first) Viewport Window if available""" viewport = get_viewport_interface() if viewport: return viewport.get_viewport_window() return None def menu_update(menu_path, visible): # get the correct viewport window as there can be multiple vp_iface = omni.kit.viewport_legacy.get_viewport_interface() viewports = vp_iface.get_instance_list() for viewport in viewports: if menu_path.endswith(vp_iface.get_viewport_window_name(viewport)): viewport_window = vp_iface.get_viewport_window(viewport) viewport_window.show_hide_window(visible) omni.kit.ui.get_editor_menu().set_value(menu_path, visible) async def _query_next_picked_world_position_async(self) -> carb.Double3: """Asynchronous version of :func:`IViewportWindow.query_next_picked_world_position`. Return a ``carb.Double3``. If no position is sampled, the returned object is None.""" f = asyncio.Future() def cb(pos): f.set_result(copy.deepcopy(pos)) self.query_next_picked_world_position(cb) return await f IViewportWindow.query_next_picked_world_position_async = _query_next_picked_world_position_async def get_nested_gpu_profiler_result(vw: IViewportWindow, max_indent: int = 1): warnings.warn( "IViewportWindow.get_nested_gpu_profiler_result is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).get_nested_gpu_profiler_result(max_indent) def get_gpu_profiler_result(vw: IViewportWindow): warnings.warn( "IViewportWindow.get_gpu_profiler_result is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).get_gpu_profiler_result() def save_gpu_profiler_result_to_json(vw: IViewportWindow, file_name: str): warnings.warn( "IViewportWindow.save_gpu_profiler_result_to_json is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).save_gpu_profiler_result_to_json(file_name) def reset_gpu_profiler_containers(vw: IViewportWindow): warnings.warn( "IViewportWindow.reset_gpu_profiler_containers is deprecated, use omni.hydra.engine.stats.HydraEngineStats instead", DeprecationWarning ) return HydraEngineStats(vw.get_usd_context_name(), vw.get_active_hydra_engine()).reset_gpu_profiler_containers() def get_mem_stats_result(vw: IViewportWindow, detailed: bool = False): warnings.warn( "IViewportWindow.get_mem_stats_result is deprecated, use omni.hydra.engine.stats.get_mem_stats instead", DeprecationWarning ) return get_mem_stats(detailed) IViewportWindow.get_nested_gpu_profiler_result = get_nested_gpu_profiler_result IViewportWindow.get_gpu_profiler_result = get_gpu_profiler_result IViewportWindow.save_gpu_profiler_result_to_json = save_gpu_profiler_result_to_json IViewportWindow.reset_gpu_profiler_containers = reset_gpu_profiler_containers IViewportWindow.get_mem_stats_result = get_mem_stats_result
3,877
Python
40.255319
128
0.740005
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/scripts/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.window.viewport/omni/kit/viewport_legacy/tests/camera_tests.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import os import tempfile import uuid import carb import omni.kit.commands import omni.kit.test import omni.kit.viewport_legacy from pxr import Gf, Usd, UsdGeom, Sdf from omni.kit.test_suite.helpers import arrange_windows class TestViewportWindowCamera(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # After running each test async def tearDown(self): pass async def test_builtin_camera_settings(self): async def test_builtin_camera_settings_inner(modify_camera=False): await omni.usd.get_context().new_stage_async() # Waiting one frame after the new stage, so in sync load cases # the USD context had a chance to launch a preSync event await omni.kit.app.get_app().next_update_async() viewport_window = omni.kit.viewport_legacy.get_default_viewport_window() omni.kit.commands.execute("CreatePrim", prim_type="Sphere") camera_paths = ["/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"] camera_names = ["Perspective", "Front", "Top", "Right"] positions = [] targets = [] if modify_camera: viewport_window.set_camera_position("/OmniverseKit_Persp", 100, 200, 300, True) viewport_window.set_camera_target("/OmniverseKit_Persp", 300, 200, 100, True) viewport_window.set_active_camera("/OmniverseKit_Front") for i in range(len(camera_paths)): position = viewport_window.get_camera_position(camera_paths[i]) self.assertTrue(position[0]) positions.append(Gf.Vec3d(position[1], position[2], position[3])) target = viewport_window.get_camera_target(camera_paths[i]) self.assertTrue(target[0]) targets.append(Gf.Vec3d(target[1], target[2], target[3])) active_camera = viewport_window.get_active_camera() with tempfile.TemporaryDirectory() as tmpdirname: tmpfilename = os.path.join(tmpdirname, f"camTest_{str(uuid.uuid4())}.usda") carb.log_info("Saving temp camera path as %s" % (tmpfilename)) await omni.usd.get_context().save_as_stage_async(tmpfilename) await omni.usd.get_context().reopen_stage_async() await omni.kit.app.get_app().next_update_async() for i in range(len(camera_names)): carb.log_info("Testing %s" % (camera_names[i])) # Position only saved for Persp camera if i == 0: saved_position = viewport_window.get_camera_position(camera_paths[i]) self.assertTrue(saved_position[0]) saved_position = Gf.Vec3d(saved_position[1], saved_position[2], saved_position[3]) carb.log_info("Comparing Positions: (%f,%f,%f) to (%f,%f,%f)" % (positions[i][0], positions[i][1], positions[i][2], saved_position[0], saved_position[1], saved_position[2])) self.assertTrue( Gf.IsClose(positions[i], saved_position, 0.000001), f"Camera position mismatched! {positions[i]} is not close to {saved_position}", ) saved_target = viewport_window.get_camera_target(camera_paths[i]) self.assertTrue(saved_target[0]) saved_target = Gf.Vec3d(saved_target[1], saved_target[2], saved_target[3]) active_camera_saved = viewport_window.get_active_camera() carb.log_info("Comparing Targets: (%f,%f,%f) to (%f,%f,%f)" % (targets[i][0], targets[i][1], targets[i][2], saved_target[0], saved_target[1], saved_target[2])) self.assertTrue( Gf.IsClose(targets[i], saved_target, 0.000001), f"Camera target mismatched! {targets[i]} is not close to {saved_target}", ) if modify_camera and i == 0: self.assertTrue(Gf.IsClose(positions[i], Gf.Vec3d(100, 200, 300), 0.000001)) self.assertTrue(Gf.IsClose(targets[i], Gf.Vec3d(300, 200, 100), 0.000001)) self.assertTrue( active_camera == active_camera_saved, f"Active camera mismatched! {active_camera} is not equal to {active_camera_saved}", ) # test default camera settings carb.log_info("Testing default camera settings") await test_builtin_camera_settings_inner() # test modified camera settings carb.log_info("Testing modified camera settings") await test_builtin_camera_settings_inner(True) async def test_camera_duplicate_from_static_active_camera(self): # Test for OM-35156 await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() stage = omni.usd.get_context().get_stage() prim = UsdGeom.Xform.Define(stage, "/World") stage.SetDefaultPrim(prim.GetPrim()) default_prim = stage.GetDefaultPrim() UsdGeom.XformCommonAPI(default_prim).SetTranslate(Gf.Vec3d(100, 0, 0)) perspective_camera = stage.GetPrimAtPath("/OmniverseKit_Persp") persp_camera_world_mtx = omni.usd.get_world_transform_matrix(perspective_camera) default_prim_world_mtx = omni.usd.get_world_transform_matrix(default_prim) omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path=perspective_camera.GetPath(), viewport_name="" ) await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute("DuplicateFromActiveViewportCamera") await omni.kit.app.get_app().next_update_async() # The name of it will be Camera new_camera_prim = stage.GetPrimAtPath(default_prim.GetPath().AppendElementString("Camera")) new_camera_local_mtx = omni.usd.get_local_transform_matrix(new_camera_prim) local_mtx = persp_camera_world_mtx * default_prim_world_mtx.GetInverse() self.assertTrue(Gf.IsClose(new_camera_local_mtx, local_mtx, 0.000001)) async def test_camera_duplicate_from_animated_active_camera(self): # Test for OM-33581 layer_with_animated_camera = """\ #usda 1.0 ( customLayerData = { } defaultPrim = "World" endTimeCode = 619 framesPerSecond = 24 metersPerUnit = 0.01 startTimeCode = 90 timeCodesPerSecond = 24 upAxis = "Y" ) def Xform "World" ( kind = "assembly" ) { def Camera "SHOTCAM" { float2 clippingRange = (10, 10000) custom bool depthOfField = 0 float focalLength = 35 float focalLength.timeSamples = { 172: 35, 173: 34.650208 } float focusDistance = 5 float fStop = 5.6 float horizontalAperture = 35.999928 float verticalAperture = 20.22853 float3 xformOp:rotateXYZ.timeSamples = { 90: (8.786562, -19.858515, -1.2905762), 91: (8.744475, -19.858515, -1.274945) } float3 xformOp:scale.timeSamples = { 90: (12.21508, 12.21508, 12.21508) } double3 xformOp:translate.timeSamples = { 90: (-462.44292428348126, 1734.9897515804505, -2997.4519412288555), 151: (-462.4429242834828, 1734.9897515804498, -2997.451941228857) } uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] } } """ format = Sdf.FileFormat.FindByExtension(".usd") root_layer = Sdf.Layer.CreateAnonymous("world.usd", format) root_layer.ImportFromString(layer_with_animated_camera) stage = Usd.Stage.Open(root_layer) await omni.usd.get_context().attach_stage_async(stage) await omni.kit.app.get_app().next_update_async() old_camera = stage.GetPrimAtPath("/World/SHOTCAM") omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path="/World/SHOTCAM", viewport_name="" ) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute("DuplicateFromActiveViewportCamera") await omni.kit.app.get_app().next_update_async() new_camera = stage.GetPrimAtPath("/World/Camera") self.assertTrue(new_camera) timeline = omni.timeline.get_timeline_interface() timecode = timeline.get_current_time() * stage.GetTimeCodesPerSecond() old_matrix = omni.usd.get_world_transform_matrix(old_camera, timecode) new_matrix = omni.usd.get_world_transform_matrix(new_camera) self.assertTrue(Gf.IsClose(new_matrix, old_matrix, 0.000001)) # Set time code to the second timecode of rotateXYZ, so they are not equal. timeline.set_current_time(float(91.0 / stage.GetTimeCodesPerSecond())) timecode = timeline.get_current_time() * stage.GetTimeCodesPerSecond() old_matrix = omni.usd.get_world_transform_matrix(old_camera, timecode) self.assertFalse(Gf.IsClose(new_matrix, old_matrix, 0.000001)) # Make another duplicate that's duplicated from updated time. omni.kit.commands.execute( "SetActiveViewportCamera", new_active_cam_path="/World/SHOTCAM", viewport_name="" ) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() omni.kit.commands.execute("DuplicateFromActiveViewportCamera") await omni.kit.app.get_app().next_update_async() new_camera = stage.GetPrimAtPath("/World/Camera_01") self.assertTrue(new_camera) old_matrix = omni.usd.get_world_transform_matrix(old_camera, timecode) new_matrix = omni.usd.get_world_transform_matrix(new_camera) self.assertTrue(Gf.IsClose(new_matrix, old_matrix, 0.000001)) async def test_layer_clear_to_remove_camera_deltas(self): # Test for OM-47804 await omni.usd.get_context().new_stage_async() for _ in range(10): # Create anonymous layer and set edit target stage = omni.usd.get_context().get_stage() replicator_layer = None for layer in stage.GetLayerStack(): if layer.GetDisplayName() == "Replicator": replicator_layer = layer break if replicator_layer is None: root = stage.GetRootLayer() replicator_layer = Sdf.Layer.CreateAnonymous(tag="Replicator") root.subLayerPaths.append(replicator_layer.identifier) omni.usd.set_edit_target_by_identifier(stage, replicator_layer.identifier) # Clear prim and assert not valid replicator_layer.Clear() self.assertFalse(stage.GetPrimAtPath("/ReplicatorPrim").IsValid()) # Define some prim on the layer stage.DefinePrim("/ReplicatorPrim", "Camera")
12,035
Python
45.832685
197
0.602659
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/create_prims.py
import os import random import carb import omni.usd import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux def create_test_stage(): stage = omni.usd.get_context().get_stage() rootname = stage.GetDefaultPrim().GetPath().pathString prim_list1 = [] prim_list2 = [] # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False ) # create material 1 mtl_created_list = [] omni.kit.commands.execute( "CreateAndBindMdlMaterialFromLibrary", mdl_name="OmniPBR.mdl", mtl_name="OmniPBR", mtl_created_list=mtl_created_list, ) mtl_path1 = mtl_created_list[0] # create material 2 mtl_created_list = [] omni.kit.commands.execute( "CreateAndBindMdlMaterialFromLibrary", mdl_name="OmniGlass.mdl", mtl_name="OmniGlass", mtl_created_list=mtl_created_list, ) mtl_path2 = mtl_created_list[0] # create prims & bind material random_list = {} samples = 100 for index in random.sample(range(samples), int(samples / 2)): random_list[index] = 0 strengths = [UsdShade.Tokens.strongerThanDescendants, UsdShade.Tokens.weakerThanDescendants] for index in range(samples): prim_path = omni.usd.get_stage_next_free_path(stage, "{}/TestCube_{}".format(rootname, index), False) omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="Cube") if index in random_list: omni.kit.commands.execute( "BindMaterial", prim_path=prim_path, material_path=mtl_path1, strength=strengths[index & 1] ) prim_list1.append(prim_path) elif (index & 3) != 0: omni.kit.commands.execute( "BindMaterial", prim_path=prim_path, material_path=mtl_path2, strength=strengths[index & 1] ) prim_list2.append(prim_path) return [(mtl_path1, prim_list1), (mtl_path2, prim_list2)] def create_and_select_cube(): stage = omni.usd.get_context().get_stage() rootname = stage.GetDefaultPrim().GetPath().pathString prim_path = "{}/Cube".format(rootname) # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path=prim_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100} ) return prim_path
2,464
Python
31.012987
109
0.635958
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/context_tests.py
import asyncio import carb import omni.usd import omni.kit.test import omni.kit.viewport_legacy import omni.timeline from pxr import Usd, UsdGeom, Gf, Sdf from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class ViewportContextTest(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() # After running each test async def tearDown(self): await wait_stage_loading() async def _create_test_stage(self): # Create the objects test_list = omni.kit.viewport_legacy.tests.create_test_stage() # Wait so that the test does not exit before MDL loaded and crash on exit. while True: try: event, payload = await asyncio.wait_for(self._usd_context.next_stage_event_async(), timeout=60.0) if event == int(omni.usd.StageEventType.ASSETS_LOADED): break except asyncio.TimeoutError: _, files_loaded, total_files = self._usd_context.get_stage_loading_status() if files_loaded == total_files: carb.log_warn("Timed out waiting for ASSETS_LOADED event. Is MDL already loaded?") break return test_list # Simulate a mouse-click-selection at pos (x,y) in viewport async def _simulate_mouse_selection(self, viewport, pos): app = omni.kit.app.get_app() mouse = omni.appwindow.get_default_app_window().get_mouse() input_provider = carb.input.acquire_input_provider() async def simulate_mouse_click(): input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.MOVE, pos, 0, pos) input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.LEFT_BUTTON_DOWN, pos, 0, pos) await app.next_update_async() input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.LEFT_BUTTON_UP, pos, 0, pos) await app.next_update_async() # You're guess as good as mine. # Need to start and end with one wait, then need 12 more waits for mouse click loop_counts = (1, 5) for i in range(loop_counts[0]): await app.next_update_async() # Is this really to sync up carb and imgui state ? for i in range(loop_counts[1]): await simulate_mouse_click() # Enable picking and do the selection viewport.request_picking() await simulate_mouse_click() # Almost done! for i in range(loop_counts[0]): await app.next_update_async() # Actual test, notice it is "async" function, so "await" can be used if needed # # But why does this test exist in Viewport?? async def test_bound_objects(self): return # Create the objects usd_context, test_list = self._usd_context, await self._create_test_stage() self.assertIsNotNone(usd_context) self.assertIsNotNone(test_list) objects = {} stage = omni.usd.get_context().get_stage() objects["stage"] = stage for mtl, mtl_prims in test_list: # Select material prim objects["prim_list"] = [stage.GetPrimAtPath(Sdf.Path(mtl))] # Run select_prims_using_material omni.kit.context_menu.get_instance().select_prims_using_material(objects) # Verify selected prims prims = omni.usd.get_context().get_selection().get_selected_prim_paths() self.assertTrue(prims == mtl_prims) async def test_create_and_select(self): viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface() viewport = viewport_interface.get_viewport_window() viewport.set_enabled_picking(True) viewport.set_window_pos(0, 0) viewport.set_window_size(400, 400) # Create the objects usd_context, cube_path = self._usd_context, omni.kit.viewport_legacy.tests.create_and_select_cube() self.assertIsNotNone(usd_context) self.assertIsNotNone(cube_path) self.assertEqual([], self._usd_context.get_selection().get_selected_prim_paths()) await self._simulate_mouse_selection(viewport, (200, 230)) self.assertEqual([cube_path], self._usd_context.get_selection().get_selected_prim_paths())
4,610
Python
38.75
142
0.642082
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/mouse_raycast_tests.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import carb.input import omni.appwindow import omni.kit.commands import omni.kit.test import omni.kit.viewport_legacy import omni.usd from carb.input import KeyboardInput as Key from omni.kit.test_suite.helpers import arrange_windows class TestViewportMouseRayCast(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows(hide_viewport=True) self._input_provider = carb.input.acquire_input_provider() app_window = omni.appwindow.get_default_app_window() self._mouse = app_window.get_mouse() self._keyboard = app_window.get_keyboard() self._app = omni.kit.app.get_app() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface() self._viewport = viewport_interface.get_viewport_window() self._viewport.set_enabled_picking(True) self._viewport.set_window_pos(0, 0) self._viewport.set_window_size(400, 400) self._viewport.show_hide_window(True) await self._app.next_update_async() # After running each test async def tearDown(self): pass async def test_viewport_mouse_raycast(self): stage_update = omni.stageupdate.get_stage_update_interface() stage_subscription = stage_update.create_stage_update_node( "viewport_mouse_raycast_test", on_raycast_fn=self._on_ray_cast ) test_data = [ ( "/OmniverseKit_Persp", (499.058, 499.735, 499.475), (-0.848083, -0.23903, -0.472884), ), ( "/OmniverseKit_Front", (-127.551, 165.44, 30000), (0, 0, -1), ), ( "/OmniverseKit_Top", (127.551, 30000, 165.44), (0, -1, 0), ), ( "/OmniverseKit_Right", (-30000, 165.44, -127.551), (1, 0, 0), ), ] for data in test_data: self._raycast_data = None self._viewport.set_active_camera(data[0]) await self._app.next_update_async() self._input_provider.buffer_mouse_event( self._mouse, carb.input.MouseEventType.MOVE, (100, 100), 0, (100, 100) ) await self._app.next_update_async() # Hold SHIFT down to start raycast self._input_provider.buffer_keyboard_key_event( self._keyboard, carb.input.KeyboardEventType.KEY_PRESS, Key.LEFT_SHIFT, 0 ) await self._app.next_update_async() self._input_provider.buffer_keyboard_key_event( self._keyboard, carb.input.KeyboardEventType.KEY_RELEASE, Key.LEFT_SHIFT, 0 ) await self._app.next_update_async() self._input_provider.buffer_mouse_event(self._mouse, carb.input.MouseEventType.MOVE, (0, 0), 0, (0, 0)) await self._app.next_update_async() self.assertIsNotNone(self._raycast_data) self.assertAlmostEqual(self._raycast_data[0][0], data[1][0], 3) self.assertAlmostEqual(self._raycast_data[0][1], data[1][1], 3) self.assertAlmostEqual(self._raycast_data[0][2], data[1][2], 3) self.assertAlmostEqual(self._raycast_data[1][0], data[2][0], 3) self.assertAlmostEqual(self._raycast_data[1][1], data[2][1], 3) self.assertAlmostEqual(self._raycast_data[1][2], data[2][2], 3) stage_subscription = None def _on_ray_cast(self, orig, dir, input): self._raycast_data = (orig, dir) print(self._raycast_data)
4,239
Python
35.551724
115
0.598726
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/drag_drop_multi_material_viewport.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import os import omni.kit.app import omni.kit.test import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows ) from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class ZZViewportDragDropMaterialMulti(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) # After running each test async def tearDown(self): await wait_stage_loading() def _verify_material(self, stage, mtl_name, to_select): # verify material created prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()] self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths) self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths) # verify bound material if to_select: for prim_path in to_select: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, f"/World/Looks/{mtl_name}") def choose_material(self, mdl_list, excluded_list): # need to skip any multi-subid materials exclude_multi = {} for _, mdl_path, _ in mdl_list: mdl_name = os.path.splitext(os.path.basename(mdl_path))[0] if not mdl_name in exclude_multi: exclude_multi[mdl_name] = 1 else: exclude_multi[mdl_name] += 1 for _, mdl_path, _ in mdl_list: mdl_name = os.path.splitext(os.path.basename(mdl_path))[0] if mdl_name not in excluded_list and exclude_multi[mdl_name] < 2: return mdl_path, mdl_name return None, None async def test_l1_drag_drop_single_material_viewport(self): from carb.input import KeyboardInput await ui_test.find("Content").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"] await wait_stage_loading() # verify bound materials before DnD for prim_path, material_path in [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", "/World/Looks/OmniPBR"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")]: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) # drag to center of viewport window # NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used viewport_window = ui_test.find("Viewport") viewport_window = ui_test.find("Viewport") await viewport_window.focus() drag_target = viewport_window.center # select prim await select_prims(to_select) # wait for UI to update await ui_test.human_delay() # get paths mdl_list = await omni.kit.material.library.get_mdl_list_async() mdl_path1, mdl_name = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"]) # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path1, drag_target=drag_target) # wait for material to load & UI to refresh await wait_stage_loading() # verify bound materials after DnD - Should be unchanged for prim_path, material_path in [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", f"/World/Looks/{mdl_name}"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")]: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) async def test_l1_drag_drop_multi_material_viewport(self): from carb.input import KeyboardInput await ui_test.find("Content").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"] expected_list = [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", "/World/Looks/OmniPBR"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")] await wait_stage_loading() # verify bound materials before DnD for prim_path, material_path in expected_list: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path) # drag to center of viewport window # NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used viewport_window = ui_test.find("Viewport") await viewport_window.focus() drag_target = viewport_window.center # select prim await select_prims(to_select) # wait for UI to update await ui_test.human_delay() # get paths mdl_list = await omni.kit.material.library.get_mdl_list_async() mdl_path1, mdl_name1 = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"]) mdl_path2, mdl_name2 = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR", mdl_name1]) # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: dir_url = os.path.dirname(os.path.commonprefix([mdl_path1, mdl_path2])) filenames = [os.path.basename(url) for url in [mdl_path1, mdl_path2]] await content_browser_helper.drag_and_drop_tree_view(dir_url, names=filenames, drag_target=drag_target) # wait for material to load & UI to refresh await wait_stage_loading() # verify bound materials after DnD - Should be unchanged for prim_path, material_path in expected_list: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertEqual(bound_material.GetPrim().IsValid(), True) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path)
7,880
Python
46.475903
219
0.65698
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/window_tests.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.test from omni.kit.viewport.utility import get_active_viewport_window class TestViewportWindowShowHide(omni.kit.test.AsyncTestCase): async def test_window_show_hide(self): # Test that multiple show-hide invocations of a window doesn't crash await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() # Show hide 10 times, and wait 60 frames between a show hide # This does make the test take 10 seconds, but might be a bit # more representative of real-world usage when it. nwaits = 60 nitrations = 10 viewport, viewport_window = get_active_viewport_window() for x in range(nitrations): viewport_window.visible = True for x in range(nwaits): await omni.kit.app.get_app().next_update_async() viewport_window.visible = False for x in range(nwaits): await omni.kit.app.get_app().next_update_async() for x in range(nitrations): viewport_window.visible = False for x in range(nwaits): await omni.kit.app.get_app().next_update_async() viewport_window.visible = True for x in range(nwaits): await omni.kit.app.get_app().next_update_async()
1,774
Python
40.279069
76
0.666291
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/__init__.py
from .draw_tests import * from .context_tests import * from .create_prims import * from .camera_tests import * from .mouse_raycast_tests import * # these tests must be last or test_viewport_mouse_raycast fails. from .multi_descendents_dialog import * from .drag_drop_multi_material_viewport import * from .drag_drop_looks_material_viewport import *
349
Python
33.999997
64
0.776504
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/draw_tests.py
import carb.dictionary import omni.usd import omni.kit.test import omni.kit.viewport_legacy import omni.timeline from pxr import Usd, UsdGeom, Gf, Sdf from omni.kit.test_suite.helpers import arrange_windows # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class ViewportDrawTest(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_ui_draw_event_payload(self): dictionary_interface = carb.dictionary.get_dictionary() viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface() viewport = viewport_interface.get_viewport_window() draw_event_stream = viewport.get_ui_draw_event_stream() CAM_PATH = "/OmniverseKit_Persp" usd_context = omni.usd.get_context() stage = usd_context.get_stage() cam_prim = stage.GetPrimAtPath(CAM_PATH) camera = UsdGeom.Camera(cam_prim) timeline_interface = omni.timeline.get_timeline_interface() timecode = timeline_interface.get_current_time() * stage.GetTimeCodesPerSecond() gf_camera = camera.GetCamera(timecode) expected_transform = gf_camera.transform expected_viewport_rect = viewport.get_viewport_rect() def uiDrawCallback(event): events_data = dictionary_interface.get_dict_copy(event.payload) vm = events_data["viewMatrix"] viewMatrix = Gf.Matrix4d( vm[0], vm[1], vm[2], vm[3], vm[4], vm[5], vm[6], vm[7], vm[8], vm[9], vm[10], vm[11], vm[12], vm[13], vm[14], vm[15], ).GetInverse() self.assertTrue(Gf.IsClose(expected_transform, viewMatrix, 0.00001)) vr = events_data["viewportRect"] self.assertAlmostEqual(expected_viewport_rect[0], vr[0]) self.assertAlmostEqual(expected_viewport_rect[1], vr[1]) self.assertAlmostEqual(expected_viewport_rect[2], vr[2]) self.assertAlmostEqual(expected_viewport_rect[3], vr[3]) subscription = draw_event_stream.create_subscription_to_pop(uiDrawCallback) await omni.kit.app.get_app().next_update_async()
2,646
Python
36.28169
142
0.608466
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/drag_drop_looks_material_viewport.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import os import omni.kit.app import omni.kit.test import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class ZZViewportDragDropMaterialLooks(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() await omni.usd.get_context().new_stage_async() # After running each test async def tearDown(self): await wait_stage_loading() def choose_material(self, mdl_list, excluded_list): for _, mdl_path, _ in mdl_list: mdl_name = os.path.splitext(os.path.basename(mdl_path))[0] if mdl_name not in excluded_list: return mdl_path, mdl_name return None, None async def test_l1_drag_drop_single_material_viewport_looks(self): from carb.input import KeyboardInput await ui_test.find("Content").focus() usd_context = omni.usd.get_context() stage = usd_context.get_stage() # create default prim omni.kit.commands.execute("CreatePrim", prim_path="/World", prim_type="Xform", select_new_prim=False) stage.SetDefaultPrim(stage.GetPrimAtPath("/World")) # drag to center of viewport window # NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used viewport_window = ui_test.find("Viewport") await viewport_window.focus() drag_target = viewport_window.center # get paths mdl_list = await omni.kit.material.library.get_mdl_list_async() mdl_path1, mdl_name = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"]) # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path1, drag_target=drag_target) # wait for material to load & UI to refresh await wait_stage_loading() # verify /World/Looks type after drag/drop prim = stage.GetPrimAtPath("/World/Looks") self.assertEqual(prim.GetTypeName(), "Scope")
2,792
Python
38.899999
126
0.698782
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/multi_descendents_dialog.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.test import omni.usd import omni.ui as ui from omni.kit.test.async_unittest import AsyncTestCase from pxr import Sdf, UsdShade from omni.kit import ui_test from omni.kit.viewport.utility import get_ui_position_for_prim from omni.kit.material.library.test_helper import MaterialLibraryTestHelper from omni.kit.test_suite.helpers import ( arrange_windows, open_stage, get_test_data_path, wait_stage_loading, handle_multiple_descendents_dialog, Vec2 ) from omni.kit.material.library.test_helper import MaterialLibraryTestHelper from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper # has to be last or test_viewport_mouse_raycast fails. class ZZMultipleDescendentsDragDropTest(AsyncTestCase): # Before running each test async def setUp(self): manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.ui_test", True) manager.set_extension_enabled_immediate("omni.kit.window.status_bar", True) manager.set_extension_enabled_immediate("omni.kit.window.content_browser", True) # load stage await open_stage(get_test_data_path(__name__, "empty_stage.usda")) # After running each test async def tearDown(self): await wait_stage_loading() async def test_l1_drag_drop_material_viewport(self): viewport_window = await arrange_windows(topleft_width=0) ui_test_window = ui_test.find("Viewport") await ui_test_window.focus() # get single and multi-subid materials single_material = None multi_material = None mdl_list = await omni.kit.material.library.get_mdl_list_async() for mtl_name, mdl_path, submenu in mdl_list: if "Presets" in mdl_path or "Base" in mdl_path: continue if not single_material and not submenu: single_material = (mtl_name, mdl_path) if not multi_material and submenu: multi_material = (mtl_name, mdl_path) # verify both tests have run self.assertTrue(single_material != None) self.assertTrue(multi_material != None) async def verify_prims(stage, mtl_name, verify_prim_list): # verify material prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()] self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths) self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths) # verify bound material if verify_prim_list: for prim_path in verify_prim_list: prim = stage.GetPrimAtPath(prim_path) bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() self.assertTrue(bound_material.GetPrim().IsValid() == True) self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}") # undo omni.kit.undo.undo() # verify material was removed prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()] self.assertFalse(f"/World/Looks/{mtl_name}" in prim_paths) async def test_mtl(stage, material, verify_prim_list, drag_target): mtl_name, mdl_path = material # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # handle create material dialog async with MaterialLibraryTestHelper() as material_library_helper: await material_library_helper.handle_create_material_dialog(mdl_path, mtl_name) # wait for material to load & UI to refresh await wait_stage_loading() # verify created/bound prims await verify_prims(stage, mtl_name, verify_prim_list) async def test_multiple_descendents_mtl(stage, material, multiple_descendents_prim, target_prim, drag_target): mtl_name, mdl_path = material # drag and drop items from the tree view of content browser async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target) # use multiple descendents dialog await handle_multiple_descendents_dialog(stage, multiple_descendents_prim, target_prim) # handle create material dialog async with MaterialLibraryTestHelper() as material_library_helper: await material_library_helper.handle_create_material_dialog(mdl_path, mtl_name) # wait for material to load & UI to refresh await wait_stage_loading() # verify created/bound prims await verify_prims(stage, mtl_name, [target_prim]) # test DnD single & multi subid material from Content window to centre of viewport - Create material stage = omni.usd.get_context().get_stage() drag_target = ui_test_window.center await test_mtl(stage, single_material, [], drag_target) await test_mtl(stage, multi_material, [], drag_target) # load stage with multi-descendent prim await open_stage(get_test_data_path(__name__, "multi-material-object-cube-component.usda")) await wait_stage_loading() # test DnD single & multi subid material from Content window to /World/Sphere - Create material & Binding stage = omni.usd.get_context().get_stage() verify_prim_list = ["/World/Sphere"] drag_target, valid = get_ui_position_for_prim(viewport_window, verify_prim_list[0]) drag_target = Vec2(drag_target[0], drag_target[1]) await test_mtl(stage, single_material, verify_prim_list, drag_target) await test_mtl(stage, multi_material, verify_prim_list, drag_target) # test DnD single & multi subid material from Content window to /World/pCube1 targeting each descendent - Create material & Binding stage = omni.usd.get_context().get_stage() multiple_descendents_prim = "/World/pCube1" descendents = ["/World/pCube1", "/World/pCube1/front1", "/World/pCube1/side1", "/World/pCube1/back", "/World/pCube1/side2", "/World/pCube1/top1", "/World/pCube1/bottom"] drag_target, valid = get_ui_position_for_prim(viewport_window, multiple_descendents_prim) drag_target = Vec2(drag_target[0], drag_target[1]) for target_prim in descendents: await test_multiple_descendents_mtl(stage, single_material, multiple_descendents_prim, target_prim, drag_target) await test_multiple_descendents_mtl(stage, multi_material, multiple_descendents_prim, target_prim, drag_target)
7,382
Python
46.025477
177
0.670144
omniverse-code/kit/exts/omni.inspect/PACKAGE-LICENSES/omni.inspect-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.inspect/config/extension.toml
[package] version = "1.0.1" title = "Object Inspection Capabilities" description = "Provides interfaces you can add to your ABI to provide data inspection information in a compliant way" keywords = [ "debug", "inspect", "information" ] [[native.plugin]] path = "bin/*.plugin" recursive = false [[python.module]] name = "omni.inspect"
336
TOML
24.923075
117
0.723214
omniverse-code/kit/exts/omni.inspect/omni/inspect/_omni_inspect.pyi
from __future__ import annotations import omni.inspect._omni_inspect import typing import omni.core._core __all__ = [ "IInspectJsonSerializer", "IInspectMemoryUse", "IInspectSerializer", "IInspector" ] class IInspectJsonSerializer(_IInspectJsonSerializer, IInspector, _IInspector, omni.core._core.IObject): """ Base class for object inspection requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def as_string(self) -> str: """ Get the current output as a string. If the output is being sent to a file path then read the file at that path and return the contents of the file (with the usual caveats about file size). @returns String representation of the output so far """ def clear(self) -> None: """ Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed. """ def close_array(self) -> bool: """ Finish writing a JSON array. @returns whether or not validation succeeded. """ def close_object(self) -> bool: """ Finish writing a JSON object. @returns whether or not validation succeeded. """ def finish(self) -> bool: """ Finishes writing the entire JSON dictionary. @returns whether or not validation succeeded. """ def open_array(self) -> bool: """ Begin a JSON array. @returns whether or not validation succeeded. @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large """ def open_object(self) -> bool: """ Begin a JSON object. @returns whether or not validation succeeded. """ def set_output_to_string(self) -> None: """ Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. """ def write_base64_encoded(self, value: bytes, size: int) -> bool: """ Write a set of bytes into the output JSON as a base64 encoded string. @param[in] value The bytes to be written. @param[in] size The number of bytes of data in @p value. @returns whether or not validation succeeded. @remarks This will take the input bytes and encode it in base64, then store that as base64 data in a string. """ def write_bool(self, value: bool) -> bool: """ Write out a JSON boolean value. @param[in] value The boolean value. @returns whether or not validation succeeded. """ def write_double(self, value: float) -> bool: """ Write out a JSON double (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded. """ def write_float(self, value: float) -> bool: """ Write out a JSON float (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded. """ def write_int(self, value: int) -> bool: """ Write out a JSON integer value. @param[in] value The integer value. @returns whether or not validation succeeded. """ def write_int64(self, value: int) -> bool: """ Write out a JSON 64-bit integer value. @param[in] value The 64-bit integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format. """ def write_key(self, key: str) -> bool: """ Write out a JSON key for an object property. @param[in] key The key name for this property. This may be nullptr. @returns whether or not validation succeeded. """ def write_key_with_length(self, key: str, key_len: int) -> bool: """ Write out a JSON key for an object property. @param[in] key The string value for the key. This can be nullptr. @param[in] keyLen The length of @ref key, excluding the null terminator. @returns whether or not validation succeeded. """ def write_null(self) -> bool: """ Write out a JSON null value. @returns whether or not validation succeeded. """ def write_string(self, value: str) -> bool: """ Write out a JSON string value. @param[in] value The string value. This can be nullptr. @returns whether or not validation succeeded. """ def write_string_with_length(self, value: str, len: int) -> bool: """ Write out a JSON string value. @param[in] value The string value. This can be nullptr if @p len is 0. @param[in] len The length of @p value, excluding the null terminator. @returns whether or not validation succeeded. """ def write_u_int(self, value: int) -> bool: """ Write out a JSON unsigned integer value. @param[in] value The unsigned integer value. @returns whether or not validation succeeded. """ def write_u_int64(self, value: int) -> bool: """ Write out a JSON 64-bit unsigned integer value. @param[in] value The 64-bit unsigned integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format. """ @property def output_location(self) -> str: """ :type: str """ @property def output_to_file_path(self) -> None: """ :type: None """ @output_to_file_path.setter def output_to_file_path(self, arg1: str) -> None: pass pass class IInspectMemoryUse(_IInspectMemoryUse, IInspector, _IInspector, omni.core._core.IObject): """ Base class for object inspection requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def reset(self) -> None: """ Reset the memory usage data to a zero state """ def total_used(self) -> int: """ @returns the total number of bytes of memory used since creation or the last call to reset(). """ def use_memory(self, ptr: capsule, bytes_used: int) -> bool: """ Add a block of used memory Returns false if the memory was not recorded (e.g. because it was already recorded) @param[in] ptr Pointer to the memory location being logged as in-use @param[in] bytesUsed Number of bytes in use at that location """ pass class IInspectSerializer(_IInspectSerializer, IInspector, _IInspector, omni.core._core.IObject): """ Base class for object serialization requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def as_string(self) -> str: """ Get the current output as a string. @returns The output that has been sent to the serializer. If the output is being sent to a file path then read the file at that path and return the contents of the file. If the output is being sent to stdout or stderr then nothing is returned as that output is unavailable after flushing. """ def clear(self) -> None: """ Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed. """ def set_output_to_string(self) -> None: """ Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. """ def write_string(self, to_write: str) -> None: """ Write a fixed string to the serializer output location @param[in] toWrite String to be written to the serializer """ @property def output_location(self) -> str: """ :type: str """ @property def output_to_file_path(self) -> None: """ :type: None """ @output_to_file_path.setter def output_to_file_path(self, arg1: str) -> None: pass pass class _IInspectJsonSerializer(IInspector, _IInspector, omni.core._core.IObject): pass class _IInspectMemoryUse(IInspector, _IInspector, omni.core._core.IObject): pass class _IInspectSerializer(IInspector, _IInspector, omni.core._core.IObject): pass class IInspector(_IInspector, omni.core._core.IObject): """ Base class for object inspection requests. """ @typing.overload def __init__(self, arg0: omni.core._core.IObject) -> None: ... @typing.overload def __init__(self) -> None: ... def help_flag(self) -> str: """ Returns the common flag used to tell the inspection process to put the help information into the inspector using the setHelp_abi function. Using this approach avoids having every inspector/object combination add an extra ABI function just for retrieving the help information, as well as providing a consistent method for requesting it. @returns String containing the name of the common flag used for help information """ def help_information(self) -> str: """ Returns the help information currently available on the inspector. Note that this could change from one invocation to the next so it's important to read it immediately after requesting it. @returns String containing the help information describing the current configuration of the inspector """ def is_flag_set(self, flag_name: str) -> bool: """ Checks whether a particular flag is currently set or not. @param[in] flagName Name of the flag to check @returns True if the named flag is set, false if not """ def set_flag(self, flag_name: str, flag_state: bool) -> None: """ Enable or disable an inspection flag. It's up to the individual inspection operations or the derived inspector interfaces to interpret the flag. @param[in] flagName Name of the flag to set @param[in] flagState New state for the flag """ @property def help(self) -> None: """ :type: None """ @help.setter def help(self, arg1: str) -> None: pass pass class _IInspector(omni.core._core.IObject): pass
11,159
unknown
35.351791
118
0.616005
omniverse-code/kit/exts/omni.inspect/omni/inspect/__init__.py
""" Contains interfaces for inspecting values used within other interfaces """ # Required to be able to instantiate the object types import omni.core # Interface from the ABI bindings from ._omni_inspect import IInspectJsonSerializer from ._omni_inspect import IInspectMemoryUse from ._omni_inspect import IInspectSerializer from ._omni_inspect import IInspector
364
Python
29.416664
70
0.815934
omniverse-code/kit/exts/omni.inspect/omni/inspect/tests/test_bindings.py
"""Suite of tests to exercise the bindings exposed by omni.inspect""" import omni.kit.test import omni.inspect as oi from pathlib import Path import tempfile # ============================================================================================================== class TestOmniInspectBindings(omni.kit.test.AsyncTestCase): """Wrapper for tests to verify functionality in the omni.inspect bindings module""" # ---------------------------------------------------------------------- def __test_inspector_api(self, inspector: oi.IInspector): """Run tests on flags common to all inspector types API surface being tested: omni.inspect.IInspector @help, help_flag, help_information, is_flag_set, set_flag """ HELP_FLAG = "help" HELP_INFO = "This is some help" self.assertEqual(inspector.help_flag(), HELP_FLAG) self.assertFalse(inspector.is_flag_set(HELP_FLAG)) inspector.help = HELP_INFO self.assertEqual(inspector.help_information(), HELP_INFO) inspector.set_flag("help", True) self.assertTrue(inspector.is_flag_set(HELP_FLAG)) inspector.set_flag("help", False) inspector.set_flag("Canadian", True) self.assertFalse(inspector.is_flag_set(HELP_FLAG)) self.assertTrue(inspector.is_flag_set("Canadian")) # ---------------------------------------------------------------------- async def test_memory_inspector(self): """Test features only available to the memory usage inspector API surface being tested: omni.inspect.IInspectMemoryUse [omni.inspect.IInspector] reset, total_used, use_memory """ inspector = oi.IInspectMemoryUse() self.__test_inspector_api(inspector) self.assertEqual(inspector.total_used(), 0) self.assertTrue(inspector.use_memory(inspector, 111)) self.assertTrue(inspector.use_memory(inspector, 222)) self.assertTrue(inspector.use_memory(inspector, 333)) self.assertEqual(inspector.total_used(), 666) inspector.reset() self.assertEqual(inspector.total_used(), 0) # ---------------------------------------------------------------------- async def test_serializer(self): """Test features only available to the shared serializer types API surface being tested: omni.inspect.IInspectSerializer [omni.inspect.IInspector] as_string, clear, output_location, output_to_file_path, set_output_to_string, write_string """ inspector = oi.IInspectSerializer() self.__test_inspector_api(inspector) self.assertEqual(inspector.as_string(), "") TEST_STRINGS = [ "This is line 1", "This is line 2", ] # Test string output inspector.write_string(TEST_STRINGS[0]) self.assertEqual(inspector.as_string(), TEST_STRINGS[0]) inspector.write_string(TEST_STRINGS[1]) self.assertEqual(inspector.as_string(), "".join(TEST_STRINGS)) inspector.clear() self.assertEqual(inspector.as_string(), "") # Test file output with tempfile.TemporaryDirectory() as tmp: test_output_file = Path(tmp) / "test_serializer.txt" # Get the temp file path and test writing a line to it inspector.output_to_file_path = str(test_output_file) inspector.write_string(TEST_STRINGS[0]) self.assertEqual(inspector.as_string(), TEST_STRINGS[0]) # Set output back to string and check the temp file contents manually inspector.set_output_to_string() file_contents = open(test_output_file, "r").readlines() self.assertEqual(file_contents, [TEST_STRINGS[0]]) # ---------------------------------------------------------------------- async def test_json_serializer(self): """Test features only available to the JSON serializer type API surface being tested: omni.inspect.IInspectJsonSerializer [omni.inspect.IInspector] as_string, clear, close_array, close_object, finish, open_array, open_object, output_location, output_to_file_path, set_output_to_string, write_base64_encoded, write_bool, write_double, write_float, write_int, write_int64, write_key, write_key_with_length, write_null, write_string, write_string_with_length, write_u_int, write_u_int64 """ inspector = oi.IInspectJsonSerializer() self.__test_inspector_api(inspector) self.assertEqual(inspector.as_string(), "") self.assertTrue(inspector.open_array()) self.assertTrue(inspector.close_array()) self.assertEqual(inspector.as_string(), "[\n]") inspector.clear() self.assertEqual(inspector.as_string(), "") # Note: There's what looks like a bug in the StructuredLog JSON output that omits the space before # a base64_encoded value. If that's ever fixed the first entry in the dictionary will have to change. every_type = """ { "base64_key":"MTI=", "bool_key": true, "double_key": 123.456, "float_key": 125.25, "int_key": -123, "int64_key": -123456789, "null_key": null, "string_key": "Hello", "string_with_length_key": "Hell", "u_int_key": 123, "u_int64_key": 123456789, "array": [ 1, 2, 3 ] } """ def __inspect_every_type(): """Helper to write one of every type to the inspector""" self.assertTrue(inspector.open_object()) self.assertTrue(inspector.write_key("base64_key")) self.assertTrue(inspector.write_base64_encoded(b'1234', 2)) self.assertTrue(inspector.write_key("bool_key")) self.assertTrue(inspector.write_bool(True)) self.assertTrue(inspector.write_key("double_key")) self.assertTrue(inspector.write_double(123.456)) self.assertTrue(inspector.write_key("float_key")) self.assertTrue(inspector.write_float(125.25)) self.assertTrue(inspector.write_key_with_length("int_key_is_truncated", 7)) self.assertTrue(inspector.write_int(-123)) self.assertTrue(inspector.write_key("int64_key")) self.assertTrue(inspector.write_int64(-123456789)) self.assertTrue(inspector.write_key("null_key")) self.assertTrue(inspector.write_null()) self.assertTrue(inspector.write_key("string_key")) self.assertTrue(inspector.write_string("Hello")) self.assertTrue(inspector.write_key("string_with_length_key")) self.assertTrue(inspector.write_string_with_length("Hello World", 4)) self.assertTrue(inspector.write_key("u_int_key")) self.assertTrue(inspector.write_u_int(123)) self.assertTrue(inspector.write_key("u_int64_key")) self.assertTrue(inspector.write_u_int64(123456789)) self.assertTrue(inspector.write_key("array")) self.assertTrue(inspector.open_array()) self.assertTrue(inspector.write_int(1)) self.assertTrue(inspector.write_int(2)) self.assertTrue(inspector.write_int(3)) self.assertTrue(inspector.close_array()) self.assertTrue(inspector.close_object()) self.assertTrue(inspector.finish()) __inspect_every_type() self.assertEqual(inspector.as_string(), every_type) # Test file output with tempfile.TemporaryDirectory() as tmp: test_output_file = Path(tmp) / "test_serializer.txt" # Get the temp file path and test writing a line to it inspector.output_to_file_path = str(test_output_file) __inspect_every_type() self.assertEqual(inspector.as_string(), every_type) # Set output back to string and check the temp file contents manually inspector.set_output_to_string() file_contents = [line.rstrip() for line in open(test_output_file, "r").readlines()] self.assertCountEqual(file_contents, every_type.split("\n")[:-1])
8,329
Python
39.833333
115
0.593829
omniverse-code/kit/exts/omni.inspect/omni/inspect/tests/__init__.py
""" Scan the test directory for unit tests """ scan_for_test_modules = True
76
Python
14.399997
38
0.710526
omniverse-code/kit/exts/omni.inspect/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [1.0.1] - 2022-06-28 ### Added - Linked docs in the build area ## [1.0.0] - 2022-04-07 ### Added - Unit test for all of the functionality ### Changed - Updated to a real version for future compatibility - Made some bug fixes revealed by the unit test ## [0.1.0] - 2021-05-12 ### Initial Version - First implementation including basic features
618
Markdown
24.791666
87
0.71521
omniverse-code/kit/exts/omni.inspect/docs/README.md
# Omniverse Data Inspector [omni.inspect] The data inspector module contains interfaces that provide a consistent method of inspecting data from extensions in an ABI-friendly manner.
184
Markdown
35.999993
102
0.826087
omniverse-code/kit/exts/omni.inspect/docs/index.rst
.. _omni_inspect_ext: omni.inspect: Omniverse Data Inspector ####################################### The interfaces in this extension don't do anything themselves, they merely provide a conduit through which other objects can provide various information through a simple ABI without each object being required to provide the same inspection interface boilerplate. The general approach is that you create an inspector, then pass it to an object to be inspected. This model provides full access to the internal data to the inspector and makes it easy for objects to add inspection capabilities. Inspecting Data =============== To add inspection to your data you need two things - an interface to pass the inspector, and an implementation of the inspection, or inspections. We'll take two imaginary interface types, one of which uses the old Carbonite interface definitions and one which uses ONI. The interfaces just manage an integer and float value, though the concept extends to arbitrariliy complex structures. Carbonite ABI Integer --------------------- .. code-block:: c++ // Interface definition -------------------------------------------------- // Implementation for the integer is just a handle, which is an int*, and the interface pointer using IntegerHandle = uint64_t; struct IInteger; struct IntegerObj { const IInteger* iInteger; IntegerHandle integerHandle; }; struct IInteger { CARB_PLUGIN_INTERFACE("omni::inspect::IInteger", 1, 0); void(CARB_ABI* set)(IntegerObj& intObj, int value) = nullptr; bool(CARB_ABI* inspect)(const IntegerObj& intObj, inspect::IInspector* inspector) = nullptr; }; // Interface implementation -------------------------------------------------- void intSet(IntegerObj& intObj, int value) { intObj.iInteger->set(intObj, value); } bool intInspect(const IntegerObj& intObj, inspect::IInspector* inspector) { // This object can handle both a memory use inspector and a serialization inspector auto memoryInspector = omni::cast<inspect::IInspectMemoryUse>(inspector); if (memoryInspector) { // The memory used by this type is just a single integer, and the object itself memoryInspector->useMemory((void*)&intObj, sizeof(intObj)); memoryInspector->useMemory((void*)intObj.integerHandle, sizeof(int)); return true; } auto jsonSerializer = omni::cast<inspect::IInspectJsonSerializer>(inspector); if (jsonSerializer) { // Valid JSON requires more than just a bare integer. // Indenting on the return value gives you a visual representation of the JSON hierarchy if (jsonSerializer->openObject()) { jsonSerializer->writeKey("Integer Value"); jsonSerializer->writeInt(*(int*)(intObj.integerHandle)); jsonSerializer->closeObject(); } return true; } auto serializer = omni::cast<inspect::IInspectSerializer>(inspector); if (serializer) { // The interesting data to write is the integer value, though you could also write the pointer if desired serializer->write("Integer value %d", *(int*)(intObj.integerHandle)); return true; } // Returning false indicates an unsupported inspector return false; } // Interface use -------------------------------------------------- IInteger iFace{ intInspect, intSet }; int myInt{ 0 }; IntegerObj iObj{ &iFace, (uint64_t)&myInt }; ONI Float --------- .. code-block:: c++ // Interface definition -------------------------------------------------- OMNI_DECLARE_INTERFACE(IFloat); class IFloat_abi : public omni::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.inspect.IFloat")> { protected: virtual void set_abi(float newValue) noexcept = 0; virtual void inspect_abi(omni::inspect::IInspector* inspector) noexcept = 0; }; // Interface implementation -------------------------------------------------- class IFloat : public omni::Implements<IIFloat> { protected: void set_abi(float newvalue) noexcept override { m_value = value; } bool inspect(omni::inspect::IInspector* inspector) noexcept override { // This object can handle both a memory use inspector and a serialization inspector auto memoryInspector = omni::cast<inspect::IInspectMemoryUse>(inspector); if (memoryInspector) { // The memory used by this type is just the size of this object memoryInspector->useMemory((void*)this, sizeof(*this)); return true; } auto jsonSerializer = omni::cast<inspect::IInspectJsonSerializer>(inspector); if (jsonSerializer) { // Valid JSON requires more than just a bare float. // Indenting on the return value gives you a visual representation of the JSON hierarchy if (jsonSerializer->openObject()) { jsonSerializer->writeKey("Float Value"); jsonSerializer->writeFloat(m_value); jsonSerializer->closeObject(); } return true; } auto serializer = omni::cast<inspect::IInspectSerializer>(inspector); if (serializer) { // The interesting data to write is the float value, though you could also write "this" if desired serializer->write("float value %g", m_value); return true; } // Returning false indicates an unsupported inspector return false; } private: float m_value{ 0.0f }; }; Calling Inspectors From Python ------------------------------ The inspectors, being ONI objects, have Python bindings so they can be instantiated directly and passed to any of the interfaces that support them. .. code-block:: python import omni.inspect as oi memory_inspector = oi.IInspectMemoryUse() my_random_object.inspect(memory_inspector) print(f"Memory use is {memory_inspector.get_memory_use()} bytes") json_serializer = oi.IInspectJsonSerializer() my_random_object.inspect(json_serializer) print(f"JSON object:\n{json_serializer.as_string()}" ) serializer = oi.IInspectSerializer() my_random_object.inspect(serializer) print(f"Serialized object:\n{serializer.as_string()}" ) omni.inspect Python Docs ======================== .. automodule:: omni.inspect :platform: Windows-x86_64, Linux-x86_64, Linux-aarch64 :members: :undoc-members: :imported-members: Administrative Details ====================== .. toctree:: :maxdepth: 1 :caption: Administrivia :glob: CHANGELOG
7,043
reStructuredText
34.938775
117
0.606986
omniverse-code/kit/exts/omni.kit.widget.imageview/PACKAGE-LICENSES/omni.kit.widget.imageview-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.widget.imageview/config/extension.toml
[package] version = "1.0.3" category = "Internal" title = "ImageView Widget" description="The widget that allows to view image in a canvas." changelog = "docs/CHANGELOG.md" [dependencies] "omni.ui" = {} [[python.module]] name = "omni.kit.widget.imageview" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", ]
461
TOML
17.479999
63
0.661605
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/__init__.py
from .imageview import ImageView
33
Python
15.999992
32
0.848485
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/imageview.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 class ImageView: """The widget that shows the image with the ability to navigate""" def __init__(self, filename, **kwargs): with ui.CanvasFrame(style_type_name_override="ImageView", **kwargs): self.__image = ui.Image(filename) def set_progress_changed_fn(self, fn): """Callback that is called when control state is changed""" self.__image.set_progress_changed_fn(fn) def destroy(self): if self.__image: self.__image.destroy() self.__image = None
985
Python
35.518517
76
0.701523
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/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 .imageview_test import TestImageview
475
Python
46.599995
76
0.812632
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/tests/imageview_test.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from ..imageview import ImageView from omni.ui.tests.test_base import OmniUiTest from functools import partial from pathlib import Path import omni.kit.app import asyncio class TestImageview(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute() # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): window = await self.create_test_window() f = asyncio.Future() def on_image_progress(future: asyncio.Future, progress): if progress >= 1: if not future.done(): future.set_result(None) with window.frame: image_view = ImageView(f"{self._golden_img_dir.joinpath('lenna.png')}") image_view.set_progress_changed_fn(partial(on_image_progress, f)) # Wait the image to be loaded await f await self.finalize_test(golden_img_dir=self._golden_img_dir)
1,697
Python
35.127659
110
0.683559
omniverse-code/kit/exts/omni.kit.widget.imageview/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.3] - 2022-11-10 ### Removed - Removed dependency on omni.kit.test ## [1.0.2] - 2022-05-04 ### Updated - Add set_progress_changed_fn API for caller to check if the image has been loaded. ## [1.0.1] - 2020-09-16 ### Updated - Fixed the unittest. ## [1.0.0] - 2020-07-19 ### Added - Added The widget that allows to view image in a canvas.
442
Markdown
21.149999
83
0.662896
omniverse-code/kit/exts/omni.graph.core/PACKAGE-LICENSES/omni.graph.core-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.graph.core/config/extension.toml
[package] title = "OmniGraph" version = "2.65.4" category = "Graph" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains the implementation of the OmniGraph core." preview_image = "data/preview.png" repository = "" keywords = ["omnigraph", "core"] # Other extensions on which this one relies [dependencies] "omni.usd" = {} "omni.client" = {} "omni.inspect" = {optional=true} "omni.gpucompute.plugins" = {} [[native.plugin]] path = "bin/*.plugin" recursive = false # Regression tests are not here because that would require Python. See the unit test tree for core-specific tests. [[test]] waiver = "Tests are in omni.graph.test" stdoutFailPatterns.exclude = [] [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph refs until that workflow is moved ] pages = [ "docs/Overview.md", "docs/nodes.rst", "docs/architecture.rst", "docs/core_concepts.rst", "docs/usd.rst", "docs/naming_conventions.rst", "docs/directory_structure.rst", "docs/how_to.rst", "docs/versioning.rst", "docs/roadmap.rst", "docs/CHANGELOG.md", "docs/omnigraph_arch_decisions.rst", "docs/categories.rst", "docs/usd_representations.rst", # "docs/index.rst", # "docs/decisions/0000-use-markdown-any-decision-records.rst", # "docs/decisions/0001-python-api-definition.rst", # "docs/decisions/0002-python-api-exposure.rst", # "docs/decisions/0003-extension-locations.rst", # "docs/decisions/adr-template.rst", # "docs/internal/SchemaPrimSetting.rst", # "docs/internal/internal.rst", # "docs/internal/deprecation.rst", # "docs/internal/versioning.rst", # "docs/internal/versioning_behavior.rst", # "docs/internal/versioning_carbonite.rst", # "docs/internal/versioning_extensions.rst", # "docs/internal/versioning_nodes.rst", # "docs/internal/versioning_oni.rst", # "docs/internal/versioning_python.rst", # "docs/internal/versioning_settings.rst", # "docs/internal/versioning_testing.rst", # "docs/internal/versioning_usd.rst", ]
2,102
TOML
29.92647
114
0.683635
omniverse-code/kit/exts/omni.graph.core/omni/graph/core/ogn/OgnPrimDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.core.Prim This is a system built-in node to deal with USD prim data interface to/from an OmniGraph node. This extends the INodeType interface, so it acts as an INodeType, but also uses the internal API to directly communicate with OmnIGraph. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnPrimDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.core.Prim Class Members: node: Node being evaluated """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnPrimDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnPrimDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnPrimDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
3,899
Python
58.090908
121
0.698897
omniverse-code/kit/exts/omni.graph.core/omni/graph/core/ogn/nodes/core/OgnPrim.cpp
// Copyright (c) 2019-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. // #include "OgnPrimDatabase.h" #include "GraphContext.h" namespace omni { namespace graph { namespace core { namespace DataModel { //backdoor :( void backdoor_copyAttribute(ComputeCacheType& cache, AttrKey dst, AttrKey src); } HandleInt nodeCtxHandleToPath(NodeContextHandle const& handle); class OgnPrim { public: // copy computed data back to usd prim // This node is used as a placeholder representing a USD prim, which might have connection(s) to upstream node(s). // This data needs to be copied over, so it can be written back to USD // This is a legacy way of doing things. We are using a private backdoor in datamodel to achieve this legacy behavior static bool compute(OgnPrimDatabase& db) { auto& contextObj = db.abi_context(); GraphContext& contextImpl = *GraphContext::getGraphContextFromHandle(contextObj.contextHandle); ComputeCacheType& cache = contextImpl.getCache(); auto node = db.abi_node(); ConstAttributeDataHandle const invalidHandle(ConstAttributeDataHandle::invalidValue()); // find all connected attribute on that node size_t countAttr = node.iNode->getAttributeCount(node); AttributeObj* attrObjIn = (AttributeObj*)alloca(countAttr * sizeof(AttributeObj)); AttributeObj* end = attrObjIn + countAttr; node.iNode->getAttributes(node, attrObjIn, countAttr); auto getHdl = [&contextObj](AttributeObj const& a) { return contextObj.iToken->getHandle(a.iAttribute->getName(a)); }; AttrKey dst{ nodeCtxHandleToPath(node.nodeContextHandle), 0 }; for (size_t i = 0; i < countAttr; ++i) { AttrKey src = (AttrKey) attrObjIn[i].iAttribute->getConstAttributeDataHandle(attrObjIn[i]); dst.second = getHdl(attrObjIn[i]).token; if (dst != src) DataModel::backdoor_copyAttribute(cache, dst, src); } return true; } }; REGISTER_OGN_NODE() } // namespace core } // namespace graph } // namespace omni
2,485
C++
34.514285
123
0.699799
omniverse-code/kit/exts/omni.graph.core/omni/graph/core/ogn/tests/TestOgnPrim.py
import omni.kit.test import omni.graph.core as og import omni.graph.core.tests as ogts import os class TestOgn(ogts.OmniGraphTestCase): async def test_data_access(self): from omni.graph.core.ogn.OgnPrimDatabase import OgnPrimDatabase test_file_name = "OgnPrimTemplate.usda" usd_path = os.path.join(os.path.dirname(__file__), "usd", test_file_name) if not os.path.exists(usd_path): self.assertTrue(False, f"{usd_path} not found for loading test") (result, error) = await ogts.load_test_file(usd_path) self.assertTrue(result, f'{error} on {usd_path}') test_node = og.Controller.node("/TestGraph/Template_omni_graph_core_Prim") database = OgnPrimDatabase(test_node) self.assertTrue(test_node.is_valid()) node_type_name = test_node.get_type_name() self.assertEqual(og.GraphRegistry().get_node_type_version(node_type_name), 1) def _attr_error(attribute: og.Attribute, usd_test: bool) -> str: test_type = "USD Load" if usd_test else "Database Access" return f"{node_type_name} {test_type} Test - {attribute.get_name()} value error"
1,167
Python
42.259258
92
0.664096
omniverse-code/kit/exts/omni.graph.core/omni/graph/core/ogn/tests/__init__.py
"""====== GENERATED BY omni.graph.tools - DO NOT EDIT ======""" import omni.graph.tools as ogt ogt.import_tests_in_directory(__file__, __name__)
145
Python
35.499991
63
0.634483
omniverse-code/kit/exts/omni.graph.core/docs/roadmap.rst
Roadmap ******* Pending Deprecations ==================== As described in :ref:`omnigraph_versioning` we attempt to provide backward compatibility for as long as we can. That notwithstanding it will always be a smoother experience for you if you migrate away from using deprecated functionality at your earliest convenience to ensure maximum compatibility. If anything is scheduled for "hard deprecation" Known Functionality Gaps ======================== As OmniGraph is still in early stages there are some known unimplemented edge cases to be aware of. Addressing these will be prioritized as resources and interests dictate. - The Node Description Editor does not support addition of tests or generation of C++ nodes - Bundle arrays are not supported - Arrays of strings are not supported - Bundles cannot contain "any" or "union" type attributes - "any" or "union" type attributes cannot be bundles - Loading a USD file with OmniGraph nodes in it will not automatically load the extensions required for those nodes to function properly
1,045
reStructuredText
44.478259
136
0.770335
omniverse-code/kit/exts/omni.graph.core/docs/nodes.rst
OmniGraph Nodes *************** The OmniGraph node provides an encapsulated piece of functionality that is used in a connected graph structure to form larger more complex calculations. One of the core strengths of the way the nodes are defined is that individual node writers do not have to deal with the complexity of the entire system, while still reaping the benefits of it. Support code is generated for the node type definitions that simplify the code necessary for implementing the algorithm, while also providing support for efficient manipulation of data through the use of Fabric both on the CPU and on the GPU. The user writes the description and code that define the operation of the node type and OmniGraph provides the interfaces that incorporate it into the Omniverse runtime. Node Type Implementations ========================= The node type definition implements the functionality that will be used by the node using two key pieces 1. The *authoring* definition, which comes in the form of a JSON format file with the suffix *.ogn* 2. The *runtime* algorithm, which can be implemented in one of several languages. The actual language of implementation is not important to OmniGraph and can be chosen based on the needs and abilities of the node writer. You can learn about the authoring description in the .ogn files by perusing the :ref:`OGN Node Writer Guide<ogn_user_guide>`, with full details in the :ref:`OGN Reference Guide<ogn_reference_guide>`, or you can follow along with some of the tutorials or node definitions seen below. A common component of all node type implementations is the presence of a generated structure known as the node type database. The database provides a simplified wrapper around the underlying OmniGraph functionality that hides all of the required boilerplate code that makes the nodes operate so efficiently. Python Implementation --------------------- The easiest type of node to write is a Python node. You only need implement a class with a static *compute(db)* method whose parameter is the generated database. The database provides access to the input values your node will use for its computation and the output values you generate as a result of that computation. +-------------------------------------------+ | :ref:`Example Below<ogn_example_node_py>` | +-------------------------------------------+ C++ Implementation ------------------ While the Python nodes are easier to write they are not particularly efficient, and for some types of nodes performance is critical. These node types can be implemented in C++. There is slightly more code to write, but you gain the performance benefits of compiled code. +--------------------------------------------+ | :ref:`Example Below<ogn_example_node_cpp>` | +--------------------------------------------+ C++/CUDA Implementation ----------------------- Sometimes you want to harness the power of the GPU to do some really complex or data-heavy computations. If you know how to program in CUDA, NVIDIA's general purpose GPU computing language, then you can insert CUDA code into your node's `compute()` method to move the computation over to the GPU. +-------------------------------------------+ | :ref:`Example Below<ogn_example_node_cu>` | +-------------------------------------------+ Warp Implementation ------------------- If you don't know how to write CUDA code but are familiar with Python then you can use the Warp package to accelerate your computations on the GPU as well. NVIDIA Warp is a Python framework for writing high-performance simulation and graphics code in Omniverse, and in particular OmniGraph. See the `Warp extension documentation <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_warp.html>`_ for details on how to write the implementation code for Warp nodes. +---------------------------------------------+ | :ref:`Example Below<ogn_example_node_warp>` | +---------------------------------------------+ Slang Implementation -------------------- `Slang <https://shader-slang.com/slang/user-guide/index.html>`_ is a language developed for efficient implementation of shaders, based on years of collaboration between researchers at NVIDIA, Carnegie Mellon University, and Stanford. To bring the benefits of Slang into Omnigraph an extension was written that allows you to create OmniGraph node implementations in the Slang language. To gain access to it you must enable the *omni.slangnode* extension, either through the extension window or via the `extension manager API <https://docs.omniverse.nvidia.com/py/kit/docs/api/core/omni.ext.html#omni.ext.ExtensionManager>`_ The Slang node type is slightly different from the others in that you do not define the authoring definition through a *.ogn* file. There is a single *.ogn* file shared by all Slang node types and you write the implementation of the node type's algorithm in the *inputs:code* attribute of an instantiation of that node type. You dynamically add attributes to the node to define the authoring interface and then you can access the attribute data using some generated Slang conventions. Moreover, the Slang language has the capability of targeting either CPU or GPU when compiled, so once the graph supports it the node will be able to run on either CPU or GPU, depending on which is more efficient on the available resources. See the `Slang extension documentation <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph/slang-nodes/nodes/slang.html>`_ for details on how to write Slang nodes. +----------------------------------------------+ | :ref:`Example Below<ogn_example_node_slang>` | +----------------------------------------------+ AutoNode Implementation ----------------------- AutoNode is a variation of the Python implementation that makes use of the Python AST to combine both the authoring description and the runtime implementation into a single Python class or function. While not yet fully functional, it provides a rapid method of implementing simple node types with minimal overhead. +---------------------------------------------+ | :ref:`Example Below<ogn_example_node_auto>` | +---------------------------------------------+ Sample Node With Different Implementations ========================================== To illustrate the difference in implementations a simple node type definition will be shown that takes in two arrays of points and outputs a weighted blend of them. .. note:: The implementations are not necessarily the most efficient, nor the most appropriate for the type of computation being performed. They are merely meant to be illustrative of the implementation options. This *.ogn* file will be used by all but the Slang and AutoNode implementations. The first highlighted line is only present in the Python and Warp implementations, as they are both Python-based. The remaining highlighted lines are used only for Warp and CUDA implementations, being used to indicate that the memory for the attributes should be retrieved from the GPU rather than the CPU. .. code-block:: json :emphasize-lines: 4,8,9,15 { "AddWeightedPoints": { "version": 1, "language": "python", "description": [ "Add two sets of points together, using an alpha value to determine how much of each point set to", "include in the result. The weighting is alpha*firstSet + (1 - alpha)*secondSet.", "memoryType": "cuda", "cudaPointers": "cpu" ], "inputs": { "alpha": { "type": "double", "description": "Relative weights to give to each of the two point sets" "memoryType": "cpu" }, "firstSet": { "type": "pointd[3][]", "description": "First set of points to blend together" }, "secondSet": { "type": "pointd[3][]", "description": "Second set of points to blend together" }, "outputs": { "result": { "type": "pointd[3][]", "description": "Weighted sum of the two sets of input points" } } } } .. _ogn_example_node_py: Python Version -------------- .. code-block:: python class OgnAddWeightedPoints: @staticmethod def compute(db) -> bool: db.outputs.result_size = len(db.inputs.firstSet) db.outputs.result = db.inputs.firstSet * db.inputs.alpha + db.inputs.secondSet * (1.0 - db.inputs.alpha) return True For illustration purposes here is the same code but with proper handling of unexpected input values, which is a good practice no matter what the implementation language. .. code-block:: python class OgnAddWeightedPoints: @staticmethod def compute(db) -> bool: first_set = db.inputs.firstSet second_set = db.inputs.secondSet if len(first_set) != len(second_set): db.log_error(f"Cannot blend two unequally sized point sets - {len(first_set)} and {len(second_set)}") return False if not (0.0 <= db.inputs.alpha <= 1.0): db.log_error(f"Alpha blend must be in the range [0.0, 1.0], not computing with {db.inputs.alpha}) return False db.outputs.result_size = len(first_set) db.outputs.result = first_set * db.inputs.alpha + second_set * (1.0 - db.inputs.alpha) return True To see further examples of the Python implementation code you can peruse the :ref:`samples used by the user guide<ogn_code_samples_py>` or the :ref:`user guide itself<ogn_user_guide>` itself. .. _ogn_example_node_cpp: C++ Version ----------- .. code-block:: cpp #include <OgnAddWeightedPointsDatabase.h> #include <algorithm> class OgnAddWeightedPoints { public: static bool compute(OgnAddWeightedPointsDatabase& db) { auto const& firstSet = db.inputs.firstSet(); auto const& secondSet = db.inputs.secondSet(); auto const& alpha = db.inputs.alpha(); const& result = db.outputs.result(); // Output arrays always have their size set before use, for efficiency result.resize(firstSet.size()); std::transform(firstSet.begin(), firstSet.end(), secondSet.begin(), result.begin(), [alpha](GfVec3d const& firstValue, GfVec3d const& secondValue) -> GfVec3d { return firstValue * alpha + (1.0 - alpha) * secondValue; }); return true; } }; REGISTER_OGN_NODE() To see further examples of the C++ implementation code you can peruse the :ref:`samples used by the user guide<ogn_code_samples_py>` or the :ref:`user guide itself<ogn_user_guide>` itself. .. _ogn_example_node_cu: C++/Cuda Version ---------------- Nodes using CUDA are split into two parts - the `.cpp` implementation that sets up the CUDA execution, and the `.cu` file containing the actual GPU functions. .. code-block:: cpp #include <OgnAddWeightedPointsDatabase.h> // The generated code gives helper types matching the attribute names to make passing data more intuitive. // This declares the CUDA function that applies the blend. extern "C" void applyBlendGPU(inputs::points_t firstSet, inputs::points_t secondSet, inputs::alpha_t alpha, outputs::points_t outputPoints, size_t numberOfPoints); class OgnAddWeightedPoints { public: static bool compute(OgnAddWeightedPointsDatabase& db) { // Output arrays always have their size set before use, for efficiency size_t numberOfPoints = db.inputs.firstSet.size(); db.outputs.result.resize(numberOfPoints); if (numberOfPoints > 0) { auto const& alpha = db.inputs.alpha(); applyBlendGPU(db.inputs.firstSet(), db.inputs.secondSet(), alpha, db.outputs.result(), numberOfPoints); } return true; } }; REGISTER_OGN_NODE() The corresponding `.cu` implementation is: .. code-block:: cpp // Although it contains unsafe CUDA constructs the generated code has guards to let this inclusion work here too #include <OgnTutorialCudaDataDatabase.h> // CUDA compute implementation code will usually have two methods; // fooGPU() - Host function to act as an intermediary between CPU and GPU code // fooCUDA() - CUDA implementation of the actual node algorithm. __global__ void applyBlendCUDA( inputs::points_t firstSet, inputs::points_t secondSet, inputs::alpha_t alpha, outputs::points_t result, size_t numberOfPoints ) { int ptIdx = blockIdx.x * blockDim.x + threadIdx.x; if (numberOfPoints <= ptIdx) return; (*result)[ptIdx].x = (*firstSet)[ptIdx].x * alpha + (*secondSet)[ptIdx].x * (1.0 - alpha); (*result)[ptIdx].y = (*firstSet)[ptIdx].y * alpha + (*secondSet)[ptIdx].y * (1.0 - alpha); (*result)[ptIdx].z = (*firstSet)[ptIdx].z * alpha + (*secondSet)[ptIdx].z * (1.0 - alpha); } extern "C" void applyBlendGPU( inputs::points_t firstSet, inputs::points_t secondSet, outputs::points_t result, inputs::alpha_t& alpha, size_t numberOfPoints ) { const int numberOfThreads = 256; const int numberOfBlocks = (numberOfPoints + numberOfThreads - 1) / numberOfThreads; applyBlendCUDA<<<numberOfBlocks, numberOfThreads>>>(firstSet, secondSet, result, alpha, numberOfPoints); } To see further examples of how CUDA compute can be used see the :ref:`CUDA tutorial node <ogn_tutorial_cudaData>`. .. _ogn_example_node_warp: Warp Version ------------ A Warp node is written in exactly the same way as a Python node, except for its `compute()` it will make use of the Warp cross-compiler to convert the Python into highly performant CUDA code. You'll notice that there is more boilerplate code to write but it is pretty straightforward, mostly wrapping arrays into common types, and the performance is the result. .. code-block:: python import numpy as np import warp as wp @wp.kernel def deform(first_set: wp.array(dtype=wp.vec3), second_set: wp.array(dtype=wp.vec3), points_out: wp.array(dtype=wp.vec3), alpha: float): tid = wp.tid() points_out[tid] = first_set[tid] * alpha + second_set[tid] * (1.0 - alpha) class OgnAddWeightedPoints: @staticmethod def compute(db) -> bool: if not db.inputs.points: return True with wp.ScopedDevice("cuda:0"): # Get the inputs first_set = wp.array(db.inputs.points, dtype=wp.vec3) second_set = wp.array(db.inputs.points, dtype=wp.vec3) points_out = wp.zeros_like(first_set) # Do the work wp.launch(kernel=deform, dim=len(first_set), inputs=[first_set, second_set, points_out, db.inputs.alpha]) # Set the result db.outputs.points = points_out.numpy() To see further examples of how Warp can be used see the `Warp extension documentation. <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_warp.html>`_ .. _ogn_example_node_slang: Slang Version ------------- Unlike the previous types, Slang implementations are done directly within the application. Once you create a blank Slang node you open up the property panel and use the **Add+** button to add the attributes. This is what the attribute definition window will look like for one of the inputs. .. image:: images/SlangAddInput.png Add the three inputs and one input in this way. In the end the property panel should reflect the addition of the attributes the node will use. .. image:: images/SlangFinalProperties.png .. note:: For now the array index is passed through to the Slang compute function as the `instanceId` as the function will be called in parallel for each element in the array. The number of elements is reflected in the attribute `inputs:instanceCount` as seen in the property panel. In an OmniGraph you can connect either of the input point arrays through an `ArrayGetSize<GENERATED - Documentation _ognomni.graph.nodes.ArrayGetSize>` node to that attribute to correctly size the output array. .. code-block:: cpp void compute(uint instanceId) { double alpha = inputs_alpha_get(); double[3] v1 = inputs_firstSet_get(instanceId); double[3] v2 = inputs_secondSet_get(instanceId); double[3] result = { v1[0] * alpha + v2[0] * (1.0 - alpha), v1[1] * alpha + v2[1] * (1.0 - alpha), v1[2] * alpha + v2[2] * (1.0 - alpha) }; outputs_result_set(instanceId, result); } To see further examples of how Slang can be used see the `Slang extension documentation <https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_omnigraph/slang-nodes/nodes/slang.html>`_ .. _ogn_example_node_auto: AutoNode Version ---------------- For this version, as with the Slang version, there is no *.ogn* file required as the type information is gleaned from the node type definition. For this example only a single point will be used for inputs and outputs as the arrays are not yet fully supported. You just execute this code in the script editor or through a file and it will define a node type `my.local.extension.blend_point` for you to use as you would any other node. .. code-block:: python @og.AutoFunc(pure=True, module_name="my.local.extension") def blend_point(firstSet: og.Double3, secondSet: og.Double3, alpha: og.Double) -> og.Double3: return ( firstSet[0] * alpha + secondSet[0] * (1.0 - alpha), firstSet[1] * alpha + secondSet[1] * (1.0 - alpha), firstSet[2] * alpha + secondSet[2] * (1.0 - alpha), ) To see further examples of how AutoNode can be used see the :ref:`AutoNode documentation<autonode_ref>`. Node Writing Tutorials ====================== We have a number of tutorials to help you write nodes in OmniGraph. This set of tutorials will walk you through the node writing process by using examples that build on each other, from the simplest to the most complex nodes. .. toctree:: :maxdepth: 2 :glob: :ref:`Node Writing Tutorials <ogn_tutorial_nodes>` OmniGraph Nodes In Kit ====================== This is an amalgamated collection of documentation for all OmniGraph nodes that have been defined in Kit proper. Other nodes may exist in other extensions and will be in the documentation for those extensions. .. toctree:: :maxdepth: 1 :glob: ../../../../_build/ogn/docs/*
18,789
reStructuredText
40.026201
151
0.667199
omniverse-code/kit/exts/omni.graph.core/docs/omnigraph_arch_decisions.rst
.. _omnigraph_architectural_decisions_log: OmniGraph Architectural Decisions Log ------------------------------------- This log lists the architectural decisions for OmniGraph. For new ADRs, please use :doc:`the ADR Decision template<decisions/adr-template>`. More information on MADR is available at `the MADR website <https://adr.github.io/madr/>`_. General information about architectural decision records is available at `the MADR GitHub repository <https://adr.github.io/>`_. .. toctree:: :maxdepth: 1 :glob: decisions/0**
547
reStructuredText
23.90909
128
0.698355
omniverse-code/kit/exts/omni.graph.core/docs/architecture.rst
OmniGraph Architecture ********************** Fabric ====== As mentioned in the introduction, one of the key dependencies that OmniGraph has is Fabric. While not doing it justice, in a nutshell Fabric is a cache of USD data in vectorized, compute friendly form. OmniGraph leverages Fabric's data vectorization feature to help optimize its performance. Fabric also facilitates the movement of data between CPU and GPU, allowing data to migrate between the two in a transparent manner. There are currently two kinds of caches. There is a single StageWithHistory cache in the whole system, and any number of StageWithoutHistory caches. When a graph is created, it must specify what kind of Fabric cache "backs" it. All the data for the graph will be stored in that cache. USD === Like the rest of Omniverse, OmniGraph interacts with and is highly compatible with USD. We use USD for persistence of the graph. Moreover, since Fabric is essentially USD in compute efficient form, any transient compute data can be "hardened" to USD if we so choose. That said, while it is possible to do so, we recommend that node writers refrain from accessing USD data directly from the node, as USD is essentially global data, and accessing it from the node would prevent it from being parallel scheduled and thus get in the way of scaling and distribution of the overall system. .. toctree:: :maxdepth: 2 :glob: OmniGraph representations in USD<usd_representations> Data model ========== The heart of any graph system is its data model, as it strictly limits the range of compute expressible with the graph. Imagine what sort of compute can be expressed if the graph can only accept two integers, for example. OmniGraph supports a range of options for the data coursing through its connections. Regular attributes ------------------ As the most basic and straightforward, you can predeclare any attributes supported by USD on the node. Give it a name, a type, and a description, and that's pretty much all there is to it. OGN will synthesize the rest. While straightforward, this option limits the data to that which is predeclared, and limits the data types to the default ones available in USD. Bundle ------ To address the limitations of "regular" attributes, we introduced the notion of the "bundle". As the name suggests, this is a flexible "bundle" of data, similar to a prim. One can dynamically create any number of attributes inside the bundle and transport that data down the graph. This serves two important purposes. First, the system becomes more flexible - we are no longer limited to pre-declared data. Second, the system becomes more usable. Instead of many connections in the graph, we have just a single connection, with all the necessary data that needs to be transported. Extended Attributes ------------------- While bundles are flexible and powerful, they are still not enough. This is because its often desirable to apply a given set of functionality against a variety of data types. Think, for example, the functionality to add things. While the concept is the same, one might want to add integers, floats, and arrays of them, to name a few. It would be infeasible to create separate nodes for each possible type. Instead, we create the notion of extended attributes, where the attribute has just an unresolved placeholder at node creation time. Once the attribute is connected to another, regular attribute, it resolves to the type of that regular attribute. Note that extended attributes will not extend to bundles. Dynamic Attributes ------------------ Sometimes, it is desirable to modify an individual node instance rather than the node type. An example is a script node, where the user wants to just type in some bits of Python to create some custom functionality, without going through the trouble of creating a new node type. To this end it would be really beneficial to just be able to add some custom attributes onto the node instance (as opposed to the node type), to customize it for use. Dynamic attributes are created for this purpose - these are attributes that are not predeclared, and do not exist on the node type, but rather tacked on at runtime onto the node instance. OGN === Node systems come with a lot of boilerplate. For example, for every attribute one adds on a node, there needs to be code to create the attribute, initialize its value, and verify its value before compute, as a few examples. If the node writer is made responsible for these mundane tasks, not only would that add substantially to the overall cost of writing and maintaining the node, but also impact the robustness of the system overall as there may be inconsistencies/errors in how node writers go about implementing that functionality. Instead, we created a code synthesizing system named OGN (OmniGraph Nodes) to alleviate those issues. From a single json description of the node, OGN is able to synthesize all the boilerplate code to take the burden off developers and keep them focused on the core functionality of the node. In addition, from the same information, OGN is able to synthesize the docs and the tests for the node if the node writer provides it with expected inputs and outputs. .. toctree:: :maxdepth: 2 :glob: :ref:`OGN Node Writer Guide<ogn_user_guide>` :ref:`OGN Reference Guide<ogn_reference_guide>` OmniGraph is a graph of graphs ============================== Due to the wide range of use cases it needs to handle, a key design goal for OmniGraph is to able to create graphs of any kind, and not just the traditional flow graphs. To achieve this goal, OmniGraph maintains strict separation between graph representation and graph evaluation. Different evaluators can attach different semantics to the graph representation, and thus create any kind of graph. Broadly speaking, graph evaluators translate the graph representation into schedulable tasks. These tasks are then scheduled with the scheduling component. Unfortunately, as of this writing this mechanism has not been fully exposed externally. Creating new graph types still requires modification to the graph core. That said, we have already created several graph types, including busy graph (push), lazy evaluation graph (dirty_push), and event handling graph (action). Although it's desirable to be able to create different graph types, the value of the different graph types would be diminished if they didn't interact with each other. To this end, OmniGraph allows graphs to interact with each other by coordinating the tasks each graph generates. The rule is that each parent graph defines the rules by which tasks from subgraphs will coordinate with its own. Practically speaking, this means that current graph types are interoperable with one another. For example it is possible to combine a lazy evaluation graph with a busy evaluation graph, by constructing the lazy evaluation graph as a subgraph of the busy one - this allows part of the overall graph to be lazy and part of it to be busy. The lazy part of the graph will only be scheduled if someone touches some node in the graph, whereas the busy part will be scheduled always. The diagram below ties the concepts together - here we have two graphs interacting with each other. The outer blue, push graph and the inner green lazy evaluation graph. Through graph evaluation (the first yellow arrow), the nodes are translated to tasks. Here the rectangles are nodes and circles are tasks. Note that the translation of the outer graph is trivial - each node just maps to 1 task. The inner lazy graph is slightly more complicated - only those nodes that are dirty (marked by yellow) have tasks to be scheduled (tasks 3,5). Finally, through the graph stitching mechanism, task 5 is joined to task 8 as one of its dependencies: .. image:: ./images/graph_stitching.png :align: center push Graph ---------- This is the simplest of graph types. Nodes are translated to tasks on a one to one basis every single frame, causing all nodes in the graph to be scheduled. dirty_push Graph ---------------- This is a lazy evaluation graph. When nodes are modified, they send dirty bits downstream, just like traditional pull graphs as in Maya or Houdini, if the reader is familiar with those systems. However, unlike standard pull graphs, all dirtied nodes are scheduled, rather than the subset whose output is requested as in standard pull graphs. This is due to the fact that our viewport is not yet setup to generate the "pull". That said, just by scheduling only the dirtied nodes, this graph already goes most of the way in terms of minimizing the amount of work by not scheduling nodes that have not changed. action graph ------------ This is a graph type that is able to respond to events, such as mouse clicked or time changed. In response to these events, we can trigger certain downstream nodes into executing. The graph works in a similar way to Blueprints in UnReal Engine, in case the user is familiar with that system. This graph contains specialized attributes (execution) that allow users to describe the execution path upon receipt of an event. Action graphs also supports constructs such as branching and looping. Subgraphs --------- Currently subgraphs can be defined within the scope of its parent graph, and can be of a different type of graph than its parent. As mentioned in the previous section, it's up to the parent graph to define the rules of interoperability, if any, between itself and the subgraphs it contains. Note that currently there are no rules defined between sibling subgraphs, and any connections between nodes of sibling subgraphs can lead to undefined behavior. Pipeline Stages =============== Graphs are currently organized into several categories, also called "pipeline stages". There are currently 4 pipeline stages: simulation, pre-render, post-render, and on-demand. Graphs in the simulation pipeline stage are run before those in pre-render which in turn are run before those in post-render. When a pipeline stage runs, all the graphs contained in the pipeline stage are evaluated. The on-demand pipeline stage is a collection of graphs that aren't run in the above described order. Instead, are individually run at an unspecified time. The owner of the graphs in the on-demand stage are responsible for calling evaluate on the graph and thus "ticking" them. Global Graphs ------------- Within each pipeline stage, there may be a number of graphs, all independent of each other. Each of these independent graphs are known as a global graph. Each of the global graphs may contain further subgraphs that interoperate with each other in the above described manner. Global graphs are special in two ways: 1. They may have their own Fabric. When the global graph is created, it can specify whether it wants to use the "StageWithHistory" cache, or its very own "StageWithoutHistory" cache. All subgraphs of the global graph must choose the "shared" Fabric setting, to share the cache of its parent global graph. Since there is only one StageWithHistory cache, specifying the shared option with a global graph is the same as specifying the StageWithHistory option. 2. They handle USD notices Currently, all subgraphs must share the Fabric cache of the parent global graph, and they do not handle their own USD notices. Global graphs that have their own cache can always be run in parallel in a threadsafe way. Global graphs that share a Fabric cache must be more careful - currently update operations (say moving an object by updating its transform) are threadsafe, but adding / deleting things from the shared Fabric are not. Orchestration Graph ------------------- Within a pipeline stage, how do we determine the order of execution of all the global graphs contained in it? The answer is the orchestration graph. Each global graph is wrapped as a node in this orchestration graph. By default, all the nodes are independent, meaning the graphs can potentially execute in parallel, independent of each other. However, if ordering is important, the nodes that wrap the graph may introduce edges to specify ordering of graph execution. While graphs in the on-demand pipeline stage also do have an orchestration graph, no edges are permitted in here as the graphs in this stage aren't necessarily executed together. Python ====== All of OmniGraph's functionality is fully bound to Python. This allows scripting, testing in Python, as well as writing of nodes in Python. Python is a first class citizen in OmniGraph. The full Python API and commands are documented here: .. toctree:: :maxdepth: 1 :glob: :ref:`Python Documentation<omniGraph_python_scripting>` Scheduling ========== As OmniGraph separates graph evaluation from graph representation, it also separates scheduling concerns from the other pieces. Once the graph evaluator does its job and translates the graph representation into tasks, we can schedule those tasks through any number of means. Static serial scheduler ----------------------- This is the simplest of the schedulers. It schedules tasks serially, and does not allow modification of the task graph. Realm scheduler --------------- This scheduler takes advantage of the Realm technology (super efficient microsecond level efficient scheduler) to parallel schedule the tasks. Dynamic scheduler ----------------- The dynamic scheduler allows the modification of the task graph at runtime, based on results of previous tasks. Currently the modification is limited to canceling of future tasks already scheduled. Extensions ========== Although you can see these in the extension window it is cluttered up with non-OmniGraph extensions. This is a distillation of how all of the **omni.graph.XXX** extensions depend on each other. Dotted lines represent optional dependencies. Lines with numbers represent dependencies on specific extension version numbers. Lines with `Test Only` represent dependencies that are only enabled for the purposes of running the extension's test suite. .. mermaid:: flowchart LR subgraph Core core(omni.graph.core) inspect(omni.inspect) py(omni.graph) tools(omni.graph.tools) end subgraph UI ui(omni.graph.ui) win(omni.graph.window.action) win_core(omni.graph.window.core) win_gen(omni.graph.window.generic) end subgraph Nodes ex_cpp(omni.graph.examples.cpp) ex_py(omni.graph.examples.python) action(omni.graph.action) exp(omni.graph.expression) nodes(omni.graph.nodes) script(omni.graph.scriptnode) io(omni.graph.io) end subgraph Support ext(omni.graph.example.ext) test(omni.graph.test) tut(omni.graph.tutorials) end bundle(omni.graph.bundle.action) core -.-> inspect py --> core py --> tools ex_cpp --> py ex_cpp --> tools ex_py --> py ex_py --> tools action --> py action --> tools action -.-> ui bundle --> py bundle --> action bundle --> nodes bundle --> tut bundle --> ui bundle --> win bundle --> inst inst --> core inst --> py inst --> tools inst --> nodes inst --> ui ui --> py ui --> tools ui -- Test Only --> action exp --> py exp --> tools ext --> py ext --> tools io --> py io --> ui nodes --> py nodes --> script nodes --> tools nodes -.-> ui script --> py script --> tools script --> action test --> py test --> tools test --> ex_cpp test --> ex_py test --> nodes test --> tut test --> action test --> script tut --> py tut --> nodes tut --> tools win_core -- 1.11 --> py win_core --> tools win_core -- 1.5 --> ui win_gen -- 1.16 --> win_core win_gen -- 1.5 --> ui win -- 1.16 --> win_core win -- 1.5 --> ui
16,177
reStructuredText
47.292537
458
0.740619
omniverse-code/kit/exts/omni.graph.core/docs/categories.rst
.. _omnigraph_node_categories: OmniGraph Node Categories ========================= An OmniGraph node can have one or more categories associated with it, giving the UI a method of presenting large lists of nodes or node types in a more organized manner. Category Specification In .ogn File ----------------------------------- For now the node categories are all specified through the .ogn file, so the node will inherit all of the categories that were associated with its node type. There are three ways you can specify a node type category in a .ogn file; using a predefined category, creating a new category definition inline, or referencing an external file that has shared category definitions. Predefined Categories +++++++++++++++++++++ This is the simplest, and recommended, method of specifying categories. There is a single .ogn keyword to add to the file to associate categories with the node type. It can take three different forms. The first is a simple string with a single category in it: .. code-block:: json { "MyNodeWithOneCategory": { "version": 1, "categories": "function", "description": "Empty node with one category" } } .. warning:: The list of categories is intentionally fixed. Using a category name that is not known to the system will result in a parsing failure and the node will not be generated. See below for methods of expanding the list of available categories. The second is a comma-separated list within that string, which specifies more than one category. .. code-block:: json { "MyNodeWithTwoCategories": { "version": 1, "categories": "function,time", "description": "Empty node with two categories" } } The last also specifies more than one category; this time in a list format: .. code-block:: json { "MyNodeWithAListOfTwoCategories": { "version": 1, "categories": ["function", "time"], "description": "Empty node with a list of two categories" } } The predefined list is contained within a configuration file. :ref:`Later<omnigraph_categories_shared_file>` you will see how to add your own category definitions. The predefined configuration file looks like this: .. literalinclude:: ../../../../source/extensions/omni.graph.tools/ogn_config/CategoryConfiguration.json :language: json .. note:: You might have noticed some categories contain a colon as a separator. This is a convention that allows splitting of a single category into subcategories. Some UI may choose to use this information to provide more fine-grained filtering an organizing features. Inline Category Definition ++++++++++++++++++++++++++ On occasion you may find that your node does not fit into any of the predefined categories, or you may wish to add extra categories that are specific to your project. One way to do this is to define a new category directly within the .ogn file. The way you define a new category is to use a *name:description* category dictionary rather than a simple string. For example, you could replace a single string directly: .. code-block:: json { "MyNodeWithOneCustomCategory": { "version": 1, "categories": {"light": "Nodes implementing lights for rendering"}, "description": "Empty node with one custom category" } } You can add more than one category by adding more dictionary entries: .. code-block:: json { "MyNodeWithTwoCustomCategories": { "version": 1, "categories": { "light": "Nodes implementing lights for rendering", "night": "Nodes implementing all aspects of nighttime" }, "description": "Empty node with two custom categories" } } You can also mix custom categories with predefined categories using the list form: .. code-block:: json { "MyNodeWithMixedCategories": { "version": 1, "categories": ["rendering", { "light": "Nodes implementing lights for rendering", "night": "Nodes implementing all aspects of nighttime" } ], "description": "Empty node with mixed categories" } } .. _omnigraph_categories_shared_file: Shared Category Definition File +++++++++++++++++++++++++++++++ While adding a category definition directly within a file is convenient, it is not all that useful as you either only have one node type per category, or you have to duplicate the category definitions in every .ogn file. A better approach is to put all of your extension's, or project's, categories into a single configuration file and add it to the build. The configuration file is a .json file containing a single dictionary entry with the keyword *categoryDefinitions*. The entries are *name:description* pairs, where *name* is the name of the category that can be used in the .ogn file and *description* is a short description of the function of node types within that category. Here is the file that would implement the above two custom categories: .. code-block:: json { "categoryDefinitions": { "$description": "These categories are applied to nodes in MyProject", "light": "Nodes implementing lights for rendering", "night": "Nodes implementing all aspects of nighttime" } } .. tip:: As with regular .ogn file any keyword beginning with a "*$*" will be ignored and can be used for documentation. If your extension is building within Kit then you can install your configuration into the build by adding this line to your *premake5.lua* file: .. code-block:: lua install_ogn_configuration_file("MyProjectCategories.json") This allows you to reference the new category list directly from your .ogn file, expanding the list of available categories using the .ogn keyword *categoryDefinitions*: .. code-block:: json { "MyNodeWithOneCustomCategory": { "version": 1, "categoryDefinitions": "MyProjectCategories.json", "categories": "light", "description": "Empty node with one custom category" } } Here, the predefined category list has been expanded to include those defined in your custom category configuration file, allowing use of the new category name without an explicit definition. If your extension is independent, either using the Kit SDK to build or not having a build component at all, you can instead reference either the absolute path of your configuration file, or the path relative to the directory in which your .ogn resides. As with categories, the definition references can be a single value or a list of values: .. code-block:: json { "MyNodeWithOneCustomCategory": { "version": 1, "categoryDefinitions": ["myConfigDirectory/MyProjectCategories.json", "C:/Shared/Categories.json"], "categories": "light", "description": "Empty node with one custom category" } } Category Access From Python --------------------------- Category Access From C++ ------------------------
7,300
reStructuredText
36.060914
120
0.673836
omniverse-code/kit/exts/omni.graph.core/docs/how_to.rst
.. _omnigraph_how_to: OmniGraph How-To Guide ====================== .. toctree:: :maxdepth: 2 :caption: How-To :glob: :ref:`Specifying Categories In Your Nodes <omnigraph_node_categories>` :ref:`Interfacing With OmniGraph <omnigraph_controller_class>` :ref:`Initializing Attribute Values At Runtime <runtime_attribute_value_initialization_in_omnigraph_nodes>` :ref:`Set Up Test Scripts <set_up_omnigraph_tests>` :ref:`Run Only A Python Script With OmniGraph code <run_omnigraph_python_script>`
521
reStructuredText
31.624998
110
0.700576