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.legacy_gizmos/config/extension.toml
[package] version = "1.0.10" title = "Legacy Viewport Gizmo drawing" description = "Deprecated API to draw gizmos in the viewport." authors = ["NVIDIA"] category = "Viewport" repository = "" readme = "docs/README.md" keywords = ["kit", "viewport", "gizmo"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [[native.plugin]] path = "bin/*.plugin" recursive = false [dependencies] "omni.usd" = {} [[python.module]] name = "omni.kit.viewport.legacy_gizmos" [settings] # Whether the Viewprt grid is enabled/visible or not app.viewport.grid.enabled = true # Whether to automatically update the grid-plane based on UsdContext and active camera app.viewport.grid.trackCamera = false [[test]] # RTX may need to build the shader-cache, so give it some time timeout = 900 dependencies = [ # FIXME: omni.ui provides carb.Format conversions required "omni.ui", "omni.hydra.rtx", "omni.kit.hydra_texture", "omni.kit.renderer.capture", "omni.kit.test_helpers_gfx" ] args = [ "--/renderer/enabled=rtx", "--/app/asyncRendering=false", "--/omni.kit.plugin/syncUsdLoads=true", "--/rtx/hydra/materialSyncLoads=true", "--/rtx/materialDb/syncLoads=true", "--/rtx/post/aa/op=0", "--/rtx/reflections/enabled=0", "--/rtx-defaults/post/aa/op=0", "--/rtx-defaults/reflections/enabled=0", "--no-window" ] unreliable = true # OM-49114 [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,497
TOML
23.557377
86
0.676687
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/omni/kit/viewport/legacy_gizmos/tests/test_legacy_gizmos.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 pathlib import asyncio import carb import omni.kit.app import omni.kit.test import omni.hydratexture import omni.renderer_capture from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric import omni.usd from pxr import Usd, Gf # FIXME: omni.ui.ImageProvider holds the carb.Format conversion routine import omni.ui EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TEST_DATA_DIR = EXTENSION_FOLDER_PATH.joinpath('data', 'tests') KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve('${kit}')).parent.parent.parent OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path()) from sys import platform if platform.find('linux') == 0: IMAGE_PLATFORM='linux' elif platform == 'darwin': IMAGE_PLATFORM='macos' elif platform == 'win32': IMAGE_PLATFORM='windows' class TestLegacyGizmos(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.acquire_settings_interface() self._hydra_texture_factory = omni.hydratexture.acquire_hydra_texture_factory_interface() self._render_capture = omni.renderer_capture.acquire_renderer_capture_interface() self._usd_context_name = 'test_context' self._usd_context = omni.usd.create_context(self._usd_context_name) async def tearDown(self): omni.usd.release_all_hydra_engines(self._usd_context) omni.usd.destroy_context(self._usd_context_name) self._hydra_texture_factory = None self._settings = None self._render_capture = None async def _create_hydra_texture_test(self, filename: str = None): wait_iterations = 15 try: if 'rtx' not in self._usd_context.get_attached_hydra_engine_names(): omni.usd.add_hydra_engine('rtx', self._usd_context) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async() if filename: test_usd_asset = TEST_DATA_DIR.joinpath(filename) self._usd_context.open_stage_with_callback(str(test_usd_asset), None) else: self._usd_context.new_stage_with_callback(None) hydra_texture = self._hydra_texture_factory.create_hydra_texture( 'test_viewport', 320, 320, self._usd_context_name, '/OmniverseKit_Persp', 'rtx', is_async=False ) return hydra_texture finally: for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async() async def _capture_hydra_texture(self, hydra_texture, test_name: str, converge: int = 5, platform_image: bool = False): drawable_result = asyncio.Future() if platform_image: global IMAGE_PLATFORM image_name = f'{test_name}_{IMAGE_PLATFORM}.png' else: image_name = f'{test_name}.png' filepath = OUTPUTS_DIR.joinpath(image_name).absolute() def on_drawable_changed(event: carb.events.IEvent): if event.type != omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED: carb.log_error('Wrong event captured for DRAWABLE_CHANGED') return result_handle = event.payload['result_handle'] self.assertIsNotNone(result_handle) ldr_info = hydra_texture.get_aov_info(result_handle, 'LdrColor', include_texture=True) self.assertEqual(len(ldr_info), 1) self.assertEqual(ldr_info[0]['name'], 'LdrColor') ldr_tex = ldr_info[0]['texture'] self.assertIsNotNone(ldr_tex) ldr_rsrc = ldr_tex['rp_resource'] self.assertIsNotNone(ldr_rsrc) nonlocal converge converge = converge - 1 if converge <= 0 and not drawable_result.done(): self._render_capture.capture_next_frame_rp_resource(str(filepath), ldr_rsrc) drawable_result.set_result(True) drawable_change_sub = hydra_texture.get_event_stream().create_subscription_to_push_by_type( omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED, on_drawable_changed, name="_capture_hydra_texture", ) result = await drawable_result drawable_change_sub = None self.assertTrue(result) return image_name async def capture_and_compare(self, image_name: str, threshold: float = 1e-4): # self._render_capture.wait_async_capture() diff = finalize_capture_and_compare(image_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=TEST_DATA_DIR, metric=ComparisonMetric.MEAN_ERROR_SQUARED) if diff > threshold: carb.log_error(f'The generated image {image_name} has a difference of {diff}, but max difference is {threshold}') async def test_light_gizmos(self): hydra_texture = await self._create_hydra_texture_test('gizmos.usda') self.assertIsNotNone(hydra_texture) # >> test_sphere_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 1) self._settings.set('/persistent/app/viewport/gizmo/scale', 1) self._usd_context.get_selection().set_selected_prim_paths(['/World/SphereLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_sphere_light', platform_image=True) await self.capture_and_compare(image) # << test_sphere_light # >> test_cylinder_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 2) self._settings.set('/persistent/app/viewport/gizmo/scale', 2) self._usd_context.get_selection().set_selected_prim_paths(['/World/CylinderLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_cylinder_light', platform_image=True) await self.capture_and_compare(image) # << test_cylinder_light # >> test_disk_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 10) self._settings.set('/persistent/app/viewport/gizmo/scale', 10) self._usd_context.get_selection().set_selected_prim_paths(['/World/DiskLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_disk_light', platform_image=True) await self.capture_and_compare(image) # << test_disk_light # >> test_rect_light self._settings.set('/app/viewport/grid/enabled', False) self._settings.set('/persistent/app/viewport/gizmo/lineWidth', 20) self._settings.set('/persistent/app/viewport/gizmo/scale', 20) self._usd_context.get_selection().set_selected_prim_paths(['/World/RectLight'], True) image = await self._capture_hydra_texture(hydra_texture, 'test_rect_light', platform_image=True) await self.capture_and_compare(image) # << test_rect_light async def test_grid_drawing(self): hydra_texture = await self._create_hydra_texture_test('empty.usda') self.assertIsNotNone(hydra_texture) # >> test_grid_drawing self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/persistent/app/viewport/grid/lineWidth', 1) self._settings.set('/persistent/app/viewport/grid/scale', 100) # Need to wait for slightly more frames on Linux to avoid writing black imge / failure image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing', converge=20) await self.capture_and_compare(image) # << test_grid_drawing # >> test_grid_drawing_yz self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'YZ') self._settings.set('/persistent/app/viewport/grid/lineWidth', 10) self._settings.set('/persistent/app/viewport/grid/scale', 150) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_yz') await self.capture_and_compare(image) # << test_grid_drawing_yz # >> test_grid_drawing_xy self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'XY') self._settings.set('/persistent/app/viewport/grid/lineWidth', 4) self._settings.set('/persistent/app/viewport/grid/scale', 200) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_xy') await self.capture_and_compare(image) # << test_grid_drawing_xy # >> test_grid_drawing_xz self._settings.set('/app/viewport/grid/enabled', True) self._settings.set('/persistent/app/viewport/grid/lineColor', carb.Float3(0.3, 0.3, 0.3)) self._settings.set('/app/viewport/grid/plane', 'XZ') self._settings.set('/persistent/app/viewport/grid/lineWidth', 6) self._settings.set('/persistent/app/viewport/grid/scale', 250) image = await self._capture_hydra_texture(hydra_texture, 'test_grid_drawing_xz') await self.capture_and_compare(image) # << test_grid_drawing_xz async def test_camera_gizmos(self): hydra_texture = await self._create_hydra_texture_test('cameras.usda') self.assertIsNotNone(hydra_texture) wait_iterations = 5 try: self._settings.set('/app/viewport/show/camera', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', False) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', False) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 10.0) self._settings.set('/persistent/app/viewport/gizmo/scale', 2.0) self._settings.set('/app/viewport/grid/enabled', False) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_0') await self.capture_and_compare(image) stage = self._usd_context.get_stage() camera_prim = stage.GetPrimAtPath('/World/Camera') camera_prim.GetAttribute('xformOp:translate').Set(Gf.Vec3d(0, 0, -250)) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_1') await self.capture_and_compare(image) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 50.0) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', True) for i in range(wait_iterations): await omni.kit.app.get_app().next_update_async(); image = await self._capture_hydra_texture(hydra_texture, 'test_camera_drawing_2') await self.capture_and_compare(image) finally: self._settings.set('/app/viewport/show/camera', False) self._settings.set('/persistent/app/viewport/gizmo/scale', 1.0) self._settings.set('/persistent/app/viewport/gizmo/constantScale', 10.0) self._settings.set('/persistent/app/viewport/gizmo/constantScaleEnabled', True) self._settings.set('/persistent/app/viewport/gizmo/constantScaleCamera', False)
12,491
Python
45.095941
125
0.650548
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/omni/kit/viewport/legacy_gizmos/tests/__init__.py
from .test_legacy_gizmos import TestLegacyGizmos
49
Python
23.999988
48
0.857143
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.10] - 2023-01-31 ### Added - /app/viewport/grid/offset setting to control grid placement in relation to origin. - Ability to disable bounding box updates during user intraction. ## [1.0.9] - 2023-01-25 ### Added - /app/viewport/grid/trackCamera setting to automatically update grid based on camera. ## [1.0.8] - 2022-12-09 ### Fixed - Issue with slow billboard updates during camera movement. ## [1.0.7] - 2022-10-24 ### Fixed - Clearing of gizmo prims when exiting live session. ## [1.0.6] - 2022-08-22 ### Fixed - Acquire Usd read lock in draw call. ## [1.0.5] - 2022-08-22 ### Fixed - Support latest UsdContext r/w lock pattern. ## [1.0.4] - 2022-08-08 ### Fixed - Performance issues when updating many USD scene representation cameras. ## [1.0.3] - 2022-08-05 ### Added - Remove camera gizmo if camera prim is removed or camera visibility turns off. ## [1.0.2] - 2022-07-26 ### Added - Honor camera scale independent of gizmo constant scale enabled state. - Ability to create and update legacy USD camera mesh representations. - Push values to /app/viewport/boundingBoxes/enabled as legacy Viewport did. ## [1.0.1] - 2022-02-03 - Added tests. ## [1.0.0] - 2021-10-15 - Initial version
1,303
Markdown
25.612244
86
0.699923
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/docs/index.rst
omni.kit.viewport.legacy_gizmos ################################################################################# API Reference ============== .. automodule:: omni.kit.viewport.legacy_gizmos :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members:
294
reStructuredText
23.583331
81
0.47619
omniverse-code/kit/exts/omni.kit.viewport.legacy_gizmos/docs/Overview.md
# Overview
11
Markdown
4.999998
10
0.727273
omniverse-code/kit/exts/omni.kit.notification_manager/PACKAGE-LICENSES/omni.kit.notification_manager-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.notification_manager/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.5" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Notification Manager" description="Extension that provides interface to post notifications." # 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", "notification"] # 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.ui" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.notification_manager" [[test]] args = [ "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.commands", "omni.kit.renderer.capture", "omni.kit.mainwindow" ] unreliable = true # OM-48628
1,541
TOML
27.036363
107
0.724854
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/notification_info.py
class NotificationStatus: WARNING = 0 INFO = 1 class NotificationButtonInfo: def __init__(self, text, on_complete=None): """ Constructor for notification button. text (str): The button text. on_complete (Callable[]): The handler to handle button click. """ self._text = text self._on_complete = on_complete @property def text(self): return self._text @property def handler(self): return self._on_complete class NotificationInfo: def __init__( self, text, hide_after_timeout=True, duration=3, status=NotificationStatus.INFO, button_infos=[]): self._text = text self._hide_after_timeout = hide_after_timeout self._duration = duration self._status = status if not button_infos and not hide_after_timeout: button_info = NotificationButtonInfo("Dismiss", None) self._button_infos = [button_info] else: self._button_infos = button_infos @property def text(self): return self._text @property def hide_after_timeout(self): return self._hide_after_timeout @property def duration(self): return self._duration @property def status(self): return self._status @property def button_infos(self): return self._button_infos
1,448
Python
21.640625
69
0.580801
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import os import weakref import omni.ext from functools import partial from .manager import NotificationManager from .notification_info import NotificationInfo, NotificationStatus _global_instance = None def post_notification( text, hide_after_timeout=True, duration=3, status=NotificationStatus.INFO, button_infos=[] ): """ Post notification. If viewport is visible, it will be docked to the right-button of viewport. Otherwise, it will be docked to main window. Args: text (str): The notification text. hide_after_timeout (bool): If the notification will hide after duration. If it's False, and button_details are not provided, it will display a default dismiss button. duration (int): The duration (in seconds) after which the notification will be hidden. This duration only works if hide_after_timeout is True. status (NotificationStatus): The notification type. button_infos ([NotificationButtonInfo]): Array of buttons. Returns: Notification handler. Examples: >>> import omni.kit.notification_manager as nm >>> >>> ok_button = nm.NotificationButtonInfo("OK", on_complete=None) >>> cancel_button = nm.NotificationButtonInfo("CANCEL", on_complete=None) >>> notification = nm.post_notification( "Notification Example", hide_after_timeout=False, duration=0, status=nm.NotificationStatus.WARNING, button_infos=[ok_button, cancel_button]) """ global _global_instance if _global_instance and _global_instance(): ni = NotificationInfo(text, hide_after_timeout, duration, status, button_infos) return _global_instance().post_notification(ni) return None class NotificationManagerExtension(omni.ext.IExt): def on_startup(self): global _global_instance _global_instance = weakref.ref(self) self._notification_manager = NotificationManager() self._notification_manager.on_startup() def on_shutdown(self): global _global_instance _global_instance = None self._notification_manager.on_shutdown() self._notification_manager = None def post_notification(self, notification_info: NotificationInfo): return self._notification_manager.post_notification(notification_info)
2,929
Python
37.552631
132
0.681803
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import * from .notification_info import NotificationButtonInfo, NotificationStatus
533
Python
43.499996
76
0.816135
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/manager.py
import asyncio import carb import omni.kit.app import omni.ui as ui from typing import List from .notification_info import NotificationInfo, NotificationStatus from .prompt import Prompt SETTINGS_DISABLE_NOTIFICATIONS = "/exts/omni.kit.notification_manager/disable_notifications" class Notification: """Handler of notification""" def __init__(self, notification_info: NotificationInfo, notification_manager): """Internal constructor""" self._prompt = None self._notification_info = notification_info self._time_passed = 0 self._notification_mananger = notification_manager self._is_warming = True def destroy(self): self._is_warming = False self._notification_info = None if self._prompt: self._prompt.destroy() self._prompt = None if self._notification_mananger: self._notification_mananger.remove_notification(self) self._notification_mananger = None def _step_and_check(self, dt): if not self._prompt: return True if self._notification_info.hide_after_timeout: if self._time_passed >= self._notification_info.duration: return True self._time_passed += dt return False async def _docking_to(self, window_x, window_y, window_width, window_height, offset_y=0): if self._prompt: await self._prompt.docking_to(window_x, window_y, window_width, window_height, offset_y) def _hide(self): if self._prompt: self._prompt.hide() async def _pre_warming(self): self._prompt = Prompt(self._notification_info) # Set it to a corner pos self._prompt.position_x = 100000 self._prompt.position_y = 100000 # FIXME: After creation, the notification window still # does not have the correct width/height. It needs to # show and wait for the first draw to get correct width/height. # The following code shows it and all notification will # be transparent at the start. After getting correct widht/height, # it will be positioned to correct position later. self._prompt.show() self._is_warming = False async def _warming(): while not self._notification_mananger._shutdown and (self._prompt.width == 0.0 or self._prompt.height == 0.0): await omni.kit.app.get_app().next_update_async() self._hide() if not self._notification_mananger._shutdown: self._notification_mananger._pending_notifications.append(self) await _warming() @property def _dismissed(self): return self._prompt is None or not self._prompt.visible @property def _hovered(self): return self._prompt and self._prompt.hovered @property def info(self): return self._notification_info def dismiss(self): self.destroy() @property def dismissed(self): return not self._is_warming and self._prompt is None class NotificationManager: def on_startup(self): self._max_showed_notifications = 5 self._max_throttle_notifications = self._max_showed_notifications + 2 self._pre_warming_notifications: List[Notification] = [] self._pending_notifications: List[Notification] = [] self._notifications: List[Notification] = [] self._timer_task = None self._shutdown = False self._docking_window_width = 0 self._docking_window_height = 0 self._docking_window_pos_x = 0 self._docking_window_pos_y = 0 async def timer_fn(): while not self._shutdown: """ For each notification, it has 3 stages: 1. When it's created, it will be put in the pre-warming queue. Pre-warming is a WA to calculate the real size of prompt before it's positioning. 2. After pre-warming, it will be put to pending queue and waits to be displayed there. 3. If there is vacancy (determined by _max_showed_notifications), it will be displayed to viewport finally. """ showed_notifications = len(self._pending_notifications) + len(self._notifications) new_notifications = max(self._max_throttle_notifications - showed_notifications, 0) new_notifications = min(len(self._pre_warming_notifications), new_notifications) for _ in range(new_notifications): notification = self._pre_warming_notifications.pop(0) await notification._pre_warming() # To avoid flooding notification queue, all others will be flushed to console. for notification in self._pre_warming_notifications: if notification.info.status == NotificationStatus.INFO: carb.log_info(notification.info.text) else: carb.log_warn(notification.info.text) notification.destroy() self._pre_warming_notifications.clear() changed = self._on_docking_window_changed() pending_to_remove = [] for notification in self._notifications: if ( (notification._step_and_check(0.5) and not notification._hovered) or notification._dismissed ): pending_to_remove.append(notification) if len(pending_to_remove): changed = True for item in pending_to_remove: item.destroy() num_current_notifications = len(self._notifications) if num_current_notifications < self._max_showed_notifications: new_added = self._max_showed_notifications - num_current_notifications else: new_added = 0 num_pending_notifications = len(self._pending_notifications) new_added = min(new_added, num_pending_notifications) for i in range(new_added): notification = self._pending_notifications.pop(0) self._notifications.append(notification) if new_added > 0: changed = True if changed: offset_y = 0 for notification in self._notifications: await notification._docking_to(self._docking_window_pos_x, self._docking_window_pos_y, self._docking_window_width, self._docking_window_height, offset_y) offset_y += notification._prompt.height + 5 # Step 1s await asyncio.sleep(0.5) self._timer_task = asyncio.ensure_future(timer_fn()) def on_shutdown(self): self._shutdown = True if self._timer_task: self._timer_task.cancel() self._timer_task = None for notification in self._notifications: notification.destroy() for notification in self._pending_notifications: notification.destroy() for notification in self._pre_warming_notifications: notification.destroy() self._notifications.clear() self._pending_notifications.clear() self._pre_warming_notifications.clear() def post_notification(self, notification_info: NotificationInfo): notification = Notification(notification_info, self) # OM-87367: options to disable all notifications. settings = carb.settings.get_settings() disable_all_notifications = settings.get(SETTINGS_DISABLE_NOTIFICATIONS) if disable_all_notifications: if notification.info.status == NotificationStatus.INFO: carb.log_info(notification.info.text) else: carb.log_warn(notification.info.text) notification.destroy() else: self._pre_warming_notifications.append(notification) # Still returns the handle of notification. return notification def remove_notification(self, notification: Notification): try: if notification in self._notifications: self._notifications.remove(notification) if notification in self._pending_notifications: self._pending_notifications.remove(notification) if notification in self._pre_warming_notifications: self._pre_warming_notifications.remove(notification) except ValueError: pass def _on_docking_window_changed(self): viewport = ui.Workspace.get_window("Viewport") if viewport and viewport.visible: window_position_x = viewport.position_x window_position_y = viewport.position_y window_width = viewport.width window_height = viewport.height else: window_position_x = 0 window_position_y = 0 window_width = ui.Workspace.get_main_window_width() window_height = ui.Workspace.get_main_window_height() if ((self._docking_window_pos_x != window_position_x) or (self._docking_window_pos_y != window_position_y) or (self._docking_window_width != window_width) or (self._docking_window_height != window_height)): self._docking_window_pos_x = window_position_x self._docking_window_pos_y = window_position_y self._docking_window_width = window_width self._docking_window_height = window_height return True return False
9,827
Python
37.390625
177
0.598962
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/prompt.py
import weakref import omni.ui as ui import omni.kit.app import uuid from .notification_info import NotificationStatus, NotificationButtonInfo, NotificationInfo from .icons import Icons HOVER_AREA_TRANSPARENT_STYLE = { "background_color": 0x0, "background_gradient_color": 0x0, "background_selected_color": 0x0, "border_color": 0x0, "color": 0x0, "selected_color": 0x0, "secondary_color": 0x0, "secondary_selected_color": 0x0, "debug_color": 0x0 } HOVER_AREA_DEFAULT_STYLE = { "Rectangle::hover_area_info": {"background_color": 0xFFE2B170, "border_radius": 10}, "Rectangle::hover_area_warning": {"background_color": 0xFF5EC7E8, "border_radius": 10}, "Label::text": {"font_size": 14, "color": 0xFF000000}, "Image::status_warning": {"image_url": Icons().get("warning"), "color": 0xFF000000}, "Image::status_info": {"image_url": Icons().get("info"), "color": 0xFF000000}, "Button:hovered": {"background_color": 0xFF9E9E9E}, } class Prompt: def __init__(self, notification_info: NotificationInfo): self._notification_info = notification_info self._build_ui( notification_info.text, notification_info.status, notification_info.button_infos ) self._docking_window_x = 0 self._docking_window_y = 0 self._docking_window_width = 0 self._docking_window_height = 0 self._hovered = False def destroy(self): self._notification_info = None self._window.destroy() self._window = None def __enter__(self): self._window.show() return self def __exit__(self, type, value, trace): self._window.hide() def show(self): self._window.visible = True def hide(self): self._window.visible = False @property def hovered(self): return self._hovered @property def visible(self): return self._window.visible @visible.setter def visible(self, value): self._window.visible = value @property def position_x(self): return self._window.position_x @position_x.setter def position_x(self, value): self._window.position_x = value @property def position_y(self): return self._window.position @position_y.setter def position_y(self, value): self._window.position_y = value @property def width(self): return self._window.width @property def height(self): return self._window.height async def docking_to(self, window_x, window_y, window_width, window_height, offset_y=0): self._docking_window_x = window_x self._docking_window_y = window_y self._docking_window_width = window_width self._docking_window_height = window_height self._window.visible = True # FIXME: No idea why this works. It needs to wait for the width/height to be stabalized. await omni.kit.app.get_app().next_update_async() position_x = self._docking_window_x + self._docking_window_width - self._window.width - 16 position_y = self._docking_window_y + self._docking_window_height - self._window.height - 16 - offset_y self._window.position_x = position_x if position_x > 0 else 0 self._window.position_y = position_y if position_y > 0 else 0 if self._notification_info.status == NotificationStatus.INFO: self._window.frame.set_style({"Window": {"background_color": 0xFF75542A, "border_radius": 10}}) else: self._window.frame.set_style({"Window": {"background_color": 0xFF2D5CA1, "border_radius": 10}}) self._layout.set_style(HOVER_AREA_DEFAULT_STYLE) def _build_ui(self, text, status, button_details): self._window = ui.Window(str(uuid.uuid1()), visible=False, height=0, dockPreference=ui.DockPreference.DISABLED) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_CLOSE | ui.WINDOW_FLAGS_NO_FOCUS_ON_APPEARING ) def _button_handler(handler): self.hide() if handler: handler() weak_self = weakref.ref(self) def _on_hovered(hovered): if not weak_self(): return weak_self()._hovered = hovered self._window.frame.style = HOVER_AREA_TRANSPARENT_STYLE with self._window.frame: self._layout = ui.ZStack(style=HOVER_AREA_DEFAULT_STYLE, height=0) with self._layout: if status == NotificationStatus.INFO: hover_area = ui.Rectangle(name="hover_area_info") else: hover_area = ui.Rectangle(name="hover_area_warning") hover_area.set_mouse_hovered_fn(_on_hovered) with ui.VStack(height=0): ui.Spacer(height=5) with ui.HStack(height=0): if status == NotificationStatus.INFO: name = "status_info" else: name = "status_warning" ui.Spacer(width=5) ui.Image(width=20, alignment=ui.Alignment.CENTER, name=name) ui.Spacer(width=10) ui.Label( text, name="text", word_wrap=True, width=self._window.width - 44, height=0, alignment=ui.Alignment.LEFT ) ui.Spacer() if button_details: button_width = 60 if len(button_details) >=3 else 120 ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer() button = ui.Button(button_details[0].text, width=button_width, height=0) button.set_clicked_fn(lambda a=button_details[0].handler: _button_handler(a)) for i in range(len(button_details) - 1): ui.Spacer(width=5) button_info = button_details[i + 1] button = ui.Button(button_info.text, width=button_width, height=0) button.set_clicked_fn(lambda a=button_info.handler: _button_handler(a)) ui.Spacer() ui.Spacer(height=5)
6,796
Python
36.346154
119
0.556651
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/icons.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pathlib import Path from .singleton import Singleton @Singleton class Icons: """A singleton that scans the icon folder and returns the icon depending on the type""" def __init__(self): self._current_path = Path(__file__).parent self._icon_path = self._current_path.parent.parent.parent.joinpath("icons") # Read all the svg files in the directory self._icons = {icon.stem: icon for icon in self._icon_path.glob("*.svg")} def get(self, name, default=None): """Checks the icon cache and returns the icon if exists""" found = self._icons.get(name) if not found and default: found = self._icons.get(default) if found: return str(found)
1,175
Python
35.749999
91
0.69617
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/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.notification_manager/omni/kit/notification_manager/tests/__init__.py
from .test_notification_manager import TestNotificationManagerUI
65
Python
31.999984
64
0.892308
omniverse-code/kit/exts/omni.kit.notification_manager/omni/kit/notification_manager/tests/test_notification_manager.py
import asyncio import carb.settings import omni.kit.test import omni.ui as ui import omni.kit.notification_manager as nm from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from threading import Thread CURRENT_PATH = Path(__file__).parent.joinpath("../../../../data") class TestNotificationManagerUI(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") self._all_notifications = [] self._settings = carb.settings.get_settings() self._original_value = self._settings.get_as_int("/persistent/app/viewport/displayOptions") self._settings.set_int("/persistent/app/viewport/displayOptions", 0) # Create test area await self.create_test_area(1024, 1024) window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE self._test_window = ui.Window( "Viewport", dockPreference=ui.DockPreference.DISABLED, flags=window_flags, width=1024, height=1024, position_x=0, position_y=0, ) # Override default background self._test_window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}}) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._golden_img_dir = None for notification in self._all_notifications: notification.dismiss() self._all_notifications.clear() # Wait for 1s to make sure all notifications are disappeared. await asyncio.sleep(1) self._test_window = None self._settings.set_int("/persistent/app/viewport/displayOptions", self._original_value) await super().tearDown() async def _wait(self, frames=10): for i in range(frames): await omni.kit.app.get_app().next_update_async() async def test_create_multiple_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=2)) self._all_notifications.append(nm.post_notification("test1", duration=2, status=nm.NotificationStatus.WARNING)) self._all_notifications.append(nm.post_notification("test2", duration=2)) await self._wait() await asyncio.sleep(1.0) # Wait 10 frames for notifications to show up. await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_create_multiple_notifications.png") async def test_auto_hide_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=0.5)) await self._wait() # Watis for 2s for notification to hide await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_auto_hide_notifications.png") async def test_multiple_auto_hide_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=0.5)) self._all_notifications.append(nm.post_notification("test1", duration=0.5)) self._all_notifications.append(nm.post_notification("test2", duration=0.5)) await self._wait() # Watis for 2s for notification to hide await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_multiple_auto_hide_notifications.png") async def test_create_non_auto_hide_notifications(self): self._all_notifications.append(nm.post_notification("test", duration=0.5, hide_after_timeout=False)) await self._wait() # Watis for 2s for notification and check if it's still shown. await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_non_auto_hide_notifications.png") async def test_manual_hide_notifications(self): for i in range(100): self._all_notifications.append(nm.post_notification("test", duration=1)) # Wait and show await self._wait() await asyncio.sleep(2) # Dismiss them manually, after this, all notifications will be dismissed for n in self._all_notifications: n.dismiss() self._all_notifications.clear() # Creates another notification and shows it should work. self._all_notifications.append(nm.post_notification("test100", duration=10)) await self._wait() await asyncio.sleep(2) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_manual_hide_notifications.png") async def test_multithreads_post(self): def run(): nm.post_notification("test multiple threads") t = Thread(target=run) try: t.start() # 2s is enough to show notification await asyncio.sleep(2.0) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_multithreads_post.png") except: pass finally: t.join()
5,253
Python
41.032
130
0.655245
omniverse-code/kit/exts/omni.kit.notification_manager/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.5] - 2022-12-13 ### Changed - Fix dismissed state check for notification. ## [1.0.4] - 2022-03-11 ### Changed - Fix issue when notifications are posted through non-main threads. ## [1.0.3] - 2022-02-16 ### Changed - Add unittests. ## [1.0.2] - 2022-02-08 ### Changed - Fix issue that non-auto-hide notifications will re-appear after resizing viewport. ## [1.0.1] - 2022-01-14 ### Added - Improve notification manager to support stacking notifications. ## [1.0.0] - 2021-02-21 ### Added - Initial version.
613
Markdown
20.928571
84
0.676998
omniverse-code/kit/exts/omni.kit.notification_manager/docs/README.md
# omni.kit.notification_manager ## Introduction This extension provides simple interface to post notifications. ## Example >>> import omni.kit.notification_manager as nm >>> >>> ok_button = nm.NotificationButtonInfo("OK", on_complete=None) >>> cancel_button = nm.NotificationButtonInfo("CANCEL", on_complete=None) >>> notification_info = nm.post_notification( "Notification Example", hide_after_timeout=False, duration=0, status=nm.NotificationStatus.WARNING, button_infos=[ok_button, cancel_button])
584
Markdown
37.999997
98
0.662671
omniverse-code/kit/exts/omni.kit.notification_manager/docs/index.rst
omni.kit.notification_manager: Notification Manager Extension ############################################################## .. toctree:: :maxdepth: 1 CHANGELOG Notification Manager ========================== .. automodule:: omni.kit.notification_manager :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: partial
418
reStructuredText
22.277777
62
0.559809
omniverse-code/kit/exts/omni.usd.schema.omnigraph/pxr/OmniGraphSchema/__init__.py
# # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _omniGraphSchema from pxr import Tf Tf.PrepareModule(_omniGraphSchema, locals()) del Tf try: from . import __DOC __DOC.Execute(locals()) del __DOC except Exception: pass
1,510
Python
32.577777
100
0.733775
omniverse-code/kit/exts/omni.usd.schema.omnigraph/pxr/OmniGraphSchema/_omniGraphSchema.pyi
from __future__ import annotations import pxr.OmniGraphSchema._omniGraphSchema import typing import Boost.Python import pxr.OmniGraphSchema import pxr.Usd __all__ = [ "CompoundNodeAPI", "OmniGraph", "OmniGraphAPI", "OmniGraphCompoundNodeType", "OmniGraphNode", "OmniGraphNodeType", "Tokens" ] class CompoundNodeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateCompoundGraphRel(*args, **kwargs) -> None: ... @staticmethod def CreateCompoundTypeAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetCompoundGraphRel(*args, **kwargs) -> None: ... @staticmethod def GetCompoundTypeAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniGraph(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateEvaluationModeAttr(*args, **kwargs) -> None: ... @staticmethod def CreateEvaluatorTypeAttr(*args, **kwargs) -> None: ... @staticmethod def CreateFabricCacheBackingAttr(*args, **kwargs) -> None: ... @staticmethod def CreateFileFormatVersionAttr(*args, **kwargs) -> None: ... @staticmethod def CreatePipelineStageAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetEvaluationModeAttr(*args, **kwargs) -> None: ... @staticmethod def GetEvaluatorTypeAttr(*args, **kwargs) -> None: ... @staticmethod def GetFabricCacheBackingAttr(*args, **kwargs) -> None: ... @staticmethod def GetFileFormatVersionAttr(*args, **kwargs) -> None: ... @staticmethod def GetPipelineStageAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniGraphAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateOmniGraphsRel(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetOmniGraphsRel(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniGraphCompoundNodeType(OmniGraphNodeType, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateOmniGraphAssetRel(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetOmniGraphAssetRel(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniGraphNode(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateNodeTypeAttr(*args, **kwargs) -> None: ... @staticmethod def CreateNodeTypeVersionAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetNodeTypeAttr(*args, **kwargs) -> None: ... @staticmethod def GetNodeTypeVersionAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniGraphNodeType(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateOmniGraphCategoriesAttr(*args, **kwargs) -> None: ... @staticmethod def CreateOmniGraphDescriptionAttr(*args, **kwargs) -> None: ... @staticmethod def CreateOmniGraphNamespaceAttr(*args, **kwargs) -> None: ... @staticmethod def CreateOmniGraphTagsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateOmniGraphUiNameAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetOmniGraphCategoriesAttr(*args, **kwargs) -> None: ... @staticmethod def GetOmniGraphDescriptionAttr(*args, **kwargs) -> None: ... @staticmethod def GetOmniGraphNamespaceAttr(*args, **kwargs) -> None: ... @staticmethod def GetOmniGraphTagsAttr(*args, **kwargs) -> None: ... @staticmethod def GetOmniGraphUiNameAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class Tokens(Boost.Python.instance): automatic = 'Automatic' dirty_push = 'dirty_push' evaluationMode = 'evaluationMode' evaluatorType = 'evaluator:type' execution = 'execution' execution_pull = 'execution_pull' fabricCacheBacking = 'fabricCacheBacking' fileFormatVersion = 'fileFormatVersion' function = 'function' instanced = 'Instanced' localNodes = 'local.nodes' nodeType = 'node:type' nodeTypeVersion = 'node:typeVersion' nodetype = 'nodetype' omniGraphAsset = 'omni:graph:asset' omniGraphCategories = 'omni:graph:categories' omniGraphCompoundGraph = 'omni:graph:compoundGraph' omniGraphCompoundType = 'omni:graph:compoundType' omniGraphDescription = 'omni:graph:description' omniGraphNamespace = 'omni:graph:namespace' omniGraphTags = 'omni:graph:tags' omniGraphUiName = 'omni:graph:uiName' omniGraphs = 'omniGraphs' pipelineStage = 'pipelineStage' pipelineStageOnDemand = 'pipelineStageOnDemand' pipelineStagePostRender = 'pipelineStagePostRender' pipelineStagePreRender = 'pipelineStagePreRender' pipelineStageSimulation = 'pipelineStageSimulation' pull = 'pull' push = 'push' shared = 'Shared' stageWithHistory = 'StageWithHistory' stageWithoutHistory = 'StageWithoutHistory' standalone = 'Standalone' subgraph = 'subgraph' pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'omniGraphSchema'
6,933
unknown
34.197969
109
0.657724
omniverse-code/kit/exts/omni.usd.schema.omnigraph/pxr/OmniGraphSchemaTools/__init__.py
# #==== # Copyright (c) 2020, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _omniGraphSchemaTools from pxr import Tf Tf.PrepareModule(_omniGraphSchemaTools, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
1,681
Python
28.508771
100
0.710291
omniverse-code/kit/exts/omni.usd.schema.omnigraph/pxr/OmniGraphSchemaTools/_omniGraphSchemaTools.pyi
from __future__ import annotations import pxr.OmniGraphSchemaTools._omniGraphSchemaTools import typing __all__ = [ "applyOmniGraphAPI", "removeOmniGraphAPI" ] def applyOmniGraphAPI(*args, **kwargs) -> None: pass def removeOmniGraphAPI(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'omniGraphSchemaTools'
334
unknown
19.937499
53
0.721557
omniverse-code/kit/exts/omni.kit.welcome.learn/omni/kit/welcome/learn/style.py
from pathlib import Path import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") LEARN_PAGE_STYLE = {}
246
Python
21.454544
70
0.752033
omniverse-code/kit/exts/omni.kit.welcome.learn/omni/kit/welcome/learn/extension.py
import webbrowser import carb.settings import carb.tokens import omni.client import omni.ext import omni.ui as ui from omni.kit.documentation.builder import DocumentationBuilderMd, DocumentationBuilderPage from omni.kit.documentation.builder import get_style as get_doc_style from omni.kit.welcome.window import register_page from omni.ui import constant as fl from .style import ICON_PATH, LEARN_PAGE_STYLE _extension_instance = None class LearnPageExtension(omni.ext.IExt): def on_startup(self, ext_id): self.__ext_name = omni.ext.get_extension_name(ext_id) register_page(self.__ext_name, self.build_ui) self.__settings = carb.settings.get_settings() url = self.__settings.get(f"/exts/{self.__ext_name}/url") self._url = carb.tokens.get_tokens_interface().resolve(url) def on_shutdown(self): global _extension_instance _extension_instance = None def build_ui(self) -> None: with ui.ZStack(style=LEARN_PAGE_STYLE): # Background ui.Rectangle(style_type_name_override="Content") with ui.VStack(): with ui.VStack(height=fl._find("welcome_page_title_height")): ui.Spacer() with ui.HStack(): ui.Spacer() ui.Button( text="VIEW ON THE WEB", image_url=f"{ICON_PATH}/external_link.svg", width=0, spacing=10, clicked_fn=self.__view_on_web, style_type_name_override="Title.Button" ) ui.Spacer() ui.Spacer() with ui.HStack(): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.ZStack(style=get_doc_style()): ui.Rectangle(style_type_name_override="Doc.Background") DocumentationBuilderPage(DocumentationBuilderMd(self._url)) ui.Spacer(width=fl._find("welcome_content_padding_x")) ui.Spacer(height=fl._find("welcome_content_padding_y")) def __view_on_web(self): web_url = self.__settings.get(f"/exts/{self.__ext_name}/web_url") if not web_url: web_url = self._url webbrowser.open(web_url)
2,403
Python
36.562499
91
0.565959
omniverse-code/kit/exts/omni.kit.welcome.learn/omni/kit/welcome/learn/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
omniverse-code/kit/exts/omni.kit.welcome.learn/omni/kit/welcome/learn/tests/test_page.py
import asyncio from pathlib import Path import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from ..extension import LearnPageExtension CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") class TestPage(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() # After running each test async def tearDown(self): await super().tearDown() async def test_page(self): window = await self.create_test_window(width=800, height=300) with window.frame: ext = LearnPageExtension() ext.on_startup("omni.kit.welcome.learn-1.1.0") ext.build_ui() await omni.kit.app.get_app().next_update_async() # Wait for icons loaded await asyncio.sleep(3) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="page.png")
1,067
Python
29.514285
99
0.668229
omniverse-code/kit/exts/omni.kit.welcome.learn/omni/kit/welcome/learn/tests/__init__.py
from .test_page import *
24
Python
23.999976
24
0.75
omniverse-code/kit/exts/omni.kit.welcome.learn/docs/index.rst
omni.kit.welcome.learn ########################### .. toctree:: :maxdepth: 1 CHANGELOG
95
reStructuredText
10.999999
27
0.463158
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/__init__.py
from .profile_python import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/profile_python.py
"""Enable automatic profiling of the python code using sys.profile.""" import sys import omni.kit.app import omni.ext import carb import carb.profiler import carb.dictionary import carb.settings _profiler_enabled = False _profile_zone_counter = 0 _python_stack_level = 0 MAX_STACK_LEVEL = 10 EXT_SETTINGS_SECTION = "/exts/omni.kit.profile_python" def set_profiler_enabled(value: bool): global _profile_zone_counter global _python_stack_level global _profiler_enabled global MAX_STACK_LEVEL if value == _profiler_enabled: return MAX_STACK_LEVEL = carb.settings.get_settings().get(EXT_SETTINGS_SECTION + "/maxStackLevel") if value: def profile_calls(frame, event, arg): global _profile_zone_counter global _python_stack_level if event == "call": _python_stack_level += 1 if _python_stack_level > MAX_STACK_LEVEL: return co = frame.f_code filename = co.co_filename if filename[-25:] == r"carb\profiler\__init__.py" or filename[-25:] == "carb/profiler/__init__.py": # Do not profile profiler events return func_name = co.co_name line_no = frame.f_lineno carb.profiler.begin_with_location(1, "Py::" + func_name, func_name, filename, line_no) _profile_zone_counter += 1 return profile_calls elif event == "return": _python_stack_level -= 1 if _python_stack_level >= MAX_STACK_LEVEL: return if _profile_zone_counter == 0: return carb.profiler.end(1) _profile_zone_counter -= 1 return profile_calls _profile_zone_counter = 0 sys.setprofile(profile_calls) else: while _profile_zone_counter > 0: carb.profiler.end(1) _profile_zone_counter -= 1 sys.setprofile(None) _profiler_enabled = value class ProfilePython(omni.ext.IExt): def _on_enable_change(self, item: carb.dictionary.Item, change_event_type: carb.settings.ChangeEventType): self._enabled = self._settings.get(EXT_SETTINGS_SECTION + "/enable") set_profiler_enabled(self._enabled) def on_startup(self): self._dictionary = carb.dictionary.acquire_dictionary_interface() self._settings = carb.settings.get_settings() self._change_subs = self._settings.subscribe_to_node_change_events( EXT_SETTINGS_SECTION + "/enable", self._on_enable_change ) self._enabled = self._settings.get(EXT_SETTINGS_SECTION + "/enable") set_profiler_enabled(self._enabled) def on_shutdown(self): self._settings.unsubscribe_to_change_events(self._change_subs) self._enabled = False set_profiler_enabled(self._enabled) self._change_subs = None self._settings = None self._dictionary = None
3,081
Python
30.131313
115
0.590393
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/tests/__init__.py
from .test_profile_python import *
35
Python
16.999992
34
0.771429
omniverse-code/kit/exts/omni.kit.profile_python/omni/kit/profile_python/tests/test_profile_python.py
import omni.kit.test import gzip import json import os from omni.kit.core.tests import KitLaunchTest PYTHON_EVENT_PREFIX = "Py::" class TestProfilePython(KitLaunchTest): async def test_profile_python(self): FUNC_1 = "some_rare_magical_function_27026930" FUNC_2 = "another_rare_magical_function_120941920" # Call some functions script = f""" def {FUNC_2}(): pass def {FUNC_1}(): {FUNC_2}() {FUNC_1}() """ args = [ # "--/app/quitAfter=10" "--enable", "omni.kit.profile_python", ] trace_file = f"{self._temp_folder}/trace.gz" args += [ "--/plugins/carb.profiler-cpu.plugin/saveProfile=1", "--/plugins/carb.profiler-cpu.plugin/compressProfile=1", "--/app/profileFromStart=1", f"--/plugins/carb.profiler-cpu.plugin/filePath='{trace_file}'", ] # run kit with python profiler and this script await self._run_kit_with_script(script, args=args) self.assertTrue(os.path.exists(trace_file)) # Parse trace and check that they have those functions at least mentioned there events = set() with gzip.open(trace_file, 'rb') as f_in: j = json.loads(f_in.read().decode("utf-8") ) for entry in j: name = entry["name"] if name.startswith(PYTHON_EVENT_PREFIX): events.add(name) self.assertTrue(PYTHON_EVENT_PREFIX + FUNC_1 in events) self.assertTrue(PYTHON_EVENT_PREFIX + FUNC_2 in events)
1,600
Python
26.135593
87
0.5775
omniverse-code/kit/exts/omni.kit.profile_python/docs/index.rst
omni.kit.profile_python ########################### Small extension rigging python sys.profile functionality to use carb.profiler
132
reStructuredText
21.166663
77
0.659091
omniverse-code/kit/exts/omni.kit.collaboration.telemetry/omni/kit/collaboration/telemetry/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """ Provides access to a bindings module to simplify emitting telemetry events for the 'omni.kit.collaboration.*' extensions. """ import omni.core # pragma: no cover from ._telemetry import * # pragma: no cover
658
Python
42.93333
86
0.767477
omniverse-code/kit/exts/omni.kit.collaboration.telemetry/omni/kit/collaboration/telemetry/_telemetry.pyi
"""bindings for structured log schema omni.kit.collaboration""" from __future__ import annotations import omni.kit.collaboration.telemetry._telemetry import typing __all__ = [ "Schema_omni_kit_collaboration_1_0", "Struct_liveEdit_liveEdit" ] class Schema_omni_kit_collaboration_1_0(): def __init__(self) -> None: ... def liveEdit_sendEvent(self, cloud_link_id: str, liveEdit: Struct_liveEdit_liveEdit) -> None: ... pass class Struct_liveEdit_liveEdit(): def __init__(self) -> None: ... @property def action(self) -> str: """ :type: str """ @action.setter def action(self, arg0: str) -> None: pass @property def id(self) -> str: """ :type: str """ @id.setter def id(self, arg0: str) -> None: pass pass
828
unknown
22.685714
101
0.586957
omniverse-code/kit/exts/omni.kit.collaboration.telemetry/omni/kit/collaboration/telemetry/tests/test_telemetry.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.kit.test import omni.kit.test.teamcity import omni.structuredlog import carb.settings import tempfile import pathlib import time import io import os import sys import json import datetime import psutil import carb import carb.tokens import omni.kit.collaboration.telemetry class TestCollaborationTelemetry(omni.kit.test.AsyncTestCase): # pragma: no cover def setUp(self): self._structured_log_settings = omni.structuredlog.IStructuredLogSettings() self._control = omni.structuredlog.IStructuredLogControl() self._settings = carb.settings.get_settings_interface() self.assertIsNotNone(self._control) self.assertIsNotNone(self._settings) self.assertIsNotNone(self._structured_log_settings) # failed to retrieve the IStructuredLogSettings object => fail if self._structured_log_settings == None or self._control == None or self._settings == None: return # make sure to flush the structured log queue now since we're going to be changing the # log output path and default log name for this test. This will ensure that any pending # events are flushed to their appropriate log files first. self._control.stop() # set the log directory and name. self._temp_dir = tempfile.TemporaryDirectory() self._log_file_name = "omni.kit.collaboration.test.log" self._old_log_name = self._structured_log_settings.log_default_name self._old_log_path = self._structured_log_settings.log_output_path self._structured_log_settings.log_default_name = self._log_file_name self._structured_log_settings.log_output_path = self._temp_dir.name # piece together the expected name of the log file we'll be watching. self._log_path = pathlib.Path(self._temp_dir.name).joinpath(self._log_file_name) self.assertEqual(pathlib.Path(self._structured_log_settings.log_default_name), self._log_path) self.assertEqual(pathlib.Path(self._structured_log_settings.log_output_path), pathlib.Path(self._temp_dir.name)) def tearDown(self): # nothing to clean up => fail. if self._structured_log_settings == None: return; self._structured_log_settings.log_output_path = self._old_log_path self._structured_log_settings.log_default_name = self._old_log_name # explicitly clean up the temporary dir. Note that we need to explicitly clean it up # since it can throw an exception on Windows if a file or folder is still locked. The # support for internally ignoring these exceptions isn't added until `tempfile` v3.10 # and we're using an older version of the package here. try: self._temp_dir.cleanup() except: pass # explicitly clean up all of our objects so we're not relying on the python GC. self._structured_log_settings = None self._control = None self._settings = None self._temp_dir = None self._log_file_name = None self._old_log_name = None self._old_log_path = None self._log_path = None def _read_log_lines(self, filename, expected_types, session = None, time_delta = -1, log_time_range = 900): """ Reads the events from the expected log file location. Each log message line is parsed as a JSON blob. The 'data' property of each message is parsed into a dictionary and a list of these parsed dictionaries are returned. The log's header JSON object will also be parsed and verified. The verification includes checking that the log's creation timestamp is recent. Parameters: filename: The name of the log file to process for events. This may not be `None`. expected_types: A list of event type names that are to be expected in the log file. If an event is found that does not match one of the events in this list, a test will fail. session: An optional session ID string to match to each event. An event will only be included in the output if its session ID matches this one. This may be `None` or "0" to ignore the session ID matching. If this is set to "0", the session ID from each event will be added to each event in the output list so that further filtering can occur. time_delta: An optional time delta in seconds used to further filter events from the log file. Only events that were logged after a point that is this many seconds earlier than the call time will be included in the output. This may be negative to disable filtering out older events. log_time_range: The maximum number of seconds old that the log's creation timestamp in its header may be. This test may be disabled by settings this value to 0. If non-zero, this should be set to an absurd range versus the ideal case so that running on slow machines doesn't cause this test to unexpectedly fail. This defaults to 900s (15m). Returns: A list of parsed events. Each event in the list will be a dictionary of the properties parsed from that event's 'data' property. Note that each returned event in this list will have had its 'type' and 'session' properties copied into it under the property names 'cloudEventsEventType' and 'cloudEventsSessionId'. These can be used by the caller to further filter and categorize the events. """ if not os.path.isfile(filename): print("failed to find the log file '" + str(filename) + "'.") return [] events = [] lines = [] header = {} with open(filename, "r") as f: lines = f.readlines() if time_delta >= 0: timestamp = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(seconds = time_delta) # walk through all the lines in the file except the first one (the log header). for i in range(1, len(lines)): line = lines[i] try: event = json.loads(line) self.assertTrue(event["type"] in expected_types) msg_time = datetime.datetime.strptime(event["time"], "%Y-%m-%dT%H:%M:%S.%f%z") # always add the 'type' and 'session' properties to the output event. Since the # "type" and "session" property names are rather generic and could legitimately # be part of the "data" property, we'll rename them to something less generic # that the caller can consume. event["data"]["cloudEventsEventType"] = event["type"] event["data"]["cloudEventsSessionId"] = event["session"] if (session == None or session == "0" or event["session"] == session) and (time_delta < 0 or msg_time >= timestamp): events.append(event["data"]) except json.decoder.JSONDecodeError as e: print("failed to parse the line '" + line + "' as JSON {reason = '" + str(e) + "'}") pass except Exception as e: print("error processing the line '" + line + "' as JSON {error = '" + str(e) + "'}") raise # ****** parse and verify the header line ****** try: header = json.loads(lines[0]) except json.decoder.JSONDecodeError as e: print("failed to parse the header '" + lines[0] + "' as JSON {reason = '" + str(e) + "'}") self.assertFalse(True) except Exception as e: print("error processing the header '" + lines[0] + "' as JSON {error = '" + str(e) + "'}") self.assertFalse(True) self.assertEqual(header["source"], "omni.structuredlog") self.assertIsNotNone(header["version"]) # make sure the log was created recently. if log_time_range > 0: timestamp = datetime.datetime.strptime(header["time"], "%Y-%m-%dT%H:%M:%S.%f%z") time_diff = datetime.datetime.now(datetime.timezone.utc) - timestamp self.assertLess(time_diff.total_seconds(), log_time_range) return events def _is_event_present(self, events, properties): """ Verifies that all keys in `properties` both exist and have the same values in a single event in `events`. Parameters: events: The set of events that were read from the log file. These are expected to have been parsed into dictionary objects from the original JSON 'data' property of each event. properties: The set of properties to verify are present and match at least one of the events in the log. All properties must match to a single event in order for this to succeed. Returns: `True` if all the requested keys match in a single event. `False` if no event containing all properties is found. """ # go through each event in the log file and check if it has all the required properties. for i in range(len(events)): event = events[i] matches = True # go through each of the required properties and verify they are all present and # have the expected value. for key, value in properties.items(): if not key in event: continue if event[key] != value: matches = False break if matches: return True return False def test_live_edit_events(self): """ Tests sending Schema_omni_kit_collaboration_1_0 events. Note that since this extension is purely a bindings module, no coverage information will be generated unfortunately. This does however test the functionality of the bindings module. """ # get the schema object and create the data object that is required to send the event. self._telemetry = omni.kit.collaboration.telemetry.Schema_omni_kit_collaboration_1_0() event = omni.kit.collaboration.telemetry.Struct_liveEdit_liveEdit() self.assertIsNotNone(self._telemetry) self.assertIsNotNone(event) # send some test events. event.id = "purple monkey dishwasher" event.action = "join" self._telemetry.liveEdit_sendEvent("fudgesicle", event) event.id = "spatula lampshade" event.action = "leave" self._telemetry.liveEdit_sendEvent("peanut butter parfait", event) # make sure all the messages are flushed to disk. self._control.stop() # read the log and verify that all the expected messages are present. events = self._read_log_lines(self._log_path, [ "com.nvidia.omni.kit.collaboration.liveEdit", ]) # verify the ordered parameters events. self.assertTrue(self._is_event_present(events, {"cloud_link_id" : "fudgesicle", "event" : { "id": "purple monkey dishwasher", "action": "join"}, "event": "live-edit"})) self.assertTrue(self._is_event_present(events, {"cloud_link_id" : "peanut butter parfait", "event" : { "id": "spatula lampshade", "action": "leave"}, "event": "live-edit"})) # clean up. self._telemetry = None event = None
12,372
Python
46.588461
181
0.613644
omniverse-code/kit/exts/omni.kit.collaboration.telemetry/omni/kit/collaboration/telemetry/tests/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from .test_telemetry import * # pragma: no cover
475
Python
51.888883
76
0.804211
omniverse-code/kit/exts/omni.graph.ui/PACKAGE-LICENSES/prettycons-LICENSE.md
# prettycons License Icons made by prettycons from "https://www.flaticon.com/"
79
Markdown
25.666658
57
0.772152
omniverse-code/kit/exts/omni.graph.ui/PACKAGE-LICENSES/omni.graph.ui-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.ui/PACKAGE-LICENSES/Pixel_perfect-LICENSE.md
# PixelPerfect License Icons made by Pixel perfect from "https://www.flaticon.com/"
84
Markdown
27.333324
60
0.77381
omniverse-code/kit/exts/omni.graph.ui/config/extension.toml
[package] title = "OmniGraph UI" version = "1.24.2" category = "Graph" feature = true readme = "docs/README.md" changelog = "docs/CHANGELOG.md" description = "Contains all of the UI specific to the OmniGraph." preview_image = "data/preview.png" repository = "" keywords = ["kit", "omnigraph", "ui", "editor"] # The location of this module's python scripts [[python.module]] name = "omni.graph.ui" [[native.plugin]] path = "bin/*.plugin" recursive = false # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] # In addition to using the OmniGraph code the editor functionality is used for the node description editor [dependencies] "omni.debugdraw" = {} "omni.graph" = {} "omni.graph.tools" = {} "omni.inspect" = {} "omni.kit.commands" = {} "omni.kit.widget.prompt" = {} "omni.kit.widget.settings" = {} "omni.kit.widget.text_editor" = {} # For use in node template UI "omni.kit.widget.stage" = {optional = true} "omni.kit.window.filepicker" = {} "omni.kit.viewport.utility" = {} "omni.ui" = {} "omni.ui.scene" = {} "omni.ui_query" = {} "omni.usd" = {} "omni.kit.pip_archive" = {} "omni.kit.window.property" = {} "omni.kit.property.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.window.preferences" = {} "omni.kit.window.extensions" = {} "omni.kit.stage_templates" = {} "omni.timeline" = {} [[test]] # RTX regression OM-51983 timeout = 600 args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", ] dependencies = [ "omni.graph.action", "omni.graph.nodes", "omni.hydra.pxr", "omni.kit.window.viewport", "omni.kit.ui_test", ] [documentation] pages = [ "docs/Overview.md", "docs/OmniGraphNodeDescriptionEditor.rst", "docs/OmniGraphSettingsEditor.rst", "docs/Pixel_perfect-LICENSE.md", "docs/prettycons-LICENSE.md", "docs/CHANGELOG.md", ]
2,108
TOML
25.037037
106
0.663188
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/__init__.py
"""Initialization for the OmniGraph UI extension""" # Required for proper resolution of ONI wrappers import omni.core from ._impl.compute_node_widget import ComputeNodeWidget from ._impl.extension import _PublicExtension from ._impl.graph_variable_custom_layout import GraphVariableCustomLayout from ._impl.menu import add_create_menu_type, remove_create_menu_type from ._impl.omnigraph_attribute_base import OmniGraphBase from ._impl.omnigraph_attribute_builder import OmniGraphPropertiesWidgetBuilder from ._impl.omnigraph_attribute_models import OmniGraphAttributeModel, OmniGraphTfTokenAttributeModel from ._impl.omnigraph_prim_node_templates import ( PrimAttributeCustomLayoutBase, PrimPathCustomLayoutBase, ReadPrimsCustomLayoutBase, ) from ._impl.omnigraph_random_node_templates import RandomNodeCustomLayoutBase from ._impl.omnigraph_settings_editor import SETTING_PAGE_NAME from ._impl.utils import build_port_type_convert_menu, find_prop __all__ = [ "add_create_menu_type", "build_port_type_convert_menu", "ComputeNodeWidget", "find_prop", "GraphVariableCustomLayout", "OmniGraphAttributeModel", "OmniGraphBase", "OmniGraphPropertiesWidgetBuilder", "OmniGraphTfTokenAttributeModel", "PrimAttributeCustomLayoutBase", "PrimPathCustomLayoutBase", "RandomNodeCustomLayoutBase", "ReadPrimsCustomLayoutBase", "remove_create_menu_type", "SETTING_PAGE_NAME", ]
1,437
Python
36.842104
101
0.78636
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadViewportPressStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadViewportPressState Read the state of the last viewport press event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnReadViewportPressStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadViewportPressState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isPressed outputs.isReleasePositionValid outputs.isValid outputs.pressPosition outputs.releasePosition Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport press events', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Press", "RightMouseDrag": "Right Mouse Press", "MiddleMouseDrag": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Press"'}, True, 'Left Mouse Press', False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for press events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isPressed', 'bool', 0, 'Is Pressed', 'True if the specified viewport is currently pressed', {}, True, None, False, ''), ('outputs:isReleasePositionValid', 'bool', 0, 'Is Release Position Valid', 'True if the press was released inside of the viewport, and false otherwise', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:pressPosition', 'double2', 0, 'Press Position', 'The position at which the specified viewport was last pressed', {}, True, None, False, ''), ('outputs:releasePosition', 'double2', 0, 'Release Position', 'The position at which the last press on the specified viewport was released,\nor (0,0) if the press was released outside of the viewport or the viewport is currently pressed', {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Press" RightMouseDrag = "Right Mouse Press" MiddleMouseDrag = "Middle Mouse Press" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Press", False, "Viewport"] @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def useNormalizedCoords(self): return self._batchedReadValues[1] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isPressed", "isReleasePositionValid", "isValid", "pressPosition", "releasePosition", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isPressed(self): value = self._batchedWriteValues.get(self._attributes.isPressed) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): self._batchedWriteValues[self._attributes.isPressed] = value @property def isReleasePositionValid(self): value = self._batchedWriteValues.get(self._attributes.isReleasePositionValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) return data_view.get() @isReleasePositionValid.setter def isReleasePositionValid(self, value): self._batchedWriteValues[self._attributes.isReleasePositionValid] = value @property def isValid(self): value = self._batchedWriteValues.get(self._attributes.isValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): self._batchedWriteValues[self._attributes.isValid] = value @property def pressPosition(self): value = self._batchedWriteValues.get(self._attributes.pressPosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pressPosition) return data_view.get() @pressPosition.setter def pressPosition(self, value): self._batchedWriteValues[self._attributes.pressPosition] = value @property def releasePosition(self): value = self._batchedWriteValues.get(self._attributes.releasePosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.releasePosition) return data_view.get() @releasePosition.setter def releasePosition(self, value): self._batchedWriteValues[self._attributes.releasePosition] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadViewportPressStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportPressStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportPressStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,738
Python
50.382775
469
0.651704
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnGetCameraTargetDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.GetCameraTarget Gets a viewport camera's target point. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import carb import numpy class OgnGetCameraTargetDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.GetCameraTarget Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.prim inputs.primPath inputs.usePath Outputs: outputs.target """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:prim', 'bundle', 0, None, "The camera prim, when 'usePath' is false", {}, False, None, False, ''), ('inputs:primPath', 'token', 0, 'Camera Path', "Path of the camera, used when 'usePath' is true", {}, True, '', False, ''), ('inputs:usePath', 'bool', 0, None, "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:target', 'point3d', 0, 'Target', 'The target point', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.prim = og.Database.ROLE_BUNDLE role_data.outputs.target = og.Database.ROLE_POINT return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"primPath", "usePath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.primPath, self._attributes.usePath] self._batchedReadValues = ["", True] @property def prim(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.prim""" return self.__bundles.prim @property def primPath(self): return self._batchedReadValues[0] @primPath.setter def primPath(self, value): self._batchedReadValues[0] = value @property def usePath(self): return self._batchedReadValues[1] @usePath.setter def usePath(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"target", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def target(self): value = self._batchedWriteValues.get(self._attributes.target) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.target) return data_view.get() @target.setter def target(self, value): self._batchedWriteValues[self._attributes.target] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnGetCameraTargetDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGetCameraTargetDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGetCameraTargetDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,089
Python
47.896551
248
0.640429
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnViewportHoveredDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnViewportHovered Event node which fires when the specified viewport is hovered over. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnOnViewportHoveredDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnViewportHovered Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.onlyPlayback inputs.viewport Outputs: outputs.began outputs.ended """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for hover events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:began', 'execution', 0, 'Began', 'Enabled when the hover begins', {}, True, None, False, ''), ('outputs:ended', 'execution', 0, 'Ended', 'Enabled when the hover ends', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.began = og.Database.ROLE_EXECUTION role_data.outputs.ended = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"onlyPlayback", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.onlyPlayback, self._attributes.viewport] self._batchedReadValues = [True, "Viewport"] @property def onlyPlayback(self): return self._batchedReadValues[0] @onlyPlayback.setter def onlyPlayback(self, value): self._batchedReadValues[0] = value @property def viewport(self): return self._batchedReadValues[1] @viewport.setter def viewport(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"began", "ended", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def began(self): value = self._batchedWriteValues.get(self._attributes.began) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.began) return data_view.get() @began.setter def began(self, value): self._batchedWriteValues[self._attributes.began] = value @property def ended(self): value = self._batchedWriteValues.get(self._attributes.ended) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.ended) return data_view.get() @ended.setter def ended(self, value): self._batchedWriteValues[self._attributes.ended] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportHoveredDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportHoveredDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportHoveredDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,465
Python
48.443708
231
0.644072
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnViewportPressedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnViewportPressed Event node which fires when the specified viewport is pressed, and when that press is released. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnOnViewportPressedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnViewportPressed Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isReleasePositionValid outputs.pressPosition outputs.pressed outputs.releasePosition outputs.released Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport press events', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Press", "RightMouseDrag": "Right Mouse Press", "MiddleMouseDrag": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Press"'}, True, 'Left Mouse Press', False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for press events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isReleasePositionValid', 'bool', 0, 'Is Release Position Valid', 'True if the press was released inside of the viewport, and false otherwise', {}, True, None, False, ''), ('outputs:pressPosition', 'double2', 0, 'Press Position', "The position at which the viewport was pressed (valid when either 'Pressed' or 'Released' is enabled)", {}, True, None, False, ''), ('outputs:pressed', 'execution', 0, 'Pressed', "Enabled when the specified viewport is pressed, populating 'Press Position' with the current mouse position", {}, True, None, False, ''), ('outputs:releasePosition', 'double2', 0, 'Release Position', "The position at which the press was released, or (0,0) if the press was released outside of the viewport\nor the viewport is currently pressed (valid when 'Ended' is enabled and 'Is Release Position Valid' is true)", {}, True, None, False, ''), ('outputs:released', 'execution', 0, 'Released', "Enabled when the press is released, populating 'Release Position' with the current mouse position\nand setting 'Is Release Position Valid' to true if the press is released inside of the viewport.\nIf the press is released outside of the viewport, 'Is Release Position Valid' is set to false\nand 'Release Position' is set to (0,0).", {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Press" RightMouseDrag = "Right Mouse Press" MiddleMouseDrag = "Middle Mouse Press" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.pressed = og.Database.ROLE_EXECUTION role_data.outputs.released = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "onlyPlayback", "useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.onlyPlayback, self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Press", True, False, "Viewport"] @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def onlyPlayback(self): return self._batchedReadValues[1] @onlyPlayback.setter def onlyPlayback(self, value): self._batchedReadValues[1] = value @property def useNormalizedCoords(self): return self._batchedReadValues[2] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[2] = value @property def viewport(self): return self._batchedReadValues[3] @viewport.setter def viewport(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isReleasePositionValid", "pressPosition", "pressed", "releasePosition", "released", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isReleasePositionValid(self): value = self._batchedWriteValues.get(self._attributes.isReleasePositionValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isReleasePositionValid) return data_view.get() @isReleasePositionValid.setter def isReleasePositionValid(self, value): self._batchedWriteValues[self._attributes.isReleasePositionValid] = value @property def pressPosition(self): value = self._batchedWriteValues.get(self._attributes.pressPosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pressPosition) return data_view.get() @pressPosition.setter def pressPosition(self, value): self._batchedWriteValues[self._attributes.pressPosition] = value @property def pressed(self): value = self._batchedWriteValues.get(self._attributes.pressed) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pressed) return data_view.get() @pressed.setter def pressed(self, value): self._batchedWriteValues[self._attributes.pressed] = value @property def releasePosition(self): value = self._batchedWriteValues.get(self._attributes.releasePosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.releasePosition) return data_view.get() @releasePosition.setter def releasePosition(self, value): self._batchedWriteValues[self._attributes.releasePosition] = value @property def released(self): value = self._batchedWriteValues.get(self._attributes.released) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.released) return data_view.get() @released.setter def released(self, value): self._batchedWriteValues[self._attributes.released] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportPressedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportPressedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportPressedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
12,069
Python
52.407079
505
0.655812
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadPickStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadPickState Read the state of the last picking event from the specified viewport. Note that picking events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import carb import numpy class OgnReadPickStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadPickState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.trackedPrimPaths inputs.trackedPrims inputs.usePaths inputs.viewport Outputs: outputs.isTrackedPrimPicked outputs.isValid outputs.pickedPrimPath outputs.pickedWorldPos Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick tokens.LeftMousePress tokens.RightMousePress tokens.MiddleMousePress """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger a picking event', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click,Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click", "LeftMousePress": "Left Mouse Press", "RightMousePress": "Right Mouse Press", "MiddleMousePress": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, 'Left Mouse Click', False, ''), ('inputs:trackedPrimPaths', 'token[]', 0, 'Tracked Prim Paths', "Optionally specify a set of prims (by paths) to track whether or not they got picked\n(only affects the value of 'Is Tracked Prim Picked')", {}, False, None, False, ''), ('inputs:trackedPrims', 'bundle', 0, 'Tracked Prims', "Optionally specify a set of prims to track whether or not they got picked\n(only affects the value of 'Is Tracked Prim Picked')", {}, False, None, False, ''), ('inputs:usePaths', 'bool', 0, 'Use Paths', "When true, 'Tracked Prim Paths' is used, otherwise 'Tracked Prims' is used", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for picking events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isTrackedPrimPicked', 'bool', 0, 'Is Tracked Prim Picked', 'True if a tracked prim got picked in the last picking event,\nor if any prim got picked if no tracked prims are specified', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:pickedPrimPath', 'token', 0, 'Picked Prim Path', 'The path of the prim picked in the last picking event, or an empty string if nothing got picked', {}, True, None, False, ''), ('outputs:pickedWorldPos', 'point3d', 0, 'Picked World Position', 'The XYZ-coordinates of the point in world space at which the prim got picked,\nor (0,0,0) if nothing got picked', {}, True, None, False, ''), ]) class tokens: LeftMouseClick = "Left Mouse Click" RightMouseClick = "Right Mouse Click" MiddleMouseClick = "Middle Mouse Click" LeftMousePress = "Left Mouse Press" RightMousePress = "Right Mouse Press" MiddleMousePress = "Middle Mouse Press" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.trackedPrims = og.Database.ROLE_BUNDLE role_data.outputs.pickedWorldPos = og.Database.ROLE_POINT return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "usePaths", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.usePaths, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Click", False, "Viewport"] @property def trackedPrimPaths(self): data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) return data_view.get() @trackedPrimPaths.setter def trackedPrimPaths(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.trackedPrimPaths) data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) data_view.set(value) self.trackedPrimPaths_size = data_view.get_array_size() @property def trackedPrims(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.trackedPrims""" return self.__bundles.trackedPrims @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def usePaths(self): return self._batchedReadValues[1] @usePaths.setter def usePaths(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isTrackedPrimPicked", "isValid", "pickedPrimPath", "pickedWorldPos", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isTrackedPrimPicked(self): value = self._batchedWriteValues.get(self._attributes.isTrackedPrimPicked) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) return data_view.get() @isTrackedPrimPicked.setter def isTrackedPrimPicked(self, value): self._batchedWriteValues[self._attributes.isTrackedPrimPicked] = value @property def isValid(self): value = self._batchedWriteValues.get(self._attributes.isValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): self._batchedWriteValues[self._attributes.isValid] = value @property def pickedPrimPath(self): value = self._batchedWriteValues.get(self._attributes.pickedPrimPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) return data_view.get() @pickedPrimPath.setter def pickedPrimPath(self, value): self._batchedWriteValues[self._attributes.pickedPrimPath] = value @property def pickedWorldPos(self): value = self._batchedWriteValues.get(self._attributes.pickedWorldPos) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) return data_view.get() @pickedWorldPos.setter def pickedWorldPos(self, value): self._batchedWriteValues[self._attributes.pickedWorldPos] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadPickStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadPickStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadPickStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,988
Python
50.900433
640
0.650567
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadWidgetPropertyDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadWidgetProperty Read the value of a widget's property (height, tooltip, etc). """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn from typing import Any import traceback import sys class OgnReadWidgetPropertyDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadWidgetProperty Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.propertyName inputs.widgetIdentifier inputs.widgetPath Outputs: outputs.value """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:propertyName', 'token', 0, 'Property Name', 'Name of the property to read.', {}, True, '', False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'Unique identifier for the widget. This is only valid within the current graph.', {}, True, '', False, ''), ('inputs:widgetPath', 'token', 0, 'Widget Path', "Full path to the widget. If present this will be used insted of 'widgetIdentifier'.\nUnlike 'widgetIdentifier' this is valid across all graphs.", {}, True, '', False, ''), ('outputs:value', 'bool,double,int,string', 1, 'Value', 'The value of the property.', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"propertyName", "widgetIdentifier", "widgetPath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.propertyName, self._attributes.widgetIdentifier, self._attributes.widgetPath] self._batchedReadValues = ["", "", ""] @property def propertyName(self): return self._batchedReadValues[0] @propertyName.setter def propertyName(self, value): self._batchedReadValues[0] = value @property def widgetIdentifier(self): return self._batchedReadValues[1] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[1] = value @property def widgetPath(self): return self._batchedReadValues[2] @widgetPath.setter def widgetPath(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def value(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.value""" return og.RuntimeAttribute(self._attributes.value.get_attribute_data(), self._context, False) @value.setter def value(self, value_to_set: Any): """Assign another attribute's value to outputs.value""" if isinstance(value_to_set, og.RuntimeAttribute): self.value.value = value_to_set.value else: self.value.value = value_to_set 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 = OgnReadWidgetPropertyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadWidgetPropertyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadWidgetPropertyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.ReadWidgetProperty' @staticmethod def compute(context, node): try: per_node_data = OgnReadWidgetPropertyDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnReadWidgetPropertyDatabase(node) per_node_data['_db'] = db except: db = OgnReadWidgetPropertyDatabase(node) try: compute_function = getattr(OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnReadWidgetPropertyDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnReadWidgetPropertyDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Read Widget Property (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Read the value of a widget's property (height, tooltip, etc).") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.set_data_access(og.eAccessLocation.E_GLOBAL, og.eAccessType.E_WRITE) OgnReadWidgetPropertyDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnReadWidgetPropertyDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnReadWidgetPropertyDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.ReadWidgetProperty")
11,160
Python
51.399061
229
0.643817
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadWindowSizeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadWindowSize Outputs the size of a UI window. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import sys import traceback class OgnReadWindowSizeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadWindowSize Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.isViewport inputs.name inputs.widgetPath Outputs: outputs.height outputs.width """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:isViewport', 'bool', 0, 'Is Viewport?', 'If true then only viewport windows will be considered.', {ogn.MetadataKeys.DEFAULT: 'false'}, False, False, False, ''), ('inputs:name', 'token', 0, 'Name', 'Name of the window. If there are multiple windows with the same name\nthe first one found will be used.', {}, False, None, False, ''), ('inputs:widgetPath', 'token', 0, 'Widget Path', "Full path to a widget in the window. If specified then 'name' will be ignored and\nthe window containing the widget will be used.", {}, False, None, False, ''), ('outputs:height', 'float', 0, 'Height', 'Height of the window in pixels.', {}, True, None, False, ''), ('outputs:width', 'float', 0, 'Width', 'Width of the window in pixels.', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isViewport", "name", "widgetPath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.isViewport, self._attributes.name, self._attributes.widgetPath] self._batchedReadValues = [False, None, None] @property def isViewport(self): return self._batchedReadValues[0] @isViewport.setter def isViewport(self, value): self._batchedReadValues[0] = value @property def name(self): return self._batchedReadValues[1] @name.setter def name(self, value): self._batchedReadValues[1] = value @property def widgetPath(self): return self._batchedReadValues[2] @widgetPath.setter def widgetPath(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"height", "width", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def height(self): value = self._batchedWriteValues.get(self._attributes.height) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): self._batchedWriteValues[self._attributes.height] = value @property def width(self): value = self._batchedWriteValues.get(self._attributes.width) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): self._batchedWriteValues[self._attributes.width] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadWindowSizeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadWindowSizeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadWindowSizeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnReadWindowSizeDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.ReadWindowSize' @staticmethod def compute(context, node): try: per_node_data = OgnReadWindowSizeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnReadWindowSizeDatabase(node) per_node_data['_db'] = db except: db = OgnReadWindowSizeDatabase(node) try: compute_function = getattr(OgnReadWindowSizeDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnReadWindowSizeDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnReadWindowSizeDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnReadWindowSizeDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnReadWindowSizeDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnReadWindowSizeDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnReadWindowSizeDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnReadWindowSizeDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Read Window Size (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Outputs the size of a UI window.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.set_data_access(og.eAccessLocation.E_GLOBAL, og.eAccessType.E_READ) OgnReadWindowSizeDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnReadWindowSizeDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnReadWindowSizeDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnReadWindowSizeDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.ReadWindowSize")
11,841
Python
48.548117
218
0.627396
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnSetCameraTargetDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.SetCameraTarget Sets the camera's target """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy import carb class OgnSetCameraTargetDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.SetCameraTarget Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.prim inputs.primPath inputs.rotate inputs.target inputs.usePath Outputs: outputs.execOut """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''), ('inputs:prim', 'bundle', 0, None, "The camera prim, when 'usePath' is false", {}, False, None, False, ''), ('inputs:primPath', 'token', 0, 'Camera Path', "Path of the camera, used when 'usePath' is true", {}, True, '', False, ''), ('inputs:rotate', 'bool', 0, 'Rotate', 'True to keep position but change orientation and radius (camera rotates to look at new target).\nFalse to keep orientation and radius but change position (camera moves to look at new target).', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:target', 'point3d', 0, 'Target', 'The target point', {}, True, [0.0, 0.0, 0.0], False, ''), ('inputs:usePath', 'bool', 0, None, "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.Database.ROLE_EXECUTION role_data.inputs.prim = og.Database.ROLE_BUNDLE role_data.inputs.target = og.Database.ROLE_POINT role_data.outputs.execOut = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "primPath", "rotate", "target", "usePath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.primPath, self._attributes.rotate, self._attributes.target, self._attributes.usePath] self._batchedReadValues = [None, "", True, [0.0, 0.0, 0.0], True] @property def prim(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.prim""" return self.__bundles.prim @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def primPath(self): return self._batchedReadValues[1] @primPath.setter def primPath(self, value): self._batchedReadValues[1] = value @property def rotate(self): return self._batchedReadValues[2] @rotate.setter def rotate(self, value): self._batchedReadValues[2] = value @property def target(self): return self._batchedReadValues[3] @target.setter def target(self, value): self._batchedReadValues[3] = value @property def usePath(self): return self._batchedReadValues[4] @usePath.setter def usePath(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSetCameraTargetDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetCameraTargetDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetCameraTargetDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,509
Python
47.079096
301
0.6338
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnWriteWidgetPropertyDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.WriteWidgetProperty Set the value of a widget's property (height, tooltip, etc). """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn from typing import Any import sys import traceback class OgnWriteWidgetPropertyDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.WriteWidgetProperty Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.propertyName inputs.value inputs.widgetIdentifier inputs.widgetPath inputs.write Outputs: outputs.written """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:propertyName', 'token', 0, 'Property Name', 'Name of the property to write to.', {}, True, '', False, ''), ('inputs:value', 'any', 2, 'Value', 'The value to write to the property.', {}, True, None, False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'Unique identifier for the widget. This is only valid within the current graph.', {}, True, '', False, ''), ('inputs:widgetPath', 'token', 0, 'Widget Path', "Full path to the widget. If present this will be used insted of 'widgetIdentifier'.\nUnlike 'widgetIdentifier' this is valid across all graphs.", {}, True, '', False, ''), ('inputs:write', 'execution', 0, 'Write', "Input execution to write the value to the widget's property.", {}, True, None, False, ''), ('outputs:written', 'execution', 0, None, 'Executed when the value has been successfully written.', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.write = og.Database.ROLE_EXECUTION role_data.outputs.written = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"propertyName", "widgetIdentifier", "widgetPath", "write", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.propertyName, self._attributes.widgetIdentifier, self._attributes.widgetPath, self._attributes.write] self._batchedReadValues = ["", "", "", None] @property def value(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute inputs.value""" return og.RuntimeAttribute(self._attributes.value.get_attribute_data(), self._context, True) @value.setter def value(self, value_to_set: Any): """Assign another attribute's value to outputs.value""" if isinstance(value_to_set, og.RuntimeAttribute): self.value.value = value_to_set.value else: self.value.value = value_to_set @property def propertyName(self): return self._batchedReadValues[0] @propertyName.setter def propertyName(self, value): self._batchedReadValues[0] = value @property def widgetIdentifier(self): return self._batchedReadValues[1] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[1] = value @property def widgetPath(self): return self._batchedReadValues[2] @widgetPath.setter def widgetPath(self, value): self._batchedReadValues[2] = value @property def write(self): return self._batchedReadValues[3] @write.setter def write(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"written", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def written(self): value = self._batchedWriteValues.get(self._attributes.written) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.written) return data_view.get() @written.setter def written(self, value): self._batchedWriteValues[self._attributes.written] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnWriteWidgetPropertyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnWriteWidgetPropertyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnWriteWidgetPropertyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.WriteWidgetProperty' @staticmethod def compute(context, node): try: per_node_data = OgnWriteWidgetPropertyDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnWriteWidgetPropertyDatabase(node) per_node_data['_db'] = db except: db = OgnWriteWidgetPropertyDatabase(node) try: if db.inputs.value.type.base_type == og.BaseDataType.UNKNOWN: db.log_warning('Required extended attribute inputs:value is not resolved, compute skipped') return False compute_function = getattr(OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnWriteWidgetPropertyDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnWriteWidgetPropertyDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Write Widget Property (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Set the value of a widget's property (height, tooltip, etc).") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnWriteWidgetPropertyDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnWriteWidgetPropertyDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnWriteWidgetPropertyDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.WriteWidgetProperty")
13,016
Python
49.649805
229
0.635295
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnVStackDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.VStack Contruct a Stack on the Viewport. All child widgets of Stack will be placed in a row, column or layer based on the direction input. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys class OgnVStackDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.VStack Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.create inputs.direction inputs.parentWidgetPath inputs.style inputs.widgetIdentifier Outputs: outputs.created outputs.widgetPath Predefined Tokens: tokens.BACK_TO_FRONT tokens.BOTTOM_TO_TOP tokens.FRONT_TO_BACK tokens.LEFT_TO_RIGHT tokens.RIGHT_TO_LEFT tokens.TOP_TO_BOTTOM """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:create', 'execution', 0, 'Create', 'Input execution to create and show the widget', {}, True, None, False, ''), ('inputs:direction', 'token', 0, 'Direction', 'The direction the widgets will be stacked.', {ogn.MetadataKeys.ALLOWED_TOKENS: 'BACK_TO_FRONT,BOTTOM_TO_TOP,FRONT_TO_BACK,LEFT_TO_RIGHT,RIGHT_TO_LEFT,TOP_TO_BOTTOM', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"BACK_TO_FRONT": "BACK_TO_FRONT", "BOTTOM_TO_TOP": "BOTTOM_TO_TOP", "FRONT_TO_BACK": "FRONT_TO_BACK", "LEFT_TO_RIGHT": "LEFT_TO_RIGHT", "RIGHT_TO_LEFT": "RIGHT_TO_LEFT", "TOP_TO_BOTTOM": "TOP_TO_BOTTOM"}', ogn.MetadataKeys.DEFAULT: '"TOP_TO_BOTTOM"'}, True, 'TOP_TO_BOTTOM', False, ''), ('inputs:parentWidgetPath', 'token', 0, 'Parent Widget Path', 'The absolute path to the parent widget.', {}, True, '', False, ''), ('inputs:style', 'string', 0, None, 'Style to be applied to the stack and its children. This can later be changed with the\nWriteWidgetStyle node.', {}, False, None, False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'An optional unique identifier for the widget.\nCan be used to refer to this widget in other places such as the OnWidgetClicked node.', {}, False, None, False, ''), ('outputs:created', 'execution', 0, 'Created', 'Executed when the widget is created', {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', 'The absolute path to the created widget', {}, True, None, False, ''), ]) class tokens: BACK_TO_FRONT = "BACK_TO_FRONT" BOTTOM_TO_TOP = "BOTTOM_TO_TOP" FRONT_TO_BACK = "FRONT_TO_BACK" LEFT_TO_RIGHT = "LEFT_TO_RIGHT" RIGHT_TO_LEFT = "RIGHT_TO_LEFT" TOP_TO_BOTTOM = "TOP_TO_BOTTOM" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.create = og.Database.ROLE_EXECUTION role_data.outputs.created = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"create", "direction", "parentWidgetPath", "style", "widgetIdentifier", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.create, self._attributes.direction, self._attributes.parentWidgetPath, self._attributes.style, self._attributes.widgetIdentifier] self._batchedReadValues = [None, "TOP_TO_BOTTOM", "", None, None] @property def create(self): return self._batchedReadValues[0] @create.setter def create(self, value): self._batchedReadValues[0] = value @property def direction(self): return self._batchedReadValues[1] @direction.setter def direction(self, value): self._batchedReadValues[1] = value @property def parentWidgetPath(self): return self._batchedReadValues[2] @parentWidgetPath.setter def parentWidgetPath(self, value): self._batchedReadValues[2] = value @property def style(self): return self._batchedReadValues[3] @style.setter def style(self, value): self._batchedReadValues[3] = value @property def widgetIdentifier(self): return self._batchedReadValues[4] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"created", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def created(self): value = self._batchedWriteValues.get(self._attributes.created) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.created) return data_view.get() @created.setter def created(self, value): self._batchedWriteValues[self._attributes.created] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnVStackDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnVStackDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnVStackDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnVStackDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.VStack' @staticmethod def compute(context, node): try: per_node_data = OgnVStackDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnVStackDatabase(node) per_node_data['_db'] = db except: db = OgnVStackDatabase(node) try: compute_function = getattr(OgnVStackDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnVStackDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnVStackDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnVStackDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnVStackDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnVStackDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnVStackDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnVStackDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Stack (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Contruct a Stack on the Viewport. All child widgets of Stack will be placed in a row, column or layer based on the direction input.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnVStackDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnVStackDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnVStackDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnVStackDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.VStack")
13,809
Python
48.498208
546
0.629517
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnPrintTextDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.PrintText Prints some text to the system log or to the screen """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import sys import traceback class OgnPrintTextDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.PrintText Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.logLevel inputs.text inputs.toScreen inputs.viewport Outputs: outputs.execOut Predefined Tokens: tokens.Info tokens.Warning tokens.Error """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''), ('inputs:logLevel', 'token', 0, 'Log Level', 'The logging level for the message [Info, Warning, Error]', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Info,Warning,Error', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["Info", "Warning", "Error"]', ogn.MetadataKeys.DEFAULT: '"Info"'}, True, 'Info', False, ''), ('inputs:text', 'string', 0, 'Text', 'The text to print', {}, True, '', False, ''), ('inputs:toScreen', 'bool', 0, 'To Screen', 'When true, displays the text on the viewport for a few seconds, as well as the log', {}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport if printing to screen, or empty for the default viewport', {}, True, '', False, ''), ('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''), ]) class tokens: Info = "Info" Warning = "Warning" Error = "Error" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.Database.ROLE_EXECUTION role_data.outputs.execOut = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "logLevel", "text", "toScreen", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.logLevel, self._attributes.text, self._attributes.toScreen, self._attributes.viewport] self._batchedReadValues = [None, "Info", "", False, ""] @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def logLevel(self): return self._batchedReadValues[1] @logLevel.setter def logLevel(self, value): self._batchedReadValues[1] = value @property def text(self): return self._batchedReadValues[2] @text.setter def text(self, value): self._batchedReadValues[2] = value @property def toScreen(self): return self._batchedReadValues[3] @toScreen.setter def toScreen(self, value): self._batchedReadValues[3] = value @property def viewport(self): return self._batchedReadValues[4] @viewport.setter def viewport(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnPrintTextDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnPrintTextDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnPrintTextDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.PrintText' @staticmethod def compute(context, node): try: per_node_data = OgnPrintTextDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnPrintTextDatabase(node) per_node_data['_db'] = db except: db = OgnPrintTextDatabase(node) try: compute_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnPrintTextDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnPrintTextDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnPrintTextDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.TAGS, "logging,toast,debug") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Print Text") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "debug") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Prints some text to the system log or to the screen") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnPrintTextDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnPrintTextDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnPrintTextDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnPrintTextDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.PrintText")
12,404
Python
46.895753
300
0.623589
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnWidgetClickedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnWidgetClicked Event node which fires when a UI widget with the specified identifier is clicked. This node should be used in combination with UI creation nodes such as OgnButton. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys class OgnOnWidgetClickedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnWidgetClicked Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.widgetIdentifier Outputs: outputs.clicked """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'A unique identifier identifying the widget.\nThis should be specified in the UI creation node such as OgnButton.', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, '', False, ''), ('outputs:clicked', 'execution', 0, 'Clicked', 'Executed when the widget is clicked', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.clicked = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"widgetIdentifier", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.widgetIdentifier] self._batchedReadValues = [""] @property def widgetIdentifier(self): return self._batchedReadValues[0] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[0] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"clicked", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def clicked(self): value = self._batchedWriteValues.get(self._attributes.clicked) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.clicked) return data_view.get() @clicked.setter def clicked(self, value): self._batchedWriteValues[self._attributes.clicked] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnWidgetClickedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnWidgetClickedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnWidgetClickedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.OnWidgetClicked' @staticmethod def compute(context, node): try: per_node_data = OgnOnWidgetClickedDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnOnWidgetClickedDatabase(node) per_node_data['_db'] = db except: db = OgnOnWidgetClickedDatabase(node) try: compute_function = getattr(OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnOnWidgetClickedDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnOnWidgetClickedDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On Widget Clicked (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Event node which fires when a UI widget with the specified identifier is clicked. This node should be used in combination with UI creation nodes such as OgnButton.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.compute_rule = og.eComputeRule.E_ON_REQUEST OgnOnWidgetClickedDatabase.INTERFACE.add_to_node_type(node_type) node_type.set_has_state(True) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnOnWidgetClickedDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnOnWidgetClickedDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.OnWidgetClicked")
11,051
Python
51.132075
244
0.641571
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnButtonDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.Button Create a button widget on the Viewport """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import sys import traceback import numpy class OgnButtonDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.Button Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.create inputs.parentWidgetPath inputs.size inputs.startHidden inputs.style inputs.text inputs.widgetIdentifier Outputs: outputs.created outputs.widgetPath """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:create', 'execution', 0, 'Create', 'Input execution to create and show the widget', {}, True, None, False, ''), ('inputs:parentWidgetPath', 'token', 0, 'Parent Widget Path', 'The absolute path to the parent widget.', {}, True, '', False, ''), ('inputs:size', 'double2', 0, 'Size', 'The width and height of the created widget.\nValue of 0 means the created widget will be just large enough to fit everything.', {}, True, [0.0, 0.0], False, ''), ('inputs:startHidden', 'bool', 0, 'Start Hidden', 'Determines whether the button will initially be visible (False) or not (True).', {ogn.MetadataKeys.DEFAULT: 'false'}, False, False, False, ''), ('inputs:style', 'string', 0, None, 'Style to be applied to the button. This can later be changed with the WriteWidgetStyle node.', {}, False, None, False, ''), ('inputs:text', 'string', 0, 'Text', 'The text that is displayed on the button', {}, False, None, False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'An optional unique identifier for the widget.\nCan be used to refer to this widget in other places such as the OnWidgetClicked node.', {}, False, None, False, ''), ('outputs:created', 'execution', 0, 'Created', 'Executed when the widget is created', {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', 'The absolute path to the created widget', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.create = og.Database.ROLE_EXECUTION role_data.outputs.created = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"create", "parentWidgetPath", "size", "startHidden", "style", "text", "widgetIdentifier", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.create, self._attributes.parentWidgetPath, self._attributes.size, self._attributes.startHidden, self._attributes.style, self._attributes.text, self._attributes.widgetIdentifier] self._batchedReadValues = [None, "", [0.0, 0.0], False, None, None, None] @property def create(self): return self._batchedReadValues[0] @create.setter def create(self, value): self._batchedReadValues[0] = value @property def parentWidgetPath(self): return self._batchedReadValues[1] @parentWidgetPath.setter def parentWidgetPath(self, value): self._batchedReadValues[1] = value @property def size(self): return self._batchedReadValues[2] @size.setter def size(self, value): self._batchedReadValues[2] = value @property def startHidden(self): return self._batchedReadValues[3] @startHidden.setter def startHidden(self, value): self._batchedReadValues[3] = value @property def style(self): return self._batchedReadValues[4] @style.setter def style(self, value): self._batchedReadValues[4] = value @property def text(self): return self._batchedReadValues[5] @text.setter def text(self, value): self._batchedReadValues[5] = value @property def widgetIdentifier(self): return self._batchedReadValues[6] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[6] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"created", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def created(self): value = self._batchedWriteValues.get(self._attributes.created) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.created) return data_view.get() @created.setter def created(self, value): self._batchedWriteValues[self._attributes.created] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnButtonDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnButtonDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnButtonDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnButtonDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.Button' @staticmethod def compute(context, node): try: per_node_data = OgnButtonDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnButtonDatabase(node) per_node_data['_db'] = db except: db = OgnButtonDatabase(node) try: compute_function = getattr(OgnButtonDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnButtonDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnButtonDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnButtonDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnButtonDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnButtonDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnButtonDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnButtonDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Button (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Create a button widget on the Viewport") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnButtonDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnButtonDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnButtonDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnButtonDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.Button")
13,655
Python
47.084507
237
0.62468
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnSliderDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.Slider Create a slider widget on the Viewport """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys class OgnSliderDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.Slider Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.create inputs.disable inputs.enable inputs.hide inputs.max inputs.min inputs.parentWidgetPath inputs.show inputs.step inputs.tearDown inputs.widgetIdentifier inputs.width Outputs: outputs.created outputs.widgetPath """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:create', 'execution', 0, 'Create', 'Input execution to create and show the widget', {}, True, None, False, ''), ('inputs:disable', 'execution', 0, 'Disable', 'Disable this button so that it cannot be pressed', {}, True, None, False, ''), ('inputs:enable', 'execution', 0, 'Enable', 'Enable this button after it has been disabled', {}, True, None, False, ''), ('inputs:hide', 'execution', 0, 'Hide', 'Input execution to hide the widget and all its child widgets', {}, True, None, False, ''), ('inputs:max', 'float', 0, 'Max', 'The maximum value of the slider', {}, True, 0.0, False, ''), ('inputs:min', 'float', 0, 'Min', 'The minimum value of the slider', {}, True, 0.0, False, ''), ('inputs:parentWidgetPath', 'token', 0, 'Parent Widget Path', 'The absolute path to the parent widget.\nIf empty, this widget will be created as a direct child of Viewport.', {}, False, None, False, ''), ('inputs:show', 'execution', 0, 'Show', 'Input execution to show the widget and all its child widgets after they become hidden', {}, True, None, False, ''), ('inputs:step', 'float', 0, 'Step', 'The step size of the slider', {ogn.MetadataKeys.DEFAULT: '0.01'}, True, 0.01, False, ''), ('inputs:tearDown', 'execution', 0, 'Tear Down', 'Input execution to tear down the widget and all its child widgets', {}, True, None, False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'An optional unique identifier for the widget.\nCan be used to refer to this widget in other places such as the OnWidgetClicked node.', {}, False, None, False, ''), ('inputs:width', 'double', 0, 'Width', 'The width of the created slider', {ogn.MetadataKeys.DEFAULT: '100.0'}, True, 100.0, False, ''), ('outputs:created', 'execution', 0, 'Created', 'Executed when the widget is created', {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', 'The absolute path to the created widget', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.create = og.Database.ROLE_EXECUTION role_data.inputs.disable = og.Database.ROLE_EXECUTION role_data.inputs.enable = og.Database.ROLE_EXECUTION role_data.inputs.hide = og.Database.ROLE_EXECUTION role_data.inputs.show = og.Database.ROLE_EXECUTION role_data.inputs.tearDown = og.Database.ROLE_EXECUTION role_data.outputs.created = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"create", "disable", "enable", "hide", "max", "min", "parentWidgetPath", "show", "step", "tearDown", "widgetIdentifier", "width", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.create, self._attributes.disable, self._attributes.enable, self._attributes.hide, self._attributes.max, self._attributes.min, self._attributes.parentWidgetPath, self._attributes.show, self._attributes.step, self._attributes.tearDown, self._attributes.widgetIdentifier, self._attributes.width] self._batchedReadValues = [None, None, None, None, 0.0, 0.0, None, None, 0.01, None, None, 100.0] @property def create(self): return self._batchedReadValues[0] @create.setter def create(self, value): self._batchedReadValues[0] = value @property def disable(self): return self._batchedReadValues[1] @disable.setter def disable(self, value): self._batchedReadValues[1] = value @property def enable(self): return self._batchedReadValues[2] @enable.setter def enable(self, value): self._batchedReadValues[2] = value @property def hide(self): return self._batchedReadValues[3] @hide.setter def hide(self, value): self._batchedReadValues[3] = value @property def max(self): return self._batchedReadValues[4] @max.setter def max(self, value): self._batchedReadValues[4] = value @property def min(self): return self._batchedReadValues[5] @min.setter def min(self, value): self._batchedReadValues[5] = value @property def parentWidgetPath(self): return self._batchedReadValues[6] @parentWidgetPath.setter def parentWidgetPath(self, value): self._batchedReadValues[6] = value @property def show(self): return self._batchedReadValues[7] @show.setter def show(self, value): self._batchedReadValues[7] = value @property def step(self): return self._batchedReadValues[8] @step.setter def step(self, value): self._batchedReadValues[8] = value @property def tearDown(self): return self._batchedReadValues[9] @tearDown.setter def tearDown(self, value): self._batchedReadValues[9] = value @property def widgetIdentifier(self): return self._batchedReadValues[10] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[10] = value @property def width(self): return self._batchedReadValues[11] @width.setter def width(self, value): self._batchedReadValues[11] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"created", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def created(self): value = self._batchedWriteValues.get(self._attributes.created) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.created) return data_view.get() @created.setter def created(self, value): self._batchedWriteValues[self._attributes.created] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSliderDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSliderDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSliderDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnSliderDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.Slider' @staticmethod def compute(context, node): try: per_node_data = OgnSliderDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnSliderDatabase(node) per_node_data['_db'] = db except: db = OgnSliderDatabase(node) try: compute_function = getattr(OgnSliderDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnSliderDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnSliderDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnSliderDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnSliderDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnSliderDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnSliderDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnSliderDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Slider (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Create a slider widget on the Viewport") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnSliderDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnSliderDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnSliderDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnSliderDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.Slider")
15,777
Python
45.680473
352
0.618369
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnSetCameraPositionDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.SetCameraPosition Sets the camera's position """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy import carb class OgnSetCameraPositionDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.SetCameraPosition Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.position inputs.prim inputs.primPath inputs.rotate inputs.usePath Outputs: outputs.execOut """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''), ('inputs:position', 'point3d', 0, 'Position', 'The new position', {}, True, [0.0, 0.0, 0.0], False, ''), ('inputs:prim', 'bundle', 0, None, "The camera prim, when 'usePath' is false", {}, False, None, False, ''), ('inputs:primPath', 'token', 0, 'Camera Path', "Path of the camera, used when 'usePath' is true", {}, True, '', False, ''), ('inputs:rotate', 'bool', 0, 'Rotate', 'True to keep position but change orientation and radius (camera moves to new \n position while still looking at the same target).\nFalse to keep orientation and radius but change position (camera moves to look at new target).', {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:usePath', 'bool', 0, None, "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.Database.ROLE_EXECUTION role_data.inputs.position = og.Database.ROLE_POINT role_data.inputs.prim = og.Database.ROLE_BUNDLE role_data.outputs.execOut = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "position", "primPath", "rotate", "usePath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.position, self._attributes.primPath, self._attributes.rotate, self._attributes.usePath] self._batchedReadValues = [None, [0.0, 0.0, 0.0], "", True, True] @property def prim(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.prim""" return self.__bundles.prim @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def position(self): return self._batchedReadValues[1] @position.setter def position(self, value): self._batchedReadValues[1] = value @property def primPath(self): return self._batchedReadValues[2] @primPath.setter def primPath(self, value): self._batchedReadValues[2] = value @property def rotate(self): return self._batchedReadValues[3] @rotate.setter def rotate(self, value): self._batchedReadValues[3] = value @property def usePath(self): return self._batchedReadValues[4] @usePath.setter def usePath(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSetCameraPositionDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetCameraPositionDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetCameraPositionDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,575
Python
47.451977
335
0.635802
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnViewportClickedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnViewportClicked Event node which fires when a viewport click event occurs in the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnOnViewportClickedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnViewportClicked Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.useNormalizedCoords inputs.viewport Outputs: outputs.clicked outputs.position Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport click events', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, 'Left Mouse Click', False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of the 2D position output are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for click events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:clicked', 'execution', 0, 'Clicked', 'Enabled when the specified input gesture triggers a viewport click event in the specified viewport', {}, True, None, False, ''), ('outputs:position', 'double2', 0, 'Position', 'The position at which the viewport click event occurred', {}, True, None, False, ''), ]) class tokens: LeftMouseClick = "Left Mouse Click" RightMouseClick = "Right Mouse Click" MiddleMouseClick = "Middle Mouse Click" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.clicked = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "onlyPlayback", "useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.onlyPlayback, self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Click", True, False, "Viewport"] @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def onlyPlayback(self): return self._batchedReadValues[1] @onlyPlayback.setter def onlyPlayback(self, value): self._batchedReadValues[1] = value @property def useNormalizedCoords(self): return self._batchedReadValues[2] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[2] = value @property def viewport(self): return self._batchedReadValues[3] @viewport.setter def viewport(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"clicked", "position", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def clicked(self): value = self._batchedWriteValues.get(self._attributes.clicked) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.clicked) return data_view.get() @clicked.setter def clicked(self, value): self._batchedWriteValues[self._attributes.clicked] = value @property def position(self): value = self._batchedWriteValues.get(self._attributes.position) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.position) return data_view.get() @position.setter def position(self, value): self._batchedWriteValues[self._attributes.position] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportClickedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportClickedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportClickedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
9,355
Python
50.977777
508
0.655799
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnViewportScrolledDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnViewportScrolled Event node which fires when a viewport scroll event occurs in the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnOnViewportScrolledDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnViewportScrolled Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.onlyPlayback inputs.useNormalizedCoords inputs.viewport Outputs: outputs.position outputs.scrollValue outputs.scrolled """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of the 2D position output are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for scroll events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:position', 'double2', 0, 'Position', 'The position at which the viewport scroll event occurred', {}, True, None, False, ''), ('outputs:scrollValue', 'float', 0, 'Scroll Value', 'The number of mouse wheel clicks scrolled up if positive, or scrolled down if negative', {}, True, None, False, ''), ('outputs:scrolled', 'execution', 0, 'Scrolled', 'Enabled when a viewport scroll event occurs in the specified viewport', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.scrolled = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"onlyPlayback", "useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.onlyPlayback, self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = [True, False, "Viewport"] @property def onlyPlayback(self): return self._batchedReadValues[0] @onlyPlayback.setter def onlyPlayback(self, value): self._batchedReadValues[0] = value @property def useNormalizedCoords(self): return self._batchedReadValues[1] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"position", "scrollValue", "scrolled", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def position(self): value = self._batchedWriteValues.get(self._attributes.position) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.position) return data_view.get() @position.setter def position(self, value): self._batchedWriteValues[self._attributes.position] = value @property def scrollValue(self): value = self._batchedWriteValues.get(self._attributes.scrollValue) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.scrollValue) return data_view.get() @scrollValue.setter def scrollValue(self, value): self._batchedWriteValues[self._attributes.scrollValue] = value @property def scrolled(self): value = self._batchedWriteValues.get(self._attributes.scrolled) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.scrolled) return data_view.get() @scrolled.setter def scrolled(self, value): self._batchedWriteValues[self._attributes.scrolled] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportScrolledDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportScrolledDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportScrolledDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,968
Python
49.960227
368
0.650089
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnWidgetValueChangedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnWidgetValueChanged Event node which fires when a UI widget with the specified identifier has its value changed. This node should be used in combination with UI creation nodes such as OgnSlider. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn from typing import Any import traceback import sys class OgnOnWidgetValueChangedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnWidgetValueChanged Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.widgetIdentifier Outputs: outputs.newValue outputs.valueChanged """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'A unique identifier identifying the widget.\nThis should be specified in the UI creation node such as OgnSlider.', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, '', False, ''), ('outputs:newValue', 'bool,float,int,string', 1, 'New Value', 'The new value of the widget', {}, True, None, False, ''), ('outputs:valueChanged', 'execution', 0, 'Value Changed', 'Executed when the value of the widget is changed', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.valueChanged = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"widgetIdentifier", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.widgetIdentifier] self._batchedReadValues = [""] @property def widgetIdentifier(self): return self._batchedReadValues[0] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[0] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"valueChanged", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def newValue(self) -> og.RuntimeAttribute: """Get the runtime wrapper class for the attribute outputs.newValue""" return og.RuntimeAttribute(self._attributes.newValue.get_attribute_data(), self._context, False) @newValue.setter def newValue(self, value_to_set: Any): """Assign another attribute's value to outputs.newValue""" if isinstance(value_to_set, og.RuntimeAttribute): self.newValue.value = value_to_set.value else: self.newValue.value = value_to_set @property def valueChanged(self): value = self._batchedWriteValues.get(self._attributes.valueChanged) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.valueChanged) return data_view.get() @valueChanged.setter def valueChanged(self, value): self._batchedWriteValues[self._attributes.valueChanged] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnWidgetValueChangedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnWidgetValueChangedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnWidgetValueChangedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.OnWidgetValueChanged' @staticmethod def compute(context, node): try: per_node_data = OgnOnWidgetValueChangedDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnOnWidgetValueChangedDatabase(node) per_node_data['_db'] = db except: db = OgnOnWidgetValueChangedDatabase(node) try: compute_function = getattr(OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnOnWidgetValueChangedDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnOnWidgetValueChangedDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On Widget Value Changed (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Event node which fires when a UI widget with the specified identifier has its value changed. This node should be used in combination with UI creation nodes such as OgnSlider.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.compute_rule = og.eComputeRule.E_ON_REQUEST OgnOnWidgetValueChangedDatabase.INTERFACE.add_to_node_type(node_type) node_type.set_has_state(True) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnOnWidgetValueChangedDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnOnWidgetValueChangedDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.OnWidgetValueChanged")
12,043
Python
51.824561
246
0.645437
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadViewportScrollStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadViewportScrollState Read the state of the last viewport scroll event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnReadViewportScrollStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadViewportScrollState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isValid outputs.position outputs.scrollValue """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of the 2D position output are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for scroll events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:position', 'double2', 0, 'Position', 'The last position at which a viewport scroll event occurred in the specified viewport', {}, True, None, False, ''), ('outputs:scrollValue', 'float', 0, 'Scroll Value', 'The number of mouse wheel clicks scrolled up if positive, or scrolled down if negative', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = [False, "Viewport"] @property def useNormalizedCoords(self): return self._batchedReadValues[0] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[0] = value @property def viewport(self): return self._batchedReadValues[1] @viewport.setter def viewport(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isValid", "position", "scrollValue", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isValid(self): value = self._batchedWriteValues.get(self._attributes.isValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): self._batchedWriteValues[self._attributes.isValid] = value @property def position(self): value = self._batchedWriteValues.get(self._attributes.position) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.position) return data_view.get() @position.setter def position(self, value): self._batchedWriteValues[self._attributes.position] = value @property def scrollValue(self): value = self._batchedWriteValues.get(self._attributes.scrollValue) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.scrollValue) return data_view.get() @scrollValue.setter def scrollValue(self, value): self._batchedWriteValues[self._attributes.scrollValue] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadViewportScrollStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportScrollStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportScrollStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,159
Python
50
332
0.650447
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnGetCameraPositionDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.GetCameraPosition Gets a viewport camera position """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import carb import numpy class OgnGetCameraPositionDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.GetCameraPosition Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.prim inputs.primPath inputs.usePath Outputs: outputs.position """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:prim', 'bundle', 0, None, "The camera prim, when 'usePath' is false", {}, False, None, False, ''), ('inputs:primPath', 'token', 0, 'Camera Path', "Path of the camera, used when 'usePath' is true", {}, True, '', False, ''), ('inputs:usePath', 'bool', 0, None, "When true, the 'primPath' attribute is used as the path to the prim being read, otherwise it will read the connection at the 'prim' attribute", {ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('outputs:position', 'point3d', 0, 'Position', 'The position of the camera in world space', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.prim = og.Database.ROLE_BUNDLE role_data.outputs.position = og.Database.ROLE_POINT return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"primPath", "usePath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.primPath, self._attributes.usePath] self._batchedReadValues = ["", True] @property def prim(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.prim""" return self.__bundles.prim @property def primPath(self): return self._batchedReadValues[0] @primPath.setter def primPath(self, value): self._batchedReadValues[0] = value @property def usePath(self): return self._batchedReadValues[1] @usePath.setter def usePath(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"position", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def position(self): value = self._batchedWriteValues.get(self._attributes.position) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.position) return data_view.get() @position.setter def position(self, value): self._batchedWriteValues[self._attributes.position] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnGetCameraPositionDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGetCameraPositionDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGetCameraPositionDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
7,141
Python
48.255172
248
0.642767
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnPickedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnPicked Event node which fires when a picking event occurs in the specified viewport. Note that picking events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import carb import numpy class OgnOnPickedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnPicked Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.trackedPrims inputs.viewport Outputs: outputs.isTrackedPrimPicked outputs.missed outputs.picked outputs.pickedPrimPath outputs.pickedWorldPos outputs.trackedPrimPaths Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick tokens.LeftMousePress tokens.RightMousePress tokens.MiddleMousePress """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger a picking event', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click,Left Mouse Press,Right Mouse Press,Middle Mouse Press', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click", "LeftMousePress": "Left Mouse Press", "RightMousePress": "Right Mouse Press", "MiddleMousePress": "Middle Mouse Press"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, 'Left Mouse Click', False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:trackedPrims', 'bundle', 0, 'Tracked Prims', "Optionally specify a set of tracked prims that will cause 'Picked' to fire when picked", {ogn.MetadataKeys.LITERAL_ONLY: '1'}, False, None, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for picking events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isTrackedPrimPicked', 'bool', 0, 'Is Tracked Prim Picked', "True if a tracked prim got picked, or if any prim got picked if no tracked prims are specified\n(will always be true when 'Picked' fires, and false when 'Missed' fires)", {}, True, None, False, ''), ('outputs:missed', 'execution', 0, 'Missed', 'Enabled when an attempted picking did not pick a tracked prim,\nor when nothing gets picked if no tracked prims are specified', {}, True, None, False, ''), ('outputs:picked', 'execution', 0, 'Picked', 'Enabled when a tracked prim is picked,\nor when any prim is picked if no tracked prims are specified', {}, True, None, False, ''), ('outputs:pickedPrimPath', 'token', 0, 'Picked Prim Path', 'The path of the picked prim, or an empty string if nothing got picked', {}, True, None, False, ''), ('outputs:pickedWorldPos', 'point3d', 0, 'Picked World Position', 'The XYZ-coordinates of the point in world space at which the prim got picked,\nor (0,0,0) if nothing got picked', {}, True, None, False, ''), ('outputs:trackedPrimPaths', 'token[]', 0, 'Tracked Prim Paths', "A list of the paths of the prims specified in 'Tracked Prims'", {}, True, None, False, ''), ]) class tokens: LeftMouseClick = "Left Mouse Click" RightMouseClick = "Right Mouse Click" MiddleMouseClick = "Middle Mouse Click" LeftMousePress = "Left Mouse Press" RightMousePress = "Right Mouse Press" MiddleMousePress = "Middle Mouse Press" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.trackedPrims = og.Database.ROLE_BUNDLE role_data.outputs.missed = og.Database.ROLE_EXECUTION role_data.outputs.picked = og.Database.ROLE_EXECUTION role_data.outputs.pickedWorldPos = og.Database.ROLE_POINT return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "onlyPlayback", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={}) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.onlyPlayback, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Click", True, "Viewport"] @property def trackedPrims(self) -> og.BundleContents: """Get the bundle wrapper class for the attribute inputs.trackedPrims""" return self.__bundles.trackedPrims @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def onlyPlayback(self): return self._batchedReadValues[1] @onlyPlayback.setter def onlyPlayback(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isTrackedPrimPicked", "missed", "picked", "pickedPrimPath", "pickedWorldPos", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.trackedPrimPaths_size = None self._batchedWriteValues = { } @property def trackedPrimPaths(self): data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) return data_view.get(reserved_element_count=self.trackedPrimPaths_size) @trackedPrimPaths.setter def trackedPrimPaths(self, value): data_view = og.AttributeValueHelper(self._attributes.trackedPrimPaths) data_view.set(value) self.trackedPrimPaths_size = data_view.get_array_size() @property def isTrackedPrimPicked(self): value = self._batchedWriteValues.get(self._attributes.isTrackedPrimPicked) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isTrackedPrimPicked) return data_view.get() @isTrackedPrimPicked.setter def isTrackedPrimPicked(self, value): self._batchedWriteValues[self._attributes.isTrackedPrimPicked] = value @property def missed(self): value = self._batchedWriteValues.get(self._attributes.missed) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.missed) return data_view.get() @missed.setter def missed(self, value): self._batchedWriteValues[self._attributes.missed] = value @property def picked(self): value = self._batchedWriteValues.get(self._attributes.picked) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.picked) return data_view.get() @picked.setter def picked(self, value): self._batchedWriteValues[self._attributes.picked] = value @property def pickedPrimPath(self): value = self._batchedWriteValues.get(self._attributes.pickedPrimPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pickedPrimPath) return data_view.get() @pickedPrimPath.setter def pickedPrimPath(self, value): self._batchedWriteValues[self._attributes.pickedPrimPath] = value @property def pickedWorldPos(self): value = self._batchedWriteValues.get(self._attributes.pickedWorldPos) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.pickedWorldPos) return data_view.get() @pickedWorldPos.setter def pickedWorldPos(self, value): self._batchedWriteValues[self._attributes.pickedWorldPos] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnPickedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnPickedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnPickedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
12,820
Python
50.906882
676
0.64922
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadViewportClickStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadViewportClickState Read the state of the last viewport click event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnReadViewportClickStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadViewportClickState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isValid outputs.position Predefined Tokens: tokens.LeftMouseClick tokens.RightMouseClick tokens.MiddleMouseClick """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport click events', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Click,Right Mouse Click,Middle Mouse Click', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseClick": "Left Mouse Click", "RightMouseClick": "Right Mouse Click", "MiddleMouseClick": "Middle Mouse Click"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Click"'}, True, 'Left Mouse Click', False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of the 2D position output are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for click events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:position', 'double2', 0, 'Position', 'The position at which the specified input gesture last triggered a viewport click event in the specified viewport', {}, True, None, False, ''), ]) class tokens: LeftMouseClick = "Left Mouse Click" RightMouseClick = "Right Mouse Click" MiddleMouseClick = "Middle Mouse Click" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Click", False, "Viewport"] @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def useNormalizedCoords(self): return self._batchedReadValues[1] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isValid", "position", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isValid(self): value = self._batchedWriteValues.get(self._attributes.isValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): self._batchedWriteValues[self._attributes.isValid] = value @property def position(self): value = self._batchedWriteValues.get(self._attributes.position) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.position) return data_view.get() @position.setter def position(self, value): self._batchedWriteValues[self._attributes.position] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadViewportClickStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportClickStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportClickStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,521
Python
50.963414
472
0.65673
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnGetActiveViewportCameraDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.GetActiveViewportCamera Gets the path of the camera bound to a viewport """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys class OgnGetActiveViewportCameraDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.GetActiveViewportCamera Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.viewport Outputs: outputs.camera """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport, or empty for the default viewport', {}, True, '', False, ''), ('outputs:camera', 'token', 0, 'Camera', 'Path of the active camera', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.viewport] self._batchedReadValues = [""] @property def viewport(self): return self._batchedReadValues[0] @viewport.setter def viewport(self, value): self._batchedReadValues[0] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"camera", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def camera(self): value = self._batchedWriteValues.get(self._attributes.camera) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.camera) return data_view.get() @camera.setter def camera(self, value): self._batchedWriteValues[self._attributes.camera] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnGetActiveViewportCameraDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnGetActiveViewportCameraDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnGetActiveViewportCameraDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.GetActiveViewportCamera' @staticmethod def compute(context, node): try: per_node_data = OgnGetActiveViewportCameraDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnGetActiveViewportCameraDatabase(node) per_node_data['_db'] = db except: db = OgnGetActiveViewportCameraDatabase(node) try: compute_function = getattr(OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnGetActiveViewportCameraDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnGetActiveViewportCameraDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Get Active Camera") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "sceneGraph:camera") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Gets the path of the camera bound to a viewport") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnGetActiveViewportCameraDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnGetActiveViewportCameraDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnGetActiveViewportCameraDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.GetActiveViewportCamera")
10,412
Python
50.549505
145
0.64224
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnPlacerDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.Placer Contruct a Placer widget. The Placer takes a single child and places it at a given position within it. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys import numpy class OgnPlacerDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.Placer Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.create inputs.parentWidgetPath inputs.position inputs.style inputs.widgetIdentifier Outputs: outputs.created outputs.widgetPath """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:create', 'execution', 0, 'Create', 'Input execution to create and show the widget', {}, True, None, False, ''), ('inputs:parentWidgetPath', 'token', 0, 'Parent Widget Path', 'The absolute path to the parent widget.', {}, True, '', False, ''), ('inputs:position', 'double2', 0, 'Position', 'Where to position the child widget within the Placer.', {}, True, [0.0, 0.0], False, ''), ('inputs:style', 'string', 0, None, 'Style to be applied to the Placer and its child. This can later be changed with the\nWriteWidgetStyle node.', {}, False, None, False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'An optional unique identifier for the widget.\nCan be used to refer to this widget in other places such as the OnWidgetClicked node.', {}, False, None, False, ''), ('outputs:created', 'execution', 0, 'Created', 'Executed when the widget is created', {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', 'The absolute path to the created Placer widget', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.create = og.Database.ROLE_EXECUTION role_data.outputs.created = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"create", "parentWidgetPath", "position", "style", "widgetIdentifier", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.create, self._attributes.parentWidgetPath, self._attributes.position, self._attributes.style, self._attributes.widgetIdentifier] self._batchedReadValues = [None, "", [0.0, 0.0], None, None] @property def create(self): return self._batchedReadValues[0] @create.setter def create(self, value): self._batchedReadValues[0] = value @property def parentWidgetPath(self): return self._batchedReadValues[1] @parentWidgetPath.setter def parentWidgetPath(self, value): self._batchedReadValues[1] = value @property def position(self): return self._batchedReadValues[2] @position.setter def position(self, value): self._batchedReadValues[2] = value @property def style(self): return self._batchedReadValues[3] @style.setter def style(self, value): self._batchedReadValues[3] = value @property def widgetIdentifier(self): return self._batchedReadValues[4] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"created", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def created(self): value = self._batchedWriteValues.get(self._attributes.created) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.created) return data_view.get() @created.setter def created(self, value): self._batchedWriteValues[self._attributes.created] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnPlacerDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnPlacerDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnPlacerDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnPlacerDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.Placer' @staticmethod def compute(context, node): try: per_node_data = OgnPlacerDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnPlacerDatabase(node) per_node_data['_db'] = db except: db = OgnPlacerDatabase(node) try: compute_function = getattr(OgnPlacerDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnPlacerDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnPlacerDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnPlacerDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnPlacerDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnPlacerDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnPlacerDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnPlacerDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Placer (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Contruct a Placer widget. The Placer takes a single child and places it at a given position within it.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnPlacerDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnPlacerDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnPlacerDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnPlacerDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.Placer")
12,901
Python
47.871212
233
0.628091
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnWriteWidgetStyleDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.WriteWidgetStyle Sets a widget's style properties. This node should be used in combination with UI creation nodes such as Button. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys class OgnWriteWidgetStyleDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.WriteWidgetStyle Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.style inputs.widgetIdentifier inputs.widgetPath inputs.write Outputs: outputs.written """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:style', 'string', 0, None, 'The style to set the widget to.', {}, True, '', False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'A unique identifier identifying the widget. This is only valid within the current graph.\nThis should be specified in the UI creation node such as OgnButton.', {}, True, '', False, ''), ('inputs:widgetPath', 'token', 0, 'Widget Path', "Full path to the widget. If present this will be used insted of 'widgetIdentifier'.\nUnlike 'widgetIdentifier' this is valid across all graphs.", {}, True, '', False, ''), ('inputs:write', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('outputs:written', 'execution', 0, None, 'Output execution', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.write = og.Database.ROLE_EXECUTION role_data.outputs.written = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"style", "widgetIdentifier", "widgetPath", "write", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.style, self._attributes.widgetIdentifier, self._attributes.widgetPath, self._attributes.write] self._batchedReadValues = ["", "", "", None] @property def style(self): return self._batchedReadValues[0] @style.setter def style(self, value): self._batchedReadValues[0] = value @property def widgetIdentifier(self): return self._batchedReadValues[1] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[1] = value @property def widgetPath(self): return self._batchedReadValues[2] @widgetPath.setter def widgetPath(self, value): self._batchedReadValues[2] = value @property def write(self): return self._batchedReadValues[3] @write.setter def write(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"written", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def written(self): value = self._batchedWriteValues.get(self._attributes.written) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.written) return data_view.get() @written.setter def written(self, value): self._batchedWriteValues[self._attributes.written] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnWriteWidgetStyleDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnWriteWidgetStyleDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnWriteWidgetStyleDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.WriteWidgetStyle' @staticmethod def compute(context, node): try: per_node_data = OgnWriteWidgetStyleDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnWriteWidgetStyleDatabase(node) per_node_data['_db'] = db except: db = OgnWriteWidgetStyleDatabase(node) try: compute_function = getattr(OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnWriteWidgetStyleDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnWriteWidgetStyleDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Write Widget Style (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Sets a widget's style properties. This node should be used in combination with UI creation nodes such as Button.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.set_data_access(og.eAccessLocation.E_GLOBAL, og.eAccessType.E_READ) OgnWriteWidgetStyleDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnWriteWidgetStyleDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnWriteWidgetStyleDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.WriteWidgetStyle")
12,222
Python
49.717842
255
0.635739
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadMouseStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadMouseState Reads the current state of the mouse. You can choose which mouse element this node is associated with. When mouse element is chosen to be a button, only outputs:isPressed is meaningful. When coordinates are chosen, only outputs:coords and outputs:window are meaningful. Pixel coordinates are the position of the mouse cursor in screen pixel units with (0,0) top left. Normalized coordinates are values between 0-1 where 0 is top/left and 1 is bottom/right. By default, coordinates are relative to the application window, but if 'Use Relative Coords' is set to true, then coordinates are relative to the workspace window containing the mouse pointer. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnReadMouseStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadMouseState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.mouseElement inputs.useRelativeCoords Outputs: outputs.coords outputs.isPressed outputs.window Predefined Tokens: tokens.LeftButton tokens.RightButton tokens.MiddleButton tokens.ForwardButton tokens.BackButton tokens.MouseCoordsNormalized tokens.MouseCoordsPixel """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:mouseElement', 'token', 0, 'Mouse Element', 'The mouse input to check the state of', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Button,Right Button,Middle Button,Forward Button,Back Button,Normalized Mouse Coordinates,Pixel Mouse Coordinates', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftButton": "Left Button", "RightButton": "Right Button", "MiddleButton": "Middle Button", "ForwardButton": "Forward Button", "BackButton": "Back Button", "MouseCoordsNormalized": "Normalized Mouse Coordinates", "MouseCoordsPixel": "Pixel Mouse Coordinates"}', ogn.MetadataKeys.DEFAULT: '"Left Button"'}, True, 'Left Button', False, ''), ('inputs:useRelativeCoords', 'bool', 0, 'Use Relative Coords', "When true, the output 'coords' is made relative to the workspace window containing the\nmouse pointer instead of the entire application window", {}, True, False, False, ''), ('outputs:coords', 'float2', 0, None, 'The coordinates of the mouse. If the mouse element selected is a button, this will output a zero vector.', {}, True, None, False, ''), ('outputs:isPressed', 'bool', 0, None, 'True if the button is currently pressed, false otherwise. If the mouse element selected\nis a coordinate, this will output false.', {}, True, None, False, ''), ('outputs:window', 'token', 0, None, "The name of the workspace window containing the mouse pointer if 'Use Relative Coords' is true\nand the mouse element selected is a coordinate", {}, True, None, False, ''), ]) class tokens: LeftButton = "Left Button" RightButton = "Right Button" MiddleButton = "Middle Button" ForwardButton = "Forward Button" BackButton = "Back Button" MouseCoordsNormalized = "Normalized Mouse Coordinates" MouseCoordsPixel = "Pixel Mouse Coordinates" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"mouseElement", "useRelativeCoords", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.mouseElement, self._attributes.useRelativeCoords] self._batchedReadValues = ["Left Button", False] @property def mouseElement(self): return self._batchedReadValues[0] @mouseElement.setter def mouseElement(self, value): self._batchedReadValues[0] = value @property def useRelativeCoords(self): return self._batchedReadValues[1] @useRelativeCoords.setter def useRelativeCoords(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"coords", "isPressed", "window", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def coords(self): value = self._batchedWriteValues.get(self._attributes.coords) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.coords) return data_view.get() @coords.setter def coords(self, value): self._batchedWriteValues[self._attributes.coords] = value @property def isPressed(self): value = self._batchedWriteValues.get(self._attributes.isPressed) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isPressed) return data_view.get() @isPressed.setter def isPressed(self, value): self._batchedWriteValues[self._attributes.isPressed] = value @property def window(self): value = self._batchedWriteValues.get(self._attributes.window) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.window) return data_view.get() @window.setter def window(self, value): self._batchedWriteValues[self._attributes.window] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadMouseStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadMouseStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadMouseStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
9,573
Python
51.604395
666
0.661339
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadViewportHoverStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadViewportHoverState Read the state of the last viewport hover event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnReadViewportHoverStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadViewportHoverState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.useNormalizedCoords inputs.viewport Outputs: outputs.isHovered outputs.isValid outputs.position outputs.velocity """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position and velocity outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for hover events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:isHovered', 'bool', 0, 'Is Hovered', 'True if the specified viewport is currently hovered', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:position', 'double2', 0, 'Position', 'The current mouse position if the specified viewport is currently hovered, otherwise (0,0)', {}, True, None, False, ''), ('outputs:velocity', 'double2', 0, 'Velocity', 'A vector representing the change in position of the mouse since the previous frame\nif the specified viewport is currently hovered, otherwise (0,0)', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = [False, "Viewport"] @property def useNormalizedCoords(self): return self._batchedReadValues[0] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[0] = value @property def viewport(self): return self._batchedReadValues[1] @viewport.setter def viewport(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"isHovered", "isValid", "position", "velocity", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def isHovered(self): value = self._batchedWriteValues.get(self._attributes.isHovered) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isHovered) return data_view.get() @isHovered.setter def isHovered(self, value): self._batchedWriteValues[self._attributes.isHovered] = value @property def isValid(self): value = self._batchedWriteValues.get(self._attributes.isValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): self._batchedWriteValues[self._attributes.isValid] = value @property def position(self): value = self._batchedWriteValues.get(self._attributes.position) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.position) return data_view.get() @position.setter def position(self, value): self._batchedWriteValues[self._attributes.position] = value @property def velocity(self): value = self._batchedWriteValues.get(self._attributes.velocity) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.velocity) return data_view.get() @velocity.setter def velocity(self, value): self._batchedWriteValues[self._attributes.velocity] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadViewportHoverStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportHoverStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportHoverStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
8,828
Python
49.451428
342
0.64556
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnSetActiveViewportCameraDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.SetActiveViewportCamera Sets Viewport's actively bound camera to given camera at give path """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import sys import traceback class OgnSetActiveViewportCameraDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.SetActiveViewportCamera Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.primPath inputs.viewport Outputs: outputs.execOut """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''), ('inputs:primPath', 'token', 0, 'Camera Path', 'Path of the camera to bind', {}, True, '', False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport, or empty for the default viewport', {}, True, '', False, ''), ('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.Database.ROLE_EXECUTION role_data.outputs.execOut = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "primPath", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.primPath, self._attributes.viewport] self._batchedReadValues = [None, "", ""] @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def primPath(self): return self._batchedReadValues[1] @primPath.setter def primPath(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSetActiveViewportCameraDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetActiveViewportCameraDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetActiveViewportCameraDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.SetActiveViewportCamera' @staticmethod def compute(context, node): try: per_node_data = OgnSetActiveViewportCameraDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnSetActiveViewportCameraDatabase(node) per_node_data['_db'] = db except: db = OgnSetActiveViewportCameraDatabase(node) try: compute_function = getattr(OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnSetActiveViewportCameraDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnSetActiveViewportCameraDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Set Active Camera") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "sceneGraph:camera") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Sets Viewport's actively bound camera to given camera at give path") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnSetActiveViewportCameraDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnSetActiveViewportCameraDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnSetActiveViewportCameraDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.SetActiveViewportCamera")
11,526
Python
49.336244
145
0.63873
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnDrawDebugCurveDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.DrawDebugCurve Given a set of curve points, draw a curve in the viewport """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import sys import numpy import traceback class OgnDrawDebugCurveDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.DrawDebugCurve Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.closed inputs.color inputs.curvepoints inputs.execIn Outputs: outputs.execOut """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:closed', 'bool', 0, 'Closed', 'When true, connect the last point to the first', {}, True, False, False, ''), ('inputs:color', 'color3f', 0, 'Color', 'The color of the curve', {}, True, [0.0, 0.0, 0.0], False, ''), ('inputs:curvepoints', 'double3[]', 0, 'Curve Points', 'The curve to be drawn', {}, True, [], False, ''), ('inputs:execIn', 'execution', 0, 'In', 'Execution input', {}, True, None, False, ''), ('outputs:execOut', 'execution', 0, 'Out', 'Execution Output', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.color = og.Database.ROLE_COLOR role_data.inputs.execIn = og.Database.ROLE_EXECUTION role_data.outputs.execOut = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"closed", "color", "execIn", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.closed, self._attributes.color, self._attributes.execIn] self._batchedReadValues = [False, [0.0, 0.0, 0.0], None] @property def curvepoints(self): data_view = og.AttributeValueHelper(self._attributes.curvepoints) return data_view.get() @curvepoints.setter def curvepoints(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.curvepoints) data_view = og.AttributeValueHelper(self._attributes.curvepoints) data_view.set(value) self.curvepoints_size = data_view.get_array_size() @property def closed(self): return self._batchedReadValues[0] @closed.setter def closed(self, value): self._batchedReadValues[0] = value @property def color(self): return self._batchedReadValues[1] @color.setter def color(self, value): self._batchedReadValues[1] = value @property def execIn(self): return self._batchedReadValues[2] @execIn.setter def execIn(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnDrawDebugCurveDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnDrawDebugCurveDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnDrawDebugCurveDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.DrawDebugCurve' @staticmethod def compute(context, node): try: per_node_data = OgnDrawDebugCurveDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnDrawDebugCurveDatabase(node) per_node_data['_db'] = db except: db = OgnDrawDebugCurveDatabase(node) try: compute_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnDrawDebugCurveDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnDrawDebugCurveDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Draw Debug Curve") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "debug") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Given a set of curve points, draw a curve in the viewport") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnDrawDebugCurveDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnDrawDebugCurveDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnDrawDebugCurveDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.DrawDebugCurve")
11,980
Python
47.703252
136
0.628047
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnSetViewportModeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.SetViewportMode Sets the mode of a specified viewport window to 'Scripted' mode or 'Default' mode when executed. 'Scripted' mode disables default viewport interaction and enables placing UI elements over the viewport. 'Default' mode is the default state of the viewport, and entering it will destroy any UI elements on the viewport. Executing with 'Enable Viewport Mouse Events' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by viewport mouse event nodes, including 'On Viewport Dragged' and 'Read Viewport Drag State'. Executing with 'Enable Picking' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by the 'On Picked' and 'Read Pick State' nodes. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import sys import traceback class OgnSetViewportModeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.SetViewportMode Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.enablePicking inputs.enableViewportMouseEvents inputs.execIn inputs.mode inputs.viewport Outputs: outputs.defaultMode outputs.scriptedMode outputs.widgetPath """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:enablePicking', 'bool', 0, 'Enable Picking', "Enable/Disable picking prims in the specified viewport when in 'Scripted' mode", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:enableViewportMouseEvents', 'bool', 0, 'Enable Viewport Mouse Events', "Enable/Disable viewport mouse events on the specified viewport when in 'Scripted' mode", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''), ('inputs:mode', 'int', 0, 'Mode', "The mode to set the specified viewport to when this node is executed (0: 'Default', 1: 'Scripted')", {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to set the mode of', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:defaultMode', 'execution', 0, 'Default Mode', "Fires when this node is successfully executed with 'Mode' set to 'Default'", {}, True, None, False, ''), ('outputs:scriptedMode', 'execution', 0, 'Scripted Mode', "Fires when this node is successfully executed with 'Mode' set to 'Scripted'", {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', "When the viewport enters 'Scripted' mode, a container widget is created under which other UI may be parented.\nThis attribute provides the absolute path to that widget, which can be used as the 'parentWidgetPath'\ninput to various UI nodes, such as Button. When the viewport exits 'Scripted' mode,\nthe container widget and all the UI within it will be destroyed.", {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.execIn = og.Database.ROLE_EXECUTION role_data.outputs.defaultMode = og.Database.ROLE_EXECUTION role_data.outputs.scriptedMode = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"enablePicking", "enableViewportMouseEvents", "execIn", "mode", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.enablePicking, self._attributes.enableViewportMouseEvents, self._attributes.execIn, self._attributes.mode, self._attributes.viewport] self._batchedReadValues = [False, False, None, 0, "Viewport"] @property def enablePicking(self): return self._batchedReadValues[0] @enablePicking.setter def enablePicking(self, value): self._batchedReadValues[0] = value @property def enableViewportMouseEvents(self): return self._batchedReadValues[1] @enableViewportMouseEvents.setter def enableViewportMouseEvents(self, value): self._batchedReadValues[1] = value @property def execIn(self): return self._batchedReadValues[2] @execIn.setter def execIn(self, value): self._batchedReadValues[2] = value @property def mode(self): return self._batchedReadValues[3] @mode.setter def mode(self, value): self._batchedReadValues[3] = value @property def viewport(self): return self._batchedReadValues[4] @viewport.setter def viewport(self, value): self._batchedReadValues[4] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"defaultMode", "scriptedMode", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def defaultMode(self): value = self._batchedWriteValues.get(self._attributes.defaultMode) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.defaultMode) return data_view.get() @defaultMode.setter def defaultMode(self, value): self._batchedWriteValues[self._attributes.defaultMode] = value @property def scriptedMode(self): value = self._batchedWriteValues.get(self._attributes.scriptedMode) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.scriptedMode) return data_view.get() @scriptedMode.setter def scriptedMode(self, value): self._batchedWriteValues[self._attributes.scriptedMode] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSetViewportModeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSetViewportModeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSetViewportModeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.SetViewportMode' @staticmethod def compute(context, node): try: per_node_data = OgnSetViewportModeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnSetViewportModeDatabase(node) per_node_data['_db'] = db except: db = OgnSetViewportModeDatabase(node) try: compute_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnSetViewportModeDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnSetViewportModeDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnSetViewportModeDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Set Viewport Mode (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Sets the mode of a specified viewport window to 'Scripted' mode or 'Default' mode when executed.\n 'Scripted' mode disables default viewport interaction and enables placing UI elements over the viewport. 'Default' mode is the default state of the viewport, and entering it will destroy any UI elements on the viewport.\n Executing with 'Enable Viewport Mouse Events' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by viewport mouse event nodes, including 'On Viewport Dragged' and 'Read Viewport Drag State'.\n Executing with 'Enable Picking' set to true in 'Scripted' mode is required to allow the specified viewport to be targeted by the 'On Picked' and 'Read Pick State' nodes.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnSetViewportModeDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnSetViewportModeDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnSetViewportModeDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnSetViewportModeDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.SetViewportMode")
15,625
Python
53.445993
795
0.652544
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnViewportDraggedDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnViewportDragged Event node which fires when a viewport drag event occurs in the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnOnViewportDraggedDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnViewportDragged Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.onlyPlayback inputs.useNormalizedCoords inputs.viewport Outputs: outputs.began outputs.ended outputs.finalPosition outputs.initialPosition Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport drag events', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Drag,Right Mouse Drag,Middle Mouse Drag', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Drag", "RightMouseDrag": "Right Mouse Drag", "MiddleMouseDrag": "Middle Mouse Drag"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Drag"'}, True, 'Left Mouse Drag', False, ''), ('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for drag events', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:began', 'execution', 0, 'Began', "Enabled when the drag begins, populating 'Initial Position' with the current mouse position", {}, True, None, False, ''), ('outputs:ended', 'execution', 0, 'Ended', "Enabled when the drag ends, populating 'Final Position' with the current mouse position", {}, True, None, False, ''), ('outputs:finalPosition', 'double2', 0, 'Final Position', "The mouse position at which the drag ended (valid when 'Ended' is enabled)", {}, True, None, False, ''), ('outputs:initialPosition', 'double2', 0, 'Initial Position', "The mouse position at which the drag began (valid when either 'Began' or 'Ended' is enabled)", {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Drag" RightMouseDrag = "Right Mouse Drag" MiddleMouseDrag = "Middle Mouse Drag" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.began = og.Database.ROLE_EXECUTION role_data.outputs.ended = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "onlyPlayback", "useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.onlyPlayback, self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Drag", True, False, "Viewport"] @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def onlyPlayback(self): return self._batchedReadValues[1] @onlyPlayback.setter def onlyPlayback(self, value): self._batchedReadValues[1] = value @property def useNormalizedCoords(self): return self._batchedReadValues[2] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[2] = value @property def viewport(self): return self._batchedReadValues[3] @viewport.setter def viewport(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"began", "ended", "finalPosition", "initialPosition", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def began(self): value = self._batchedWriteValues.get(self._attributes.began) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.began) return data_view.get() @began.setter def began(self, value): self._batchedWriteValues[self._attributes.began] = value @property def ended(self): value = self._batchedWriteValues.get(self._attributes.ended) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.ended) return data_view.get() @ended.setter def ended(self, value): self._batchedWriteValues[self._attributes.ended] = value @property def finalPosition(self): value = self._batchedWriteValues.get(self._attributes.finalPosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.finalPosition) return data_view.get() @finalPosition.setter def finalPosition(self, value): self._batchedWriteValues[self._attributes.finalPosition] = value @property def initialPosition(self): value = self._batchedWriteValues.get(self._attributes.initialPosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.initialPosition) return data_view.get() @initialPosition.setter def initialPosition(self, value): self._batchedWriteValues[self._attributes.initialPosition] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnViewportDraggedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnViewportDraggedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnViewportDraggedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,794
Python
50.161137
496
0.648508
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnSpacerDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.Spacer A widget that leaves empty space. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import sys import traceback class OgnSpacerDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.Spacer Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.create inputs.height inputs.parentWidgetPath inputs.style inputs.widgetIdentifier inputs.width Outputs: outputs.created outputs.widgetPath """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:create', 'execution', 0, 'Create', 'Input execution to create and show the widget', {}, True, None, False, ''), ('inputs:height', 'int', 0, 'Height', 'The amount of vertical space to leave, in pixels.', {ogn.MetadataKeys.DEFAULT: '0'}, False, 0, False, ''), ('inputs:parentWidgetPath', 'token', 0, 'Parent Widget Path', 'The absolute path to the parent widget.', {}, True, '', False, ''), ('inputs:style', 'string', 0, None, 'Style to be applied to the spacer. This can later be changed with the WriteWidgetStyle node.', {}, False, None, False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'An optional unique identifier for the widget.\nCan be used to refer to this widget in other places such as the OnWidgetClicked node.', {}, False, None, False, ''), ('inputs:width', 'int', 0, 'Width', 'The amount of horizontal space to leave, in pixels.', {ogn.MetadataKeys.DEFAULT: '0'}, False, 0, False, ''), ('outputs:created', 'execution', 0, 'Created', 'Executed when the widget is created', {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', 'The absolute path to the created widget', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.create = og.Database.ROLE_EXECUTION role_data.outputs.created = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"create", "height", "parentWidgetPath", "style", "widgetIdentifier", "width", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.create, self._attributes.height, self._attributes.parentWidgetPath, self._attributes.style, self._attributes.widgetIdentifier, self._attributes.width] self._batchedReadValues = [None, 0, "", None, None, 0] @property def create(self): return self._batchedReadValues[0] @create.setter def create(self, value): self._batchedReadValues[0] = value @property def height(self): return self._batchedReadValues[1] @height.setter def height(self, value): self._batchedReadValues[1] = value @property def parentWidgetPath(self): return self._batchedReadValues[2] @parentWidgetPath.setter def parentWidgetPath(self, value): self._batchedReadValues[2] = value @property def style(self): return self._batchedReadValues[3] @style.setter def style(self, value): self._batchedReadValues[3] = value @property def widgetIdentifier(self): return self._batchedReadValues[4] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[4] = value @property def width(self): return self._batchedReadValues[5] @width.setter def width(self, value): self._batchedReadValues[5] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"created", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def created(self): value = self._batchedWriteValues.get(self._attributes.created) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.created) return data_view.get() @created.setter def created(self, value): self._batchedWriteValues[self._attributes.created] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSpacerDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSpacerDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSpacerDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnSpacerDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.Spacer' @staticmethod def compute(context, node): try: per_node_data = OgnSpacerDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnSpacerDatabase(node) per_node_data['_db'] = db except: db = OgnSpacerDatabase(node) try: compute_function = getattr(OgnSpacerDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnSpacerDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnSpacerDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnSpacerDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnSpacerDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnSpacerDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnSpacerDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnSpacerDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Spacer (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "A widget that leaves empty space.") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnSpacerDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnSpacerDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnSpacerDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnSpacerDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.Spacer")
13,123
Python
47.07326
233
0.624171
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnComboBoxDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ComboBox Create a combo box widget on the Viewport """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy import sys import traceback class OgnComboBoxDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ComboBox Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.create inputs.disable inputs.enable inputs.hide inputs.itemList inputs.parentWidgetPath inputs.show inputs.tearDown inputs.widgetIdentifier inputs.width Outputs: outputs.created outputs.widgetPath """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:create', 'execution', 0, 'Create', 'Input execution to create and show the widget', {}, True, None, False, ''), ('inputs:disable', 'execution', 0, 'Disable', 'Disable this button so that it cannot be pressed', {}, True, None, False, ''), ('inputs:enable', 'execution', 0, 'Enable', 'Enable this button after it has been disabled', {}, True, None, False, ''), ('inputs:hide', 'execution', 0, 'Hide', 'Input execution to hide the widget and all its child widgets', {}, True, None, False, ''), ('inputs:itemList', 'token[]', 0, 'Item List', 'A list of items that appears in the drop-down list', {}, True, [], False, ''), ('inputs:parentWidgetPath', 'token', 0, 'Parent Widget Path', 'The absolute path to the parent widget.\nIf empty, this widget will be created as a direct child of Viewport.', {}, False, None, False, ''), ('inputs:show', 'execution', 0, 'Show', 'Input execution to show the widget and all its child widgets after they become hidden', {}, True, None, False, ''), ('inputs:tearDown', 'execution', 0, 'Tear Down', 'Input execution to tear down the widget and all its child widgets', {}, True, None, False, ''), ('inputs:widgetIdentifier', 'token', 0, 'Widget Identifier', 'An optional unique identifier for the widget.\nCan be used to refer to this widget in other places such as the OnWidgetClicked node.', {}, False, None, False, ''), ('inputs:width', 'double', 0, 'Width', 'The width of the created combo box', {ogn.MetadataKeys.DEFAULT: '100.0'}, True, 100.0, False, ''), ('outputs:created', 'execution', 0, 'Created', 'Executed when the widget is created', {}, True, None, False, ''), ('outputs:widgetPath', 'token', 0, 'Widget Path', 'The absolute path to the created widget', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.create = og.Database.ROLE_EXECUTION role_data.inputs.disable = og.Database.ROLE_EXECUTION role_data.inputs.enable = og.Database.ROLE_EXECUTION role_data.inputs.hide = og.Database.ROLE_EXECUTION role_data.inputs.show = og.Database.ROLE_EXECUTION role_data.inputs.tearDown = og.Database.ROLE_EXECUTION role_data.outputs.created = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"create", "disable", "enable", "hide", "parentWidgetPath", "show", "tearDown", "widgetIdentifier", "width", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.create, self._attributes.disable, self._attributes.enable, self._attributes.hide, self._attributes.parentWidgetPath, self._attributes.show, self._attributes.tearDown, self._attributes.widgetIdentifier, self._attributes.width] self._batchedReadValues = [None, None, None, None, None, None, None, None, 100.0] @property def itemList(self): data_view = og.AttributeValueHelper(self._attributes.itemList) return data_view.get() @itemList.setter def itemList(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.itemList) data_view = og.AttributeValueHelper(self._attributes.itemList) data_view.set(value) self.itemList_size = data_view.get_array_size() @property def create(self): return self._batchedReadValues[0] @create.setter def create(self, value): self._batchedReadValues[0] = value @property def disable(self): return self._batchedReadValues[1] @disable.setter def disable(self, value): self._batchedReadValues[1] = value @property def enable(self): return self._batchedReadValues[2] @enable.setter def enable(self, value): self._batchedReadValues[2] = value @property def hide(self): return self._batchedReadValues[3] @hide.setter def hide(self, value): self._batchedReadValues[3] = value @property def parentWidgetPath(self): return self._batchedReadValues[4] @parentWidgetPath.setter def parentWidgetPath(self, value): self._batchedReadValues[4] = value @property def show(self): return self._batchedReadValues[5] @show.setter def show(self, value): self._batchedReadValues[5] = value @property def tearDown(self): return self._batchedReadValues[6] @tearDown.setter def tearDown(self, value): self._batchedReadValues[6] = value @property def widgetIdentifier(self): return self._batchedReadValues[7] @widgetIdentifier.setter def widgetIdentifier(self, value): self._batchedReadValues[7] = value @property def width(self): return self._batchedReadValues[8] @width.setter def width(self, value): self._batchedReadValues[8] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"created", "widgetPath", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def created(self): value = self._batchedWriteValues.get(self._attributes.created) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.created) return data_view.get() @created.setter def created(self, value): self._batchedWriteValues[self._attributes.created] = value @property def widgetPath(self): value = self._batchedWriteValues.get(self._attributes.widgetPath) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.widgetPath) return data_view.get() @widgetPath.setter def widgetPath(self, value): self._batchedWriteValues[self._attributes.widgetPath] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnComboBoxDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnComboBoxDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnComboBoxDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnComboBoxDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.ComboBox' @staticmethod def compute(context, node): try: per_node_data = OgnComboBoxDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnComboBoxDatabase(node) per_node_data['_db'] = db except: db = OgnComboBoxDatabase(node) try: compute_function = getattr(OgnComboBoxDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnComboBoxDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnComboBoxDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnComboBoxDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnComboBoxDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnComboBoxDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnComboBoxDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnComboBoxDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Combo Box (BETA)") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,ui") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Create a combo box widget on the Viewport") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnComboBoxDatabase.INTERFACE.add_to_node_type(node_type) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnComboBoxDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnComboBoxDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnComboBoxDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.ComboBox")
15,419
Python
46.592592
285
0.62397
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnOnNewFrameDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.OnNewFrame Triggers when there is a new frame available for the given viewport. Note that the graph will run asynchronously to the new frame event """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import traceback import sys class OgnOnNewFrameDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.OnNewFrame Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.viewport Outputs: outputs.execOut outputs.frameNumber """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:viewport', 'token', 0, None, 'Name of the viewport, or empty for the default viewport', {'displayGroup': 'parameters'}, True, '', False, ''), ('outputs:execOut', 'execution', 0, None, 'Output Execution', {}, True, None, False, ''), ('outputs:frameNumber', 'int', 0, None, 'The number of the frame which is available', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.outputs.execOut = og.Database.ROLE_EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.viewport] self._batchedReadValues = [""] @property def viewport(self): return self._batchedReadValues[0] @viewport.setter def viewport(self, value): self._batchedReadValues[0] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "frameNumber", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value @property def frameNumber(self): value = self._batchedWriteValues.get(self._attributes.frameNumber) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.frameNumber) return data_view.get() @frameNumber.setter def frameNumber(self, value): self._batchedWriteValues[self._attributes.frameNumber] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnOnNewFrameDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnOnNewFrameDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnOnNewFrameDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnOnNewFrameDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.ui.OnNewFrame' @staticmethod def compute(context, node): try: per_node_data = OgnOnNewFrameDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnOnNewFrameDatabase(node) per_node_data['_db'] = db except: db = OgnOnNewFrameDatabase(node) try: compute_function = getattr(OgnOnNewFrameDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnOnNewFrameDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnOnNewFrameDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnOnNewFrameDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) @staticmethod def release(node): release_function = getattr(OgnOnNewFrameDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnOnNewFrameDatabase._release_per_node_data(node) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnOnNewFrameDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnOnNewFrameDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.ui") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On New Frame") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Triggers when there is a new frame available for the given viewport. Note that the graph will run asynchronously to the new frame event") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.compute_rule = og.eComputeRule.E_ON_REQUEST OgnOnNewFrameDatabase.INTERFACE.add_to_node_type(node_type) node_type.set_has_state(True) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnOnNewFrameDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None GENERATOR_VERSION = (1, 17, 2) TARGET_VERSION = (2, 65, 4) @staticmethod def register(node_type_class): OgnOnNewFrameDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnOnNewFrameDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.graph.ui.OnNewFrame")
11,338
Python
48.951542
207
0.630534
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/OgnReadViewportDragStateDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.ui.ReadViewportDragState Read the state of the last viewport drag event from the specified viewport. Note that viewport mouse events must be enabled on the specified viewport using a SetViewportMode node. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnReadViewportDragStateDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.ui.ReadViewportDragState Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.gesture inputs.useNormalizedCoords inputs.viewport Outputs: outputs.currentPosition outputs.initialPosition outputs.isDragInProgress outputs.isValid outputs.velocity Predefined Tokens: tokens.LeftMouseDrag tokens.RightMouseDrag tokens.MiddleMouseDrag """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:gesture', 'token', 0, 'Gesture', 'The input gesture to trigger viewport drag events', {'displayGroup': 'parameters', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Mouse Drag,Right Mouse Drag,Middle Mouse Drag', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftMouseDrag": "Left Mouse Drag", "RightMouseDrag": "Right Mouse Drag", "MiddleMouseDrag": "Middle Mouse Drag"}', ogn.MetadataKeys.DEFAULT: '"Left Mouse Drag"'}, True, 'Left Mouse Drag', False, ''), ('inputs:useNormalizedCoords', 'bool', 0, 'Use Normalized Coords', 'When true, the components of 2D position and velocity outputs are scaled to between 0 and 1,\nwhere 0 is top/left and 1 is bottom/right.\nWhen false, components are in viewport render resolution pixels.', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:viewport', 'token', 0, 'Viewport', 'Name of the viewport window to watch for drag events', {ogn.MetadataKeys.DEFAULT: '"Viewport"'}, True, 'Viewport', False, ''), ('outputs:currentPosition', 'double2', 0, 'Current Position', 'The current mouse position if a drag is in progress,\nor the final mouse position of the most recent drag if a drag is not in progress', {}, True, None, False, ''), ('outputs:initialPosition', 'double2', 0, 'Initial Position', 'The mouse position at which the most recent drag began', {}, True, None, False, ''), ('outputs:isDragInProgress', 'bool', 0, 'Is Drag In Progress', 'True if a viewport drag event is currently in progress in the specified viewport', {}, True, None, False, ''), ('outputs:isValid', 'bool', 0, 'Is Valid', 'True if a valid event state was detected and the outputs of this node are valid, and false otherwise', {}, True, None, False, ''), ('outputs:velocity', 'double2', 0, 'Velocity', 'A vector representing the change in position of the mouse since the previous frame\nif a drag is in progress, otherwise (0,0)', {}, True, None, False, ''), ]) class tokens: LeftMouseDrag = "Left Mouse Drag" RightMouseDrag = "Right Mouse Drag" MiddleMouseDrag = "Middle Mouse Drag" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"gesture", "useNormalizedCoords", "viewport", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.gesture, self._attributes.useNormalizedCoords, self._attributes.viewport] self._batchedReadValues = ["Left Mouse Drag", False, "Viewport"] @property def gesture(self): return self._batchedReadValues[0] @gesture.setter def gesture(self, value): self._batchedReadValues[0] = value @property def useNormalizedCoords(self): return self._batchedReadValues[1] @useNormalizedCoords.setter def useNormalizedCoords(self, value): self._batchedReadValues[1] = value @property def viewport(self): return self._batchedReadValues[2] @viewport.setter def viewport(self, value): self._batchedReadValues[2] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"currentPosition", "initialPosition", "isDragInProgress", "isValid", "velocity", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def currentPosition(self): value = self._batchedWriteValues.get(self._attributes.currentPosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.currentPosition) return data_view.get() @currentPosition.setter def currentPosition(self, value): self._batchedWriteValues[self._attributes.currentPosition] = value @property def initialPosition(self): value = self._batchedWriteValues.get(self._attributes.initialPosition) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.initialPosition) return data_view.get() @initialPosition.setter def initialPosition(self, value): self._batchedWriteValues[self._attributes.initialPosition] = value @property def isDragInProgress(self): value = self._batchedWriteValues.get(self._attributes.isDragInProgress) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isDragInProgress) return data_view.get() @isDragInProgress.setter def isDragInProgress(self, value): self._batchedWriteValues[self._attributes.isDragInProgress] = value @property def isValid(self): value = self._batchedWriteValues.get(self._attributes.isValid) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.isValid) return data_view.get() @isValid.setter def isValid(self, value): self._batchedWriteValues[self._attributes.isValid] = value @property def velocity(self): value = self._batchedWriteValues.get(self._attributes.velocity) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.velocity) return data_view.get() @velocity.setter def velocity(self, value): self._batchedWriteValues[self._attributes.velocity] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnReadViewportDragStateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnReadViewportDragStateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnReadViewportDragStateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,716
Python
50.277512
460
0.649776
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportHovered.cpp
// 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. // #include <OgnOnViewportHoveredDatabase.h> #include "ViewportHoverNodeCommon.h" #include <omni/kit/IApp.h> #include <omni/ui/Workspace.h> namespace omni { namespace graph { namespace ui { class OgnOnViewportHovered { public: struct InternalState { carb::events::ISubscriptionPtr hoverBeganSub; carb::events::ISubscriptionPtr hoverEndedSub; ViewportHoverEventPayloads eventPayloads; ViewportHoverEventStates eventStates; } m_internalState; static void initialize(GraphContextObj const&, NodeObj const& nodeObj) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sm_stateManagerOgnOnViewportHovered .getState<OgnOnViewportHovered>(nodeObj.nodeHandle); // Subscribe to hover events if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>()) { state.m_internalState.hoverBeganSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kHoverBeganEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sm_stateManagerOgnOnViewportHovered .getState<OgnOnViewportHovered>(nodeObj.nodeHandle); state.m_internalState.eventPayloads.setHoverBeganPayload(e->payload); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); state.m_internalState.hoverEndedSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kHoverEndedEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sm_stateManagerOgnOnViewportHovered .getState<OgnOnViewportHovered>(nodeObj.nodeHandle); state.m_internalState.eventPayloads.setHoverEndedPayload(e->payload); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); } } static void release(const NodeObj& nodeObj) { OgnOnViewportHovered& state = OgnOnViewportHoveredDatabase::sm_stateManagerOgnOnViewportHovered .getState<OgnOnViewportHovered>(nodeObj.nodeHandle); // Unsubscribe from hover events if (state.m_internalState.hoverBeganSub.get()) state.m_internalState.hoverBeganSub.detach()->unsubscribe(); if (state.m_internalState.hoverEndedSub.get()) state.m_internalState.hoverEndedSub.detach()->unsubscribe(); } static bool compute(OgnOnViewportHoveredDatabase& db) { if (checkNodeDisabledForOnlyPlay(db)) return true; OgnOnViewportHovered& state = db.internalState<OgnOnViewportHovered>(); if (state.m_internalState.eventPayloads.empty()) return true; // Get the targeted viewport char const* const viewportWindowName = db.tokenToString(db.inputs.viewport()); if (!omni::ui::Workspace::getWindow(viewportWindowName)) { db.logWarning("Viewport window '%s' not found", viewportWindowName); } // Process event payloads and update event state bool hoverBegan = false; for (auto const& hoverBeganPayload : state.m_internalState.eventPayloads.hoverBeganPayloads()) { if (!hoverBeganPayload.second.isValid) continue; auto& eventStateValue = state.m_internalState.eventStates[hoverBeganPayload.first]; eventStateValue.isHovered = true; if (std::strcmp(viewportWindowName, hoverBeganPayload.first.viewportWindowName) == 0) { hoverBegan = true; } } bool hoverEnded = false; for (auto const& hoverEndedPayload : state.m_internalState.eventPayloads.hoverEndedPayloads()) { if (!hoverEndedPayload.second.isValid) continue; auto& eventStateValue = state.m_internalState.eventStates[hoverEndedPayload.first]; if (eventStateValue.isHovered) { eventStateValue.isHovered = false; if (std::strcmp(viewportWindowName, hoverEndedPayload.first.viewportWindowName) == 0) { hoverEnded = true; } } } state.m_internalState.eventPayloads.clear(); // Get event state and set outputs auto it = state.m_internalState.eventStates.find({viewportWindowName}); if (it != state.m_internalState.eventStates.end()) { if (hoverEnded) { db.outputs.began() = kExecutionAttributeStateDisabled; db.outputs.ended() = kExecutionAttributeStateEnabled; } else if (hoverBegan) { db.outputs.began() = kExecutionAttributeStateEnabled; db.outputs.ended() = kExecutionAttributeStateDisabled; } else { db.outputs.began() = kExecutionAttributeStateDisabled; db.outputs.ended() = kExecutionAttributeStateDisabled; } } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
6,148
C++
34.959064
119
0.605563
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSlider.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.graph.core as og import omni.kit.app import omni.ui as ui from . import UINodeCommon class OgnSlider: @staticmethod def internal_state(): return UINodeCommon.OgnUINodeInternalState() @staticmethod def compute(db) -> bool: if db.inputs.create != og.ExecutionAttributeState.DISABLED: min_value = db.inputs.min max_value = db.inputs.max step = db.inputs.step if step <= 0: db.log_error("The step size of the slider must be positive!") return False width = db.inputs.width if width <= 0: db.log_error("The width of the slider must be positive!") return False widget_identifier = UINodeCommon.get_unique_widget_identifier(db) parent_widget = UINodeCommon.get_parent_widget(db) if parent_widget is None: return False # Tear down previously created widget if db.internal_state.created_widget is not None: UINodeCommon.tear_down_widget(db) def on_slider_finished_dragging(model): if not db.internal_state.created_widget.enabled: return message_bus = omni.kit.app.get_app().get_message_bus_event_stream() event_name = "value_changed_" + widget_identifier reg_event_name = UINodeCommon.registered_event_name(event_name) payload = {"newValue": model.get_value_as_float(), "valueType": "float"} message_bus.push(reg_event_name, payload=payload) # Now create the button widget and register callbacks with parent_widget: db.internal_state.created_frame = ui.Frame() with db.internal_state.created_frame: with ui.HStack(content_clipping=1): db.internal_state.created_widget = ui.FloatSlider( identifier=widget_identifier, width=width, min=min_value, max=max_value, step=step, ) db.internal_state.created_widget.model.set_value((min_value + max_value) / 2) db.internal_state.created_widget.model.add_end_edit_fn(on_slider_finished_dragging) db.outputs.created = og.ExecutionAttributeState.ENABLED db.outputs.widgetPath = UINodeCommon.find_widget_path(db.internal_state.created_widget) return True if db.inputs.tearDown != og.ExecutionAttributeState.DISABLED: return UINodeCommon.tear_down_widget(db) if db.inputs.show != og.ExecutionAttributeState.DISABLED: return UINodeCommon.show_widget(db) if db.inputs.hide != og.ExecutionAttributeState.DISABLED: return UINodeCommon.hide_widget(db) if db.inputs.enable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.enable_widget(db) if db.inputs.disable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.disable_widget(db) db.log_warning("Unexpected execution with no execution input enabled") return False
3,765
Python
39.063829
107
0.611155
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnComboBox.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.graph.core as og import omni.kit.app import omni.ui as ui from . import UINodeCommon class ComboBoxItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.model = ui.SimpleStringModel(text) class ComboBoxModel(ui.AbstractItemModel): def __init__(self, item_list): super().__init__() self._current_index = ui.SimpleIntModel(0) self._current_index.add_value_changed_fn(lambda index_model: self._item_changed(None)) self._items = [ComboBoxItem(text) for text in item_list] def get_item_children(self, item=None): return self._items def get_item_value_model(self, item=None, column_id=0): if item is None: return self._current_index return item.model class OgnComboBox: @staticmethod def internal_state(): return UINodeCommon.OgnUINodeInternalState() @staticmethod def compute(db) -> bool: if db.inputs.create != og.ExecutionAttributeState.DISABLED: item_list = db.inputs.itemList if not item_list: db.log_error("The combo box must have at least one item!") return False width = db.inputs.width if width <= 0: db.log_error("The width of the combo box must be positive!") return False widget_identifier = UINodeCommon.get_unique_widget_identifier(db) parent_widget = UINodeCommon.get_parent_widget(db) if parent_widget is None: return False # Tear down previously created widget if db.internal_state.created_widget is not None: UINodeCommon.tear_down_widget(db) def on_combox_box_item_changed(model, item): if not db.internal_state.created_widget.enabled: return current_index = model.get_item_value_model().as_int selected_child = model.get_item_children()[current_index] selected_value = model.get_item_value_model(selected_child).as_string message_bus = omni.kit.app.get_app().get_message_bus_event_stream() event_name = "value_changed_" + widget_identifier reg_event_name = UINodeCommon.registered_event_name(event_name) payload = {"newValue": selected_value, "valueType": "string"} message_bus.push(reg_event_name, payload=payload) # Now create the button widget and register callbacks with parent_widget: db.internal_state.created_frame = ui.Frame() with db.internal_state.created_frame: with ui.HStack(content_clipping=1): db.internal_state.created_widget = ui.ComboBox( ComboBoxModel(item_list), identifier=widget_identifier, width=width, ) db.internal_state.created_widget.model.add_item_changed_fn(on_combox_box_item_changed) db.outputs.created = og.ExecutionAttributeState.ENABLED db.outputs.widgetPath = UINodeCommon.find_widget_path(db.internal_state.created_widget) return True if db.inputs.tearDown != og.ExecutionAttributeState.DISABLED: return UINodeCommon.tear_down_widget(db) if db.inputs.show != og.ExecutionAttributeState.DISABLED: return UINodeCommon.show_widget(db) if db.inputs.hide != og.ExecutionAttributeState.DISABLED: return UINodeCommon.hide_widget(db) if db.inputs.enable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.enable_widget(db) if db.inputs.disable != og.ExecutionAttributeState.DISABLED: return UINodeCommon.disable_widget(db) db.log_warning("Unexpected execution with no execution input enabled") return False
4,440
Python
37.284482
110
0.625225
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnGetCameraPosition.cpp
// Copyright (c) 2021-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. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnGetCameraPositionDatabase.h> #include "CameraState.h" #include "NodeUtils.h" namespace omni { namespace graph { namespace ui { class OgnGetCameraPosition { public: static bool compute(OgnGetCameraPositionDatabase& db) { PXR_NS::UsdPrim prim = getPrimFromPathOrRelationship(db, OgnGetCameraPositionAttributes::inputs::prim.m_token); if (!prim) return false; auto camera = PXR_NS::UsdGeomCamera(prim); if (!camera) return true; CameraState cameraState(std::move(camera)); carb::Double3 position; cameraState.getCameraPosition(position); carb::Double3& positionAttrib = reinterpret_cast<carb::Double3&>(db.outputs.position()); positionAttrib = position; return true; } }; REGISTER_OGN_NODE() } } }
1,334
C++
23.272727
119
0.707646
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/UINodeCommon.h
// 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. // #include <omni/graph/core/ogn/UsdTypes.h> #include <carb/dictionary/IDictionary.h> #include <carb/events/EventsUtils.h> #include <carb/events/IEvents.h> #include <algorithm> #include <cstring> #include <map> #include <memory> #include <utility> namespace omni { namespace graph { namespace ui { /** * Checks if the node with `inputs:onlyPlayback` should be disabled, because playback is not happening. * * @param[in] db The node OGN Database object * @return true if the node should be disabled */ template<typename NodeDb> bool checkNodeDisabledForOnlyPlay(NodeDb const& db) { return db.inputs.onlyPlayback() && (not db.abi_context().iContext->getIsPlaying(db.abi_context())); } /** * Memoizes constant copies of C-strings to reduce heap allocation calls when passing equivalent C-strings between scopes. */ class StringMemo { public: /** * Finds or creates a constant copy of the input C-string having the same lifetime as this StringMemo object. * * @param[in] cstr A null-terminated C-style string * @return An equivalent constant C-style string */ char const* lookup(char const* cstr) { if (!cstr) return nullptr; auto it = m_map.find(cstr); if (it == m_map.end()) { std::unique_ptr<char const, cstr_deleter> cstr_copy {cstrdup(cstr)}; char const* cstr_copy_ptr = cstr_copy.get(); m_map.emplace(cstr_copy_ptr, std::move(cstr_copy)); return cstr_copy_ptr; } return it->first; } private: static char* cstrdup(const char *cstr) { std::size_t const len = std::strlen(cstr); char* new_copy = static_cast<char*>(std::malloc(len + 1)); if (!new_copy) return nullptr; std::memcpy(new_copy, cstr, len + 1); return new_copy; } struct cstr_cmp { bool operator()(char const* a, char const* b) const { return std::strcmp(a, b) < 0; } }; struct cstr_deleter{ void operator()(char const* p) const { std::free(const_cast<char*>(p)); } }; std::map<char const*, std::unique_ptr<char const, cstr_deleter>, cstr_cmp> m_map; }; } } }
2,688
C
25.106796
122
0.641369
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportPressNodeCommon.h
// 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. // #include "UINodeCommon.h" namespace omni { namespace graph { namespace ui { constexpr carb::events::EventType kPressBeganEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.press.began"); constexpr carb::events::EventType kPressEndedEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.press.ended"); class ViewportPressEventPayloads { public: struct Key { char const* viewportWindowName; char const* gestureName; bool operator<(Key const& other) const { int const ret = std::strcmp(viewportWindowName, other.viewportWindowName); if (ret < 0) return true; else if (ret <= 0) return std::strcmp(gestureName, other.gestureName) < 0; return false; } }; struct PressBeganValue { pxr::GfVec2d pressPositionNorm; pxr::GfVec2d pressPositionPixel; bool isValid; }; struct PressEndedValue { pxr::GfVec2d releasePositionNorm; pxr::GfVec2d releasePositionPixel; bool isReleasePositionValid; bool isValid; }; // Store a press began event payload void setPressBeganPayload(carb::dictionary::Item* payload) { auto idict = carb::dictionary::getCachedDictionaryInterface(); Key key { stringMemo.lookup(idict->get<char const*>(payload, "viewport")), stringMemo.lookup(idict->get<char const*>(payload, "gesture")) }; pressBeganPayloadMap[key] = PressBeganValue { pxr::GfVec2d { idict->get<double>(payload, "pos_norm_x"), idict->get<double>(payload, "pos_norm_y") }, pxr::GfVec2d { idict->get<double>(payload, "pos_pixel_x"), idict->get<double>(payload, "pos_pixel_y") }, true }; } // Store a press ended event payload void setPressEndedPayload(carb::dictionary::Item* payload) { auto idict = carb::dictionary::getCachedDictionaryInterface(); Key key { stringMemo.lookup(idict->get<char const*>(payload, "viewport")), stringMemo.lookup(idict->get<char const*>(payload, "gesture")) }; pressEndedPayloadMap[key] = PressEndedValue { pxr::GfVec2d { idict->get<double>(payload, "pos_norm_x"), idict->get<double>(payload, "pos_norm_y") }, pxr::GfVec2d { idict->get<double>(payload, "pos_pixel_x"), idict->get<double>(payload, "pos_pixel_y") }, idict->get<bool>(payload, "pos_valid"), true }; } // Invalidate all stored payloads void clear() { for (auto& p : pressBeganPayloadMap) { p.second.isValid = false; } for (auto& p : pressEndedPayloadMap) { p.second.isValid = false; } } bool empty() { if (std::any_of(pressBeganPayloadMap.begin(), pressBeganPayloadMap.end(), [](auto const& p) { return p.second.isValid; })) { return false; } if (std::any_of(pressEndedPayloadMap.begin(), pressEndedPayloadMap.end(), [](auto const& p) { return p.second.isValid; })) { return false; } return true; } std::map<Key, PressBeganValue> const& pressBeganPayloads() { return pressBeganPayloadMap; } std::map<Key, PressEndedValue> const& pressEndedPayloads() { return pressEndedPayloadMap; } private: std::map<Key, PressBeganValue> pressBeganPayloadMap; std::map<Key, PressEndedValue> pressEndedPayloadMap; StringMemo stringMemo; }; using ViewportPressEventStateKey = ViewportPressEventPayloads::Key; struct ViewportPressEventStateValue { pxr::GfVec2d pressPositionNorm = {0.0, 0.0}; pxr::GfVec2d pressPositionPixel = {0.0, 0.0}; pxr::GfVec2d releasePositionNorm = {0.0, 0.0}; pxr::GfVec2d releasePositionPixel = {0.0, 0.0}; bool isPressed = false; bool isReleasePositionValid = false; }; using ViewportPressEventStates = std::map<ViewportPressEventStateKey, ViewportPressEventStateValue>; } } }
4,796
C
27.553571
118
0.600292
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnWriteWidgetStyle.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.graph.core as og from . import UINodeCommon class OgnWriteWidgetStyle: @staticmethod def compute(db) -> bool: if db.inputs.write != og.ExecutionAttributeState.DISABLED: widget_path = db.inputs.widgetPath if not widget_path: widget_identifier = db.inputs.widgetIdentifier if not widget_identifier: db.log_warning("No widgetIdentifier or widgetPath provided.") return False widget = UINodeCommon.get_registered_widget(db.abi_context, widget_identifier) if not widget: db.log_warning(f"No widget with identifier '{widget_identifier}' found in this graph.") return False else: widget = UINodeCommon.find_widget_among_all_windows(widget_path) if not widget: db.log_warning(f"No widget found at path '{widget_path}'.") return False # For error messages only. widget_identifier = widget_path style_string = db.inputs.style if not style_string: db.log_error("No style provided.") return False style = {} try: style = UINodeCommon.to_ui_style(db.inputs.style) except SyntaxError as err: db.log_error(f"'inputs:style': {err.msg}") return False widget.set_style(style) db.outputs.written = og.ExecutionAttributeState.ENABLED return True db.log_warning("Unexpected execution with no execution input enabled") return False
2,150
Python
37.410714
107
0.607907
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportDragManipulator.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportDragManipulatorFactory"] from typing import Any import carb import omni.kit.app import omni.kit.commands from omni.ui import scene as sc EVENT_NAME_BEGAN = "omni.graph.viewport.drag.began" EVENT_NAME_CHANGED = "omni.graph.viewport.drag.changed" EVENT_NAME_ENDED = "omni.graph.viewport.drag.ended" GESTURE_NAMES = ["Left Mouse Drag", "Right Mouse Drag", "Middle Mouse Drag"] class DoNotPrevent(sc.GestureManager): def can_be_prevented(self, gesture): return False class ViewportDragGesture(sc.DragGesture): def __init__(self, viewport_api: Any, viewport_window_name: str, mouse_button: int): super().__init__(mouse_button=mouse_button, manager=DoNotPrevent()) self._viewport_api = viewport_api self._viewport_window_name = viewport_window_name self._gesture_name = GESTURE_NAMES[mouse_button] self._event_type_began = carb.events.type_from_string(EVENT_NAME_BEGAN) self._event_type_changed = carb.events.type_from_string(EVENT_NAME_CHANGED) self._event_type_ended = carb.events.type_from_string(EVENT_NAME_ENDED) self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream() self._start_pos_valid = False self._started_moving = False self._start_pos_norm = None self._start_pos_pixel = None def on_began(self): mouse = self.sender.gesture_payload.mouse resolution = self._viewport_api.resolution # Start position in normalized coords pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0] pos_norm = (pos_norm[0], 1.0 - pos_norm[1]) if not all(0.0 <= x <= 1.0 for x in pos_norm): self._start_pos_valid = False return # Start position in viewport resolution pixels pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1]) # Store start position and wait for on_changed to send self._start_pos_valid = True self._started_moving = False self._start_pos_norm = pos_norm self._start_pos_pixel = pos_pixel def on_changed(self): if not self._start_pos_valid: return mouse = self.sender.gesture_payload.mouse mouse_moved = self.sender.gesture_payload.mouse_moved resolution = self._viewport_api.resolution # Current position in normalized coords pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0] pos_norm = (pos_norm[0], 1.0 - pos_norm[1]) if not all(0.0 <= x <= 1.0 for x in pos_norm): return # Current position in viewport resolution pixels pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1]) # Velocity in normalized coords vel_norm = self._viewport_api.map_ndc_to_texture(mouse_moved)[0] origin_norm = self._viewport_api.map_ndc_to_texture((0, 0))[0] vel_norm = (vel_norm[0] - origin_norm[0], origin_norm[1] - vel_norm[1]) # Velocity in viewport resolution pixels vel_pixel = (vel_norm[0] * resolution[0], vel_norm[1] * resolution[1]) if not self._started_moving: payload = { "viewport": self._viewport_window_name, "gesture": self._gesture_name, "start_pos_norm_x": self._start_pos_norm[0], "start_pos_norm_y": self._start_pos_norm[1], "start_pos_pixel_x": self._start_pos_pixel[0], "start_pos_pixel_y": self._start_pos_pixel[1], "pos_norm_x": pos_norm[0], "pos_norm_y": pos_norm[1], "pos_pixel_x": pos_pixel[0], "pos_pixel_y": pos_pixel[1], "vel_norm_x": vel_norm[0], "vel_norm_y": vel_norm[1], "vel_pixel_x": vel_pixel[0], "vel_pixel_y": vel_pixel[1], } self._message_bus.push(self._event_type_began, payload=payload) self._started_moving = True else: payload = { "viewport": self._viewport_window_name, "gesture": self._gesture_name, "pos_norm_x": pos_norm[0], "pos_norm_y": pos_norm[1], "pos_pixel_x": pos_pixel[0], "pos_pixel_y": pos_pixel[1], "vel_norm_x": vel_norm[0], "vel_norm_y": vel_norm[1], "vel_pixel_x": vel_pixel[0], "vel_pixel_y": vel_pixel[1], } self._message_bus.push(self._event_type_changed, payload=payload) def on_ended(self): if self._start_pos_valid and self._started_moving: payload = { "viewport": self._viewport_window_name, "gesture": self._gesture_name, } self._message_bus.push(self._event_type_ended, payload=payload) self._start_pos_valid = False # Custom manipulator containing a Screen that contains the gestures class ViewportDragManipulator(sc.Manipulator): def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs): super().__init__(*args, **kwargs) self._gestures = [ ViewportDragGesture(viewport_api, viewport_window_name, 0), # left mouse drag ViewportDragGesture(viewport_api, viewport_window_name, 1), # right mouse drag ViewportDragGesture(viewport_api, viewport_window_name, 2), # middle mouse drag ] self._screen = None self._transform = None self.name = None self.categories = () def on_build(self): self._transform = sc.Transform() with self._transform: self._screen = sc.Screen(gesture=self._gestures) def destroy(self): self._gestures = [] self._screen = None if self._transform: self._transform.clear() self._transform = None # Factory creator def ViewportDragManipulatorFactory(desc: dict) -> ViewportDragManipulator: # noqa: N802 manip = ViewportDragManipulator(desc.get("viewport_api"), desc.get("viewport_window_name")) manip.categories = () manip.name = f"ViewportDragManipulator.{desc.get('viewport_window_name')}" return manip
6,711
Python
38.482353
95
0.60453
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadViewportPressState.cpp
// 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. // #include <OgnReadViewportPressStateDatabase.h> #include "ViewportPressNodeCommon.h" #include <omni/kit/IApp.h> #include <omni/ui/Workspace.h> namespace omni { namespace graph { namespace ui { class OgnReadViewportPressState { public: struct InternalState { carb::events::ISubscriptionPtr pressBeganSub; carb::events::ISubscriptionPtr pressEndedSub; ViewportPressEventPayloads eventPayloads; ViewportPressEventStates eventStates; } m_internalState; // Process event payloads and update event states immediately after receiving each payload static void updateEventStates(ViewportPressEventStates& eventStates, ViewportPressEventPayloads& eventPayloads) { for (auto const& pressBeganPayload : eventPayloads.pressBeganPayloads()) { if (!pressBeganPayload.second.isValid) continue; auto& eventStateValue = eventStates[pressBeganPayload.first]; eventStateValue.pressPositionNorm = pressBeganPayload.second.pressPositionNorm; eventStateValue.pressPositionPixel = pressBeganPayload.second.pressPositionPixel; eventStateValue.releasePositionNorm = {0.0, 0.0}; eventStateValue.releasePositionPixel = {0.0, 0.0}; eventStateValue.isPressed = true; eventStateValue.isReleasePositionValid = false; } for (auto const& pressEndedPayload : eventPayloads.pressEndedPayloads()) { if (!pressEndedPayload.second.isValid) continue; auto& eventStateValue = eventStates[pressEndedPayload.first]; if (eventStateValue.isPressed) { eventStateValue.releasePositionNorm = pressEndedPayload.second.releasePositionNorm; eventStateValue.releasePositionPixel = pressEndedPayload.second.releasePositionPixel; eventStateValue.isPressed = false; eventStateValue.isReleasePositionValid = pressEndedPayload.second.isReleasePositionValid; } } eventPayloads.clear(); } static void initialize(GraphContextObj const&, NodeObj const& nodeObj) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sm_stateManagerOgnReadViewportPressState .getState<OgnReadViewportPressState>(nodeObj.nodeHandle); // Subscribe to press events if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>()) { state.m_internalState.pressBeganSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kPressBeganEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sm_stateManagerOgnReadViewportPressState .getState<OgnReadViewportPressState>(nodeObj.nodeHandle); state.m_internalState.eventPayloads.setPressBeganPayload(e->payload); updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads); } } ); state.m_internalState.pressEndedSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kPressEndedEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sm_stateManagerOgnReadViewportPressState .getState<OgnReadViewportPressState>(nodeObj.nodeHandle); state.m_internalState.eventPayloads.setPressEndedPayload(e->payload); updateEventStates(state.m_internalState.eventStates, state.m_internalState.eventPayloads); } } ); } } static void release(const NodeObj& nodeObj) { OgnReadViewportPressState& state = OgnReadViewportPressStateDatabase::sm_stateManagerOgnReadViewportPressState .getState<OgnReadViewportPressState>(nodeObj.nodeHandle); // Unsubscribe from press events if (state.m_internalState.pressBeganSub.get()) state.m_internalState.pressBeganSub.detach()->unsubscribe(); if (state.m_internalState.pressEndedSub.get()) state.m_internalState.pressEndedSub.detach()->unsubscribe(); } static bool compute(OgnReadViewportPressStateDatabase& db) { OgnReadViewportPressState& state = db.internalState<OgnReadViewportPressState>(); // Get the targeted viewport and gesture char const* const viewportWindowName = db.tokenToString(db.inputs.viewport()); char const* const gestureName = db.tokenToString(db.inputs.gesture()); if (!omni::ui::Workspace::getWindow(viewportWindowName)) { db.logWarning("Viewport window '%s' not found", viewportWindowName); } // Output press state auto it = state.m_internalState.eventStates.find({viewportWindowName, gestureName}); if (it != state.m_internalState.eventStates.end()) { if (db.inputs.useNormalizedCoords()) { db.outputs.pressPosition() = it->second.pressPositionNorm; db.outputs.releasePosition() = it->second.releasePositionNorm; } else { db.outputs.pressPosition() = it->second.pressPositionPixel; db.outputs.releasePosition() = it->second.releasePositionPixel; } db.outputs.isReleasePositionValid() = it->second.isReleasePositionValid; db.outputs.isPressed() = it->second.isPressed; db.outputs.isValid() = true; } else { db.outputs.pressPosition() = {0.0, 0.0}; db.outputs.releasePosition() = {0.0, 0.0}; db.outputs.isReleasePositionValid() = false; db.outputs.isPressed() = false; db.outputs.isValid() = false; } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
6,811
C++
37.925714
134
0.639554
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportClickNodeCommon.h
// 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. // #include "UINodeCommon.h" namespace omni { namespace graph { namespace ui { constexpr carb::events::EventType kClickEventType = CARB_EVENTS_TYPE_FROM_STR("omni.graph.viewport.click"); class ViewportClickEventPayloads { public: struct Key { char const* viewportWindowName; char const* gestureName; bool operator<(Key const& other) const { int const ret = std::strcmp(viewportWindowName, other.viewportWindowName); if (ret < 0) return true; else if (ret <= 0) return std::strcmp(gestureName, other.gestureName) < 0; return false; } }; struct Value { pxr::GfVec2d positionNorm; pxr::GfVec2d positionPixel; bool isValid; }; // Store an event payload as a key-value pair void setPayload(carb::dictionary::Item* payload) { auto idict = carb::dictionary::getCachedDictionaryInterface(); Key key { stringMemo.lookup(idict->get<char const*>(payload, "viewport")), stringMemo.lookup(idict->get<char const*>(payload, "gesture")) }; payloadMap[key] = Value { pxr::GfVec2d { idict->get<double>(payload, "pos_norm_x"), idict->get<double>(payload, "pos_norm_y") }, pxr::GfVec2d { idict->get<double>(payload, "pos_pixel_x"), idict->get<double>(payload, "pos_pixel_y") }, true }; } // Retrieve a payload value by key Value const* getPayloadValue(char const* viewportWindowName, char const* gestureName) { auto it = payloadMap.find({viewportWindowName, gestureName}); if (it != payloadMap.end() && it->second.isValid) { return &(it->second); } return nullptr; } // Invalidate all stored payloads void clear() { for (auto& p : payloadMap) { p.second.isValid = false; } } // Check if there exists a valid payload bool empty() { return std::none_of(payloadMap.begin(), payloadMap.end(), [](auto const& p) { return p.second.isValid; }); } private: std::map<Key, Value> payloadMap; StringMemo stringMemo; }; } } }
2,797
C
25.149532
107
0.58956
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/PickingManipulator.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["PickingManipulatorFactory"] from typing import Any, List, Optional import carb import omni.kit.app import omni.kit.commands from omni.ui import scene as sc EVENT_NAME = "omni.graph.picking" CLICK_GESTURE_NAMES = ["Left Mouse Click", "Right Mouse Click", "Middle Mouse Click"] PRESS_GESTURE_NAMES = ["Left Mouse Press", "Right Mouse Press", "Middle Mouse Press"] SEQ_LIMIT = 128 class DoNotPrevent(sc.GestureManager): def can_be_prevented(self, gesture): return False # Custom gesture that triggers a picking query on mouse press, and sends the result on both mouse press and end of click class PickingGesture(sc.DragGesture): def __init__(self, viewport_api: Any, viewport_window_name: str, mouse_button: int): super().__init__(mouse_button=mouse_button, manager=DoNotPrevent()) self._viewport_api = viewport_api self._viewport_window_name = viewport_window_name self._click_gesture_name = CLICK_GESTURE_NAMES[mouse_button] self._press_gesture_name = PRESS_GESTURE_NAMES[mouse_button] self._event_type = carb.events.type_from_string(EVENT_NAME) self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream() # Sequence number for associating picking queries with gestures self._seq = 0 # Bool to track whether the mouse button was initially pressed over the 3D viewport or not # (does not need to be an array like the rest since _query_completed does not need to check it) self._began = False # Sequence number indexed bools to control the following execution order cases for mouse click: # 1: on_began -> _query_completed -> on_ended # 2: on_began -> _query_completed -> on_changed (cancelled) -> on_ended # 3: on_began -> on_ended -> _query_completed # 4: on_began -> on_changed (cancelled) -> _query_completed -> on_ended # 5: on_began -> on_changed (cancelled) -> on_ended -> _query_completed self._ended = [False] * SEQ_LIMIT # True if the mouse button has been released without moving the mouse self._cancelled = [False] * SEQ_LIMIT # True if the mouse was moved while pressed, cancelling the click self._result_stored = [False] * SEQ_LIMIT # True if the picking query has completed and stored its result # Sequence number indexed temporary buffers to hold the picking result self._picked_prim_path = [None] * SEQ_LIMIT self._world_space_pos = [None] * SEQ_LIMIT # Callback to request_query called when the picking query completes def _query_completed(self, seq: int, picked_prim_path: str, world_space_pos: Optional[List[float]], *args): # Handle mouse press: # Send the picked prim path and picked world position in an event payload # Include the viewport window name and gesture name to filter on the receiving end press_payload = { "viewport": self._viewport_window_name, "gesture": self._press_gesture_name, "path": picked_prim_path, "pos_x": world_space_pos[0] if world_space_pos else 0.0, "pos_y": world_space_pos[1] if world_space_pos else 0.0, "pos_z": world_space_pos[2] if world_space_pos else 0.0, } self._message_bus.push(self._event_type, payload=press_payload) # Handle cases for mouse click if self._cancelled[seq]: return if self._ended[seq]: # Case 3: Click has already ended and we were waiting on the query to complete, so send the payload now click_payload = { "viewport": self._viewport_window_name, "gesture": self._click_gesture_name, "path": picked_prim_path, "pos_x": world_space_pos[0] if world_space_pos else 0.0, "pos_y": world_space_pos[1] if world_space_pos else 0.0, "pos_z": world_space_pos[2] if world_space_pos else 0.0, } self._message_bus.push(self._event_type, payload=click_payload) else: # Case 1 or 2: Click has not completed yet, so save the picking result and wait until mouse is released self._picked_prim_path[seq] = picked_prim_path self._world_space_pos[seq] = world_space_pos self._result_stored[seq] = True def _query_completed_seq(self, seq: int): return lambda *args: self._query_completed(seq, *args) # Called when the specified mouse button is pressed def on_began(self): # Get the next sequence number and reset the control bools self._seq = (self._seq + 1) % SEQ_LIMIT self._began = False self._ended[self._seq] = False self._cancelled[self._seq] = False self._result_stored[self._seq] = False self._picked_prim_path[self._seq] = None self._world_space_pos[self._seq] = None # Get the mouse position in normalized coords and check if the mouse is actually over the 3D viewport mouse = self.sender.gesture_payload.mouse resolution = self._viewport_api.resolution pos_norm, _ = self._viewport_api.map_ndc_to_texture(mouse) if pos_norm is None or not all(0.0 <= x <= 1.0 for x in pos_norm): return self._began = True # Get the mouse position in viewport resolution pixels and request a picking query pos_pixel = (int(pos_norm[0] * resolution[0]), int((1.0 - pos_norm[1]) * resolution[1])) self._viewport_api.request_query( pos_pixel, self._query_completed_seq(self._seq), query_name=f"omni.graph.ui.nodes.PickingManipulator.{id(self)}", ) # Called when the mouse is moved while pressed, cancelling the click def on_changed(self): if not self._began: return self._cancelled[self._seq] = True # Called when the specified mouse button is released def on_ended(self): if not self._began or self._cancelled[self._seq]: return if self._result_stored[self._seq]: # Case 1: The picking query has already completed and we have the result saved, so send the payload now picked_prim_path = self._picked_prim_path[self._seq] world_space_pos = self._world_space_pos[self._seq] click_payload = { "viewport": self._viewport_window_name, "gesture": self._click_gesture_name, "path": picked_prim_path, "pos_x": world_space_pos[0] if world_space_pos else 0.0, "pos_y": world_space_pos[1] if world_space_pos else 0.0, "pos_z": world_space_pos[2] if world_space_pos else 0.0, } self._message_bus.push(self._event_type, payload=click_payload) else: # Case 3: The picking query has not completed yet, so wait until it completes to send the payload self._ended[self._seq] = True # Custom manipulator containing a screen that contains the gestures class PickingManipulator(sc.Manipulator): def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs): super().__init__(*args, **kwargs) self._gestures = [ PickingGesture(viewport_api, viewport_window_name, 0), # left mouse click/press PickingGesture(viewport_api, viewport_window_name, 1), # right mouse click/press PickingGesture(viewport_api, viewport_window_name, 2), # middle mouse click/press ] self._screen = None self._transform = None self.name = None self.categories = () def on_build(self): # Create a transform and put a screen in it (must hold a reference to keep the sc.Screen alive) self._transform = sc.Transform() with self._transform: # sc.Screen is an invisible rectangle that is always in front of and entirely covers the viewport camera # By attaching the gestures to this screen, the gestures can be triggered by clicking anywhere self._screen = sc.Screen(gesture=self._gestures) def destroy(self): self._gestures = [] self._screen = None if self._transform: self._transform.clear() self._transform = None # Factory creator def PickingManipulatorFactory(desc: dict) -> PickingManipulator: # noqa: N802 manip = PickingManipulator(desc.get("viewport_api"), desc.get("viewport_window_name")) manip.categories = () manip.name = f"PickingManipulator.{desc.get('viewport_window_name')}" return manip
9,093
Python
45.397959
120
0.638953
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSetCameraPosition.cpp
// Copyright (c) 2021-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. // // clang-format off #include "UsdPCH.h" // clang-format on #include <OgnSetCameraPositionDatabase.h> #include "CameraState.h" #include "NodeUtils.h" #include <pxr/base/gf/vec3d.h> namespace omni { namespace graph { namespace ui { class OgnSetCameraPosition { public: static bool compute(OgnSetCameraPositionDatabase& db) { PXR_NS::UsdPrim prim = getPrimFromPathOrRelationship(db, OgnSetCameraPositionAttributes::inputs::prim.m_token); if (!prim) return false; auto position = db.inputs.position(); auto rotate = db.inputs.rotate(); auto camera = PXR_NS::UsdGeomCamera(prim); if (!camera) return false; CameraState cameraState(std::move(camera)); bool ok = cameraState.setCameraPosition({ position[0], position[1], position[2] }, rotate); if (!ok) { db.logError("Could not set position for camera %s", prim.GetPath().GetText()); } db.outputs.execOut() = kExecutionAttributeStateEnabled; return true; } }; REGISTER_OGN_NODE() } } }
1,535
C++
23.774193
119
0.683388
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnReadViewportScrollState.cpp
// 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. // #include <OgnReadViewportScrollStateDatabase.h> #include "ViewportScrollNodeCommon.h" #include <omni/kit/IApp.h> #include <omni/ui/Workspace.h> namespace omni { namespace graph { namespace ui { class OgnReadViewportScrollState { public: struct InternalState { carb::events::ISubscriptionPtr scrollSub; ViewportScrollEventPayloads eventPayloads; } m_internalState; static void initialize(GraphContextObj const& context, NodeObj const& nodeObj) { OgnReadViewportScrollState& state = OgnReadViewportScrollStateDatabase::sm_stateManagerOgnReadViewportScrollState .getState<OgnReadViewportScrollState>(nodeObj.nodeHandle); // Subscribe to scroll events if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>()) { state.m_internalState.scrollSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kScrollEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnReadViewportScrollState& state = OgnReadViewportScrollStateDatabase::sm_stateManagerOgnReadViewportScrollState .getState<OgnReadViewportScrollState>(nodeObj.nodeHandle); state.m_internalState.eventPayloads.setPayload(e->payload); } } ); } } static void release(const NodeObj& nodeObj) { OgnReadViewportScrollState& state = OgnReadViewportScrollStateDatabase::sm_stateManagerOgnReadViewportScrollState .getState<OgnReadViewportScrollState>(nodeObj.nodeHandle); // Unsubscribe from scroll events if (state.m_internalState.scrollSub.get()) state.m_internalState.scrollSub.detach()->unsubscribe(); } static bool compute(OgnReadViewportScrollStateDatabase& db) { OgnReadViewportScrollState& state = db.internalState<OgnReadViewportScrollState>(); // Get the targeted viewport and gesture char const* const viewportWindowName = db.tokenToString(db.inputs.viewport()); if (!omni::ui::Workspace::getWindow(viewportWindowName)) { db.logWarning("Viewport window '%s' not found", viewportWindowName); } auto const* eventPayloadValuePtr = state.m_internalState.eventPayloads.getPayloadValue(viewportWindowName); if (eventPayloadValuePtr) { db.outputs.scrollValue() = eventPayloadValuePtr->scrollValue; db.outputs.position() = db.inputs.useNormalizedCoords() ? eventPayloadValuePtr->positionNorm : eventPayloadValuePtr->positionPixel; db.outputs.isValid() = true; } else { db.outputs.scrollValue() = 0.0f; db.outputs.position() = {0.0, 0.0}; db.outputs.isValid() = false; } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
3,478
C++
34.141414
143
0.660725
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnWidgetValueChanged.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 contextlib import suppress import omni.graph.core as og from omni.graph.ui.ogn.OgnOnWidgetValueChangedDatabase import OgnOnWidgetValueChangedDatabase from . import UINodeCommon class OgnOnWidgetValueChanged: @staticmethod def try_resolve_output_attribute(node, attr_name, attr_type): out_attr = node.get_attribute(attr_name) attr_type_valid = attr_type.base_type != og.BaseDataType.UNKNOWN if out_attr.get_resolved_type().base_type != og.BaseDataType.UNKNOWN and ( not attr_type_valid or attr_type != out_attr.get_resolved_type() ): out_attr.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN)) if attr_type_valid and out_attr.get_resolved_type().base_type == og.BaseDataType.UNKNOWN: out_attr.set_resolved_type(attr_type) @staticmethod def internal_state(): return UINodeCommon.OgnUIEventNodeInternalState() @staticmethod def compute(db) -> bool: widget_identifier = db.inputs.widgetIdentifier if not widget_identifier: return True event_name = "value_changed_" + widget_identifier if db.internal_state.first_time_subscribe(db.node, event_name): return True payload = db.internal_state.try_pop_event() if payload is None: return True if "valueType" in payload.get_keys(): value_type = payload["valueType"] OgnOnWidgetValueChanged.try_resolve_output_attribute( db.node, "outputs:newValue", og.AttributeType.type_from_ogn_type_name(value_type) ) if "newValue" in payload.get_keys(): new_value = payload["newValue"] db.outputs.newValue = new_value db.outputs.valueChanged = og.ExecutionAttributeState.ENABLED return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnWidgetValueChangedDatabase.per_node_internal_state(node) state.release()
2,689
Python
35.849315
101
0.6627
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnDrawDebugCurve.py
""" This is the implementation of the OGN node defined in OgnDrawDebugCurve.ogn """ import carb import numpy as np import omni.debugdraw as dd import omni.graph.core as og class OgnDrawDebugCurve: """ Draws a curve using omni.debugdraw """ @staticmethod def compute(db) -> bool: """Compute the outputs from the current input""" curvepoints = db.inputs.curvepoints color = db.inputs.color closed = db.inputs.closed try: ddi = dd._debugDraw.acquire_debug_draw_interface() # noqa: PLW0212 rgb_bytes = (np.clip(color, 0, 1.0) * 255).astype("uint8").tobytes() argb_bytes = b"\xff" + rgb_bytes argb = int.from_bytes(argb_bytes, byteorder="big") carbpoints = [carb.Float3(p.tolist()) for p in curvepoints] # carb.log_warn(f'{color} = {argb_bytes} = {argb}, {carbpoints[0]}, {carbpoints[1]}') for i in range(len(carbpoints) - 1): ddi.draw_line(carbpoints[i], argb, carbpoints[i + 1], argb) if closed: ddi.draw_line(carbpoints[-1], argb, carbpoints[0], argb) except Exception as error: # noqa: PLW0703 import traceback raise RuntimeError(traceback.format_exc()) from error db.outputs.execOut = og.ExecutionAttributeState.ENABLED return True
1,376
Python
33.424999
97
0.606105
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnNewFrame.py
""" This is the implementation of the OGN node defined in OgnOnNewFrame.ogn """ from contextlib import suppress import omni.graph.core as og import omni.usd from omni.graph.ui.ogn.OgnOnNewFrameDatabase import OgnOnNewFrameDatabase from omni.kit.viewport.utility import get_viewport_from_window_name class OgnOnNewFrameInternalState: """Convenience class for maintaining per-node state information""" def __init__(self): """Instantiate the per-node state information.""" # This subscription object controls the lifetime of our callback, it will be # cleaned up automatically when our node is destroyed self.sub = None # Set when the callback has triggered self.is_set = False # The last payload received self.payload = None # The node instance handle self.node = None # The viewport we are watching frames for self.viewport_handle = None def on_event(self, e): """The event callback""" if e is None: return self.is_set = True viewport_handle = e.payload["viewport_handle"] if viewport_handle != self.viewport_handle: return self.payload = e.payload # Tell the evaluator we need to be computed if self.node.is_valid(): self.node.request_compute() def first_time_subscribe(self, node: og.Node, viewport_handle: int) -> bool: """Checked call to set up carb subscription Args: node: The node instance viewport_handle: The handle for the viewport to watch Returns: True if we subscribed, False if we are already subscribed """ if self.sub is not None and self.viewport_handle != viewport_handle: # event name changed since we last subscribed, unsubscribe self.sub.unsubscribe() self.sub = None if self.sub is None: self.sub = ( omni.usd.get_context() .get_rendering_event_stream() .create_subscription_to_push_by_type( int(omni.usd.StageRenderingEventType.NEW_FRAME), self.on_event, name=f"omni.graph.action.__on_new_frame.{node.node_id()}", ) ) self.viewport_handle = viewport_handle self.node = node self.payload = None return True return False def try_pop_event(self): """Pop the payload of the last event received, or None if there is no event to pop""" if self.is_set: self.is_set = False payload = self.payload self.payload = None return payload return None # ====================================================================== class OgnOnNewFrame: @staticmethod def internal_state(): """Returns an object that will contain per-node state information""" return OgnOnNewFrameInternalState() @staticmethod def compute(db) -> bool: viewport_name = db.inputs.viewport viewport_api = get_viewport_from_window_name(viewport_name) if not viewport_api: return True state = db.internal_state # XXX: Note this may be incorrect, viewport_handle is not stable (and may be None) viewport_handle = viewport_api.frame_info.get("viewport_handle") if state.first_time_subscribe(db.node, viewport_handle): return True payload = state.try_pop_event() if payload is None: return True # Copy the event dict contents into the output bundle db.outputs.frameNumber = payload["frame_number"] db.outputs.execOut = og.ExecutionAttributeState.ENABLED return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnNewFrameDatabase.per_node_internal_state(node) if state.sub: state.sub.unsubscribe() state.sub = None
4,326
Python
33.34127
101
0.587379
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnSetViewportMode.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 dataclasses import dataclass from threading import Lock from typing import Any, Callable, Dict, Optional import omni.graph.core as og import omni.ui as ui from omni.graph.ui.ogn.OgnSetViewportModeDatabase import OgnSetViewportModeDatabase from omni.kit.viewport.utility import get_active_viewport_and_window from omni.ui import scene as sc from omni.ui_query import OmniUIQuery from .OgnVStack import OgnVStack # noqa: PLE0402 from .PickingManipulator import PickingManipulatorFactory # noqa: PLE0402 from .ViewportClickManipulator import ViewportClickManipulatorFactory # noqa: PLE0402 from .ViewportDragManipulator import ViewportDragManipulatorFactory # noqa: PLE0402 from .ViewportHoverManipulator import ViewportHoverManipulatorFactory # noqa: PLE0402 from .ViewportPressManipulator import ViewportPressManipulatorFactory # noqa: PLE0402 from .ViewportScrollManipulator import ViewportScrollManipulatorFactory # noqa: PLE0402 UI_FRAME_NAME = "omni.graph.SetViewportMode" VIEWPORT_OVERLAY_NAME = "OG_overlay" IS_LOCK_REQUIRED = True class NoLock: def __init__(self): pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass class OgnSetViewportMode: @dataclass class ViewportState: viewport_click_manipulator: Optional[Any] = None viewport_press_manipulator: Optional[Any] = None viewport_drag_manipulator: Optional[Any] = None viewport_hover_manipulator: Optional[Any] = None viewport_scroll_manipulator: Optional[Any] = None picking_manipulator: Optional[Any] = None __viewport_states: Dict[str, ViewportState] = {} __do_it_lock: Optional[Any] = Lock() if IS_LOCK_REQUIRED else NoLock() @staticmethod def compute(db) -> bool: if db.inputs.execIn == og.ExecutionAttributeState.DISABLED: return False with OgnSetViewportMode.__do_it_lock: result = OgnSetViewportMode.__do_it( db.inputs.mode, db.inputs.viewport, db.abi_context, db.outputs, db.log_error, db.inputs.enableViewportMouseEvents, db.inputs.enablePicking, ) if result: if db.inputs.mode == 0: db.outputs.defaultMode = og.ExecutionAttributeState.ENABLED db.outputs.scriptedMode = og.ExecutionAttributeState.DISABLED elif db.inputs.mode == 1: db.outputs.defaultMode = og.ExecutionAttributeState.DISABLED db.outputs.scriptedMode = og.ExecutionAttributeState.ENABLED return True db.outputs.defaultMode = og.ExecutionAttributeState.DISABLED db.outputs.scriptedMode = og.ExecutionAttributeState.DISABLED return False @staticmethod def __do_it( mode: int, viewport_window_name: str, context: og.GraphContext, outputs: OgnSetViewportModeDatabase.ValuesForOutputs, log_fn: Optional[Callable], viewport_mouse_events_enabled: bool, picking_enabled: bool, ) -> bool: # Validate the viewport window name if not viewport_window_name: if log_fn is not None: log_fn(f"Viewport window '{viewport_window_name}' not found") return False viewport_api, viewport_window = get_active_viewport_and_window(window_name=viewport_window_name) if viewport_window is None: if log_fn is not None: log_fn(f"Viewport window '{viewport_window_name}' not found") return False if hasattr(viewport_api, "legacy_window"): if log_fn is not None: log_fn(f"Legacy viewport window '{viewport_window_name}' not compatible with Set Viewport Mode") return False # Default mode if mode == 0: # Destroy the manipulators OgnSetViewportMode.__viewport_states[viewport_window_name] = OgnSetViewportMode.__viewport_states.get( viewport_window_name, OgnSetViewportMode.ViewportState() ) viewport_state = OgnSetViewportMode.__viewport_states[viewport_window_name] if viewport_state.viewport_click_manipulator is not None: viewport_state.viewport_click_manipulator.destroy() viewport_state.viewport_click_manipulator = None if viewport_state.viewport_press_manipulator is not None: viewport_state.viewport_press_manipulator.destroy() viewport_state.viewport_press_manipulator = None if viewport_state.viewport_drag_manipulator is not None: viewport_state.viewport_drag_manipulator.destroy() viewport_state.viewport_drag_manipulator = None if viewport_state.viewport_hover_manipulator is not None: viewport_state.viewport_hover_manipulator.destroy() viewport_state.viewport_hover_manipulator = None if viewport_state.viewport_scroll_manipulator is not None: viewport_state.viewport_scroll_manipulator.destroy() viewport_state.viewport_scroll_manipulator = None if viewport_state.picking_manipulator is not None: viewport_state.picking_manipulator.destroy() viewport_state.picking_manipulator = None # Destroy the ui.ZStack and sc.SceneView if they exist frame = viewport_window.get_frame(UI_FRAME_NAME) frame_children = ui.Inspector.get_children(frame) if frame_children: widget_container = frame_children[0] widget_container_children = ui.Inspector.get_children(widget_container) if widget_container_children: scene_view = widget_container_children[0] viewport_api.remove_scene_view(scene_view) scene_view.scene.clear() scene_view.destroy() OgnVStack.deregister_widget(context, VIEWPORT_OVERLAY_NAME) widget_container.destroy() frame.clear() # Clear output widget path outputs.widgetPath = "" # Scripted mode elif mode == 1: # Create the ui.ZStack and sc.SceneView if they don't exist frame = viewport_window.get_frame(UI_FRAME_NAME) frame_children = ui.Inspector.get_children(frame) if frame_children: widget_container = frame_children[0] else: with frame: widget_container = ui.ZStack(identifier=VIEWPORT_OVERLAY_NAME, content_clipping=1) # Register the container widget so that graphs can access its properties, like size. OgnVStack.register_widget(context, VIEWPORT_OVERLAY_NAME, widget_container) widget_container_children = ui.Inspector.get_children(widget_container) if widget_container_children: scene_view = widget_container_children[0] else: with widget_container: scene_view = sc.SceneView(child_windows_input=0) viewport_api.add_scene_view(scene_view) # Destroy any existing manipulators and create the enabled manipulators OgnSetViewportMode.__viewport_states[viewport_window_name] = OgnSetViewportMode.__viewport_states.get( viewport_window_name, OgnSetViewportMode.ViewportState() ) viewport_state = OgnSetViewportMode.__viewport_states[viewport_window_name] if viewport_state.viewport_click_manipulator is not None: viewport_state.viewport_click_manipulator.destroy() viewport_state.viewport_click_manipulator = None if viewport_state.viewport_press_manipulator is not None: viewport_state.viewport_press_manipulator.destroy() viewport_state.viewport_press_manipulator = None if viewport_state.viewport_drag_manipulator is not None: viewport_state.viewport_drag_manipulator.destroy() viewport_state.viewport_drag_manipulator = None if viewport_state.viewport_hover_manipulator is not None: viewport_state.viewport_hover_manipulator.destroy() viewport_state.viewport_hover_manipulator = None if viewport_state.viewport_scroll_manipulator is not None: viewport_state.viewport_scroll_manipulator.destroy() viewport_state.viewport_scroll_manipulator = None if viewport_state.picking_manipulator is not None: viewport_state.picking_manipulator.destroy() viewport_state.picking_manipulator = None with scene_view.scene: if viewport_mouse_events_enabled: viewport_state.viewport_click_manipulator = ViewportClickManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_press_manipulator = ViewportPressManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_drag_manipulator = ViewportDragManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_hover_manipulator = ViewportHoverManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) viewport_state.viewport_scroll_manipulator = ViewportScrollManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) if picking_enabled: viewport_state.picking_manipulator = PickingManipulatorFactory( {"viewport_api": viewport_api, "viewport_window_name": viewport_window_name} ) # Set output widget path outputs.widgetPath = OmniUIQuery.get_widget_path(viewport_window, widget_container) return True
10,946
Python
42.963855
114
0.638589
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/ViewportScrollManipulator.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportScrollManipulatorFactory"] from typing import Any import carb import omni.kit.app import omni.kit.commands from omni.ui import scene as sc EVENT_NAME = "omni.graph.viewport.scroll" class DoNotPrevent(sc.GestureManager): def can_be_prevented(self, gesture): return False class ViewportScrollGesture(sc.ScrollGesture): def __init__(self, viewport_api: Any, viewport_window_name: str): super().__init__(manager=DoNotPrevent()) self._viewport_api = viewport_api self._viewport_window_name = viewport_window_name self._event_type = carb.events.type_from_string(EVENT_NAME) self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream() def on_ended(self, *args): mouse = self.sender.gesture_payload.mouse resolution = self._viewport_api.resolution # Position in normalized coords pos_norm = self._viewport_api.map_ndc_to_texture(mouse)[0] pos_norm = (pos_norm[0], 1.0 - pos_norm[1]) if not all(0.0 <= x <= 1.0 for x in pos_norm): return # Position in viewport resolution pixels pos_pixel = (pos_norm[0] * resolution[0], pos_norm[1] * resolution[1]) payload = { "viewport": self._viewport_window_name, "pos_norm_x": pos_norm[0], "pos_norm_y": pos_norm[1], "pos_pixel_x": pos_pixel[0], "pos_pixel_y": pos_pixel[1], "scroll": self.scroll[0], } self._message_bus.push(self._event_type, payload=payload) class ViewportScrollManipulator(sc.Manipulator): def __init__(self, viewport_api: Any, viewport_window_name: str, *args, **kwargs): super().__init__(*args, **kwargs) self._gestures = [ViewportScrollGesture(viewport_api, viewport_window_name)] self._screen = None self._transform = None self.name = None self.categories = () def on_build(self): self._transform = sc.Transform() with self._transform: self._screen = sc.Screen(gesture=self._gestures) def destroy(self): self._gestures = [] self._screen = None if self._transform: self._transform.clear() self._transform = None # Factory creator def ViewportScrollManipulatorFactory(desc: dict) -> ViewportScrollManipulator: # noqa: N802 manip = ViewportScrollManipulator(desc.get("viewport_api"), desc.get("viewport_window_name")) manip.categories = () manip.name = f"ViewportScrollManipulator.{desc.get('viewport_window_name')}" return manip
3,047
Python
33.636363
97
0.65146
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnWidgetClicked.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 contextlib import suppress import omni.graph.core as og from omni.graph.ui.ogn.OgnOnWidgetClickedDatabase import OgnOnWidgetClickedDatabase from . import UINodeCommon class OgnOnWidgetClicked: @staticmethod def internal_state(): return UINodeCommon.OgnUIEventNodeInternalState() @staticmethod def compute(db) -> bool: widget_identifier = db.inputs.widgetIdentifier if not widget_identifier: return True event_name = "clicked_" + widget_identifier if db.internal_state.first_time_subscribe(db.node, event_name): return True payload = db.internal_state.try_pop_event() if payload is None: return True # Currently payload is an empty dictionary db.outputs.clicked = og.ExecutionAttributeState.ENABLED return True # ---------------------------------------------------------------------------- @staticmethod def release(node): # Unsubscribe right away instead of waiting for GC cleanup, we don't want our callback firing # after the node has been released. with suppress(og.OmniGraphError): state = OgnOnWidgetClickedDatabase.per_node_internal_state(node) state.release()
1,703
Python
32.411764
101
0.678802
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/CameraState.cpp
// 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. // #include "CameraState.h" #include <carb/settings/ISettings.h> #include <omni/timeline/ITimeline.h> #include <omni/usd/UsdUtils.h> using namespace omni::graph::ui; static const PXR_NS::TfToken kCenterOfInterest("omni:kit:centerOfInterest"); static bool checkPositionAndTarget(const PXR_NS::GfVec3d& position, const PXR_NS::GfVec3d& target) { // If position and target are coincident, fail if ((position - target).GetLengthSq() <= std::numeric_limits<double>::epsilon()) { return false; } return true; } static PXR_NS::GfVec3d getCameraUp(PXR_NS::UsdStageRefPtr stage) { PXR_NS::TfToken upAxis = PXR_NS::UsdGeomGetStageUpAxis(stage); if (upAxis == PXR_NS::UsdGeomTokens->x) { return { 1, 0, 0 }; } if (upAxis == PXR_NS::UsdGeomTokens->z) { return { 0, 0, 1 }; } return { 0, 1, 0 }; } CameraState::CameraState(PXR_NS::UsdGeomCamera camera, const PXR_NS::UsdTimeCode* time) : m_camera(std::move(camera)) , m_timeCode(time ? *time : omni::timeline::getTimeline()->getCurrentTime() * m_camera.GetPrim().GetStage()->GetTimeCodesPerSecond()) { } void CameraState::getCameraPosition(carb::Double3& position) const { PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfVec3d worldPos = worldXform.Transform(PXR_NS::GfVec3d(0, 0, 0)); position = { worldPos[0], worldPos[1], worldPos[2] }; } void CameraState::getCameraTarget(carb::Double3& target) const { PXR_NS::GfVec3d localCenterOfInterest; PXR_NS::UsdAttribute coiAttr = m_camera.GetPrim().GetAttribute(kCenterOfInterest); if (!coiAttr || !coiAttr.Get(&localCenterOfInterest, m_timeCode)) { localCenterOfInterest = { 0, 0, -1 }; } PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfVec3d worldCenterOfInterest = worldXform.Transform(localCenterOfInterest); target = { worldCenterOfInterest[0], worldCenterOfInterest[1], worldCenterOfInterest[2] }; } bool CameraState::setCameraPosition(const carb::Double3& worldPosition, bool rotate) { PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfMatrix4d parentXform = m_camera.ComputeParentToWorldTransform(m_timeCode); PXR_NS::GfMatrix4d invParentXform = parentXform.GetInverse(); PXR_NS::GfMatrix4d initialLocalXform = worldXform * invParentXform; PXR_NS::GfVec3d posInParent = invParentXform.Transform(PXR_NS::GfVec3d(worldPosition.x, worldPosition.y, worldPosition.z)); PXR_NS::UsdPrim camPrim = m_camera.GetPrim(); PXR_NS::UsdAttribute coiAttr; PXR_NS::GfVec3d prevLocalCenterOfInterest; PXR_NS::GfMatrix4d newLocalXform; if (rotate) { const PXR_NS::GfVec3d camUp = getCameraUp(camPrim.GetStage()); coiAttr = camPrim.GetAttribute(kCenterOfInterest); if (!coiAttr || !coiAttr.Get(&prevLocalCenterOfInterest, m_timeCode)) { prevLocalCenterOfInterest = { 0, 0, -1 }; } PXR_NS::GfVec3d coiInParent = invParentXform.Transform(worldXform.Transform(prevLocalCenterOfInterest)); if (!checkPositionAndTarget(posInParent, coiInParent)) { return false; } newLocalXform = PXR_NS::GfMatrix4d(1).SetLookAt(posInParent, coiInParent, camUp).GetInverse(); } else { newLocalXform = initialLocalXform; } newLocalXform.SetTranslateOnly(posInParent); omni::usd::UsdUtils::setLocalTransformMatrix(camPrim, newLocalXform, m_timeCode); if (coiAttr) { PXR_NS::GfVec3d prevWorldCOI = worldXform.Transform(prevLocalCenterOfInterest); PXR_NS::GfVec3d newLocalCOI = (newLocalXform * parentXform).GetInverse().Transform(prevWorldCOI); omni::usd::UsdUtils::setAttribute(coiAttr, newLocalCOI, m_timeCode); } return true; } bool CameraState::setCameraTarget(const carb::Double3& worldTarget, bool rotate) { PXR_NS::UsdPrim camPrim = m_camera.GetPrim(); PXR_NS::GfMatrix4d worldXform = m_camera.ComputeLocalToWorldTransform(m_timeCode).RemoveScaleShear(); PXR_NS::GfMatrix4d parentXform = m_camera.ComputeParentToWorldTransform(m_timeCode); PXR_NS::GfMatrix4d invParentXform = parentXform.GetInverse(); PXR_NS::GfMatrix4d initialLocalXform = worldXform * invParentXform; PXR_NS::GfVec3d gfWorldTarget(worldTarget.x, worldTarget.y, worldTarget.z); PXR_NS::GfVec3d prevLocalCenterOfInterest; PXR_NS::UsdAttribute coiAttr = camPrim.GetAttribute(kCenterOfInterest); if (!coiAttr || !coiAttr.Get(&prevLocalCenterOfInterest, m_timeCode)) { prevLocalCenterOfInterest = { 0, 0, -1 }; } PXR_NS::GfVec3d posInParent = invParentXform.Transform(initialLocalXform.Transform(PXR_NS::GfVec3d(0, 0, 0))); PXR_NS::GfMatrix4d newLocalXform; PXR_NS::GfVec3d newLocalCenterOfInterest; if (rotate) { // Rotate camera to look at new target, leaving it where it is PXR_NS::GfVec3d camUp = getCameraUp(camPrim.GetStage()); PXR_NS::GfVec3d coiInParent = invParentXform.Transform(gfWorldTarget); if (!checkPositionAndTarget(posInParent, coiInParent)) { return false; } newLocalXform = PXR_NS::GfMatrix4d(1).SetLookAt(posInParent, coiInParent, camUp).GetInverse(); newLocalCenterOfInterest = (newLocalXform * parentXform).GetInverse().Transform(gfWorldTarget); } else { // Camera keeps orientation and distance relative to target // Calculate movement of center-of-interest in parent's space PXR_NS::GfVec3d targetMove = invParentXform.Transform(gfWorldTarget) - invParentXform.Transform(worldXform.Transform(prevLocalCenterOfInterest)); // Copy the camera's local transform newLocalXform = initialLocalXform; // And move it by the delta newLocalXform.SetTranslateOnly(posInParent + targetMove); } if (rotate) { omni::usd::UsdUtils::setAttribute(coiAttr, newLocalCenterOfInterest, m_timeCode); } omni::usd::UsdUtils::setLocalTransformMatrix(camPrim, newLocalXform, m_timeCode); return true; }
6,669
C++
38.235294
153
0.708802
omniverse-code/kit/exts/omni.graph.ui/omni/graph/ui/ogn/nodes/OgnOnViewportPressed.cpp
// 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. // #include <OgnOnViewportPressedDatabase.h> #include "ViewportPressNodeCommon.h" #include <omni/kit/IApp.h> #include <omni/ui/Workspace.h> namespace omni { namespace graph { namespace ui { class OgnOnViewportPressed { public: struct InternalState { carb::events::ISubscriptionPtr pressBeganSub; carb::events::ISubscriptionPtr pressEndedSub; ViewportPressEventPayloads eventPayloads; ViewportPressEventStates eventStates; } m_internalState; static void initialize(GraphContextObj const&, NodeObj const& nodeObj) { OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed .getState<OgnOnViewportPressed>(nodeObj.nodeHandle); // Subscribe to press events if (omni::kit::IApp* app = carb::getCachedInterface<omni::kit::IApp>()) { state.m_internalState.pressBeganSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kPressBeganEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed .getState<OgnOnViewportPressed>(nodeObj.nodeHandle); state.m_internalState.eventPayloads.setPressBeganPayload(e->payload); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); state.m_internalState.pressEndedSub = carb::events::createSubscriptionToPushByType( app->getMessageBusEventStream(), kPressEndedEventType, [nodeObj](carb::events::IEvent* e) { if (e) { OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed .getState<OgnOnViewportPressed>(nodeObj.nodeHandle); state.m_internalState.eventPayloads.setPressEndedPayload(e->payload); if (nodeObj.iNode->isValid(nodeObj)) nodeObj.iNode->requestCompute(nodeObj); } } ); } } static void release(const NodeObj& nodeObj) { OgnOnViewportPressed& state = OgnOnViewportPressedDatabase::sm_stateManagerOgnOnViewportPressed .getState<OgnOnViewportPressed>(nodeObj.nodeHandle); // Unsubscribe from press events if (state.m_internalState.pressBeganSub.get()) state.m_internalState.pressBeganSub.detach()->unsubscribe(); if (state.m_internalState.pressEndedSub.get()) state.m_internalState.pressEndedSub.detach()->unsubscribe(); } static bool compute(OgnOnViewportPressedDatabase& db) { if (checkNodeDisabledForOnlyPlay(db)) return true; OgnOnViewportPressed& state = db.internalState<OgnOnViewportPressed>(); if (state.m_internalState.eventPayloads.empty()) return true; // Get the targeted viewport and gesture char const* const viewportWindowName = db.tokenToString(db.inputs.viewport()); char const* const gestureName = db.tokenToString(db.inputs.gesture()); if (!omni::ui::Workspace::getWindow(viewportWindowName)) { db.logWarning("Viewport window '%s' not found", viewportWindowName); } // Process event payloads and update event state bool pressBegan = false; for (auto const& pressBeganPayload : state.m_internalState.eventPayloads.pressBeganPayloads()) { if (!pressBeganPayload.second.isValid) continue; auto& eventStateValue = state.m_internalState.eventStates[pressBeganPayload.first]; eventStateValue.pressPositionNorm = pressBeganPayload.second.pressPositionNorm; eventStateValue.pressPositionPixel = pressBeganPayload.second.pressPositionPixel; eventStateValue.releasePositionNorm = {0.0, 0.0}; eventStateValue.releasePositionPixel = {0.0, 0.0}; eventStateValue.isPressed = true; eventStateValue.isReleasePositionValid = false; if (std::strcmp(viewportWindowName, pressBeganPayload.first.viewportWindowName) == 0 && std::strcmp(gestureName, pressBeganPayload.first.gestureName) == 0) { pressBegan = true; } } bool pressEnded = false; for (auto const& pressEndedPayload : state.m_internalState.eventPayloads.pressEndedPayloads()) { if (!pressEndedPayload.second.isValid) continue; auto& eventStateValue = state.m_internalState.eventStates[pressEndedPayload.first]; if (eventStateValue.isPressed) { eventStateValue.releasePositionNorm = pressEndedPayload.second.releasePositionNorm; eventStateValue.releasePositionPixel = pressEndedPayload.second.releasePositionPixel; eventStateValue.isPressed = false; eventStateValue.isReleasePositionValid = pressEndedPayload.second.isReleasePositionValid; if (std::strcmp(viewportWindowName, pressEndedPayload.first.viewportWindowName) == 0 && std::strcmp(gestureName, pressEndedPayload.first.gestureName) == 0) { pressEnded = true; } } } state.m_internalState.eventPayloads.clear(); // Get event state and set outputs auto it = state.m_internalState.eventStates.find({viewportWindowName, gestureName}); if (it != state.m_internalState.eventStates.end()) { if (pressEnded) { db.outputs.pressed() = kExecutionAttributeStateDisabled; db.outputs.released() = kExecutionAttributeStateEnabled; db.outputs.pressPosition() = db.inputs.useNormalizedCoords() ? it->second.pressPositionNorm : it->second.pressPositionPixel; db.outputs.releasePosition() = db.inputs.useNormalizedCoords() ? it->second.releasePositionNorm : it->second.releasePositionPixel; db.outputs.isReleasePositionValid() = it->second.isReleasePositionValid; } else if (pressBegan) { db.outputs.pressed() = kExecutionAttributeStateEnabled; db.outputs.released() = kExecutionAttributeStateDisabled; db.outputs.pressPosition() = db.inputs.useNormalizedCoords() ? it->second.pressPositionNorm : it->second.pressPositionPixel; db.outputs.releasePosition() = {0.0, 0.0}; db.outputs.isReleasePositionValid() = false; } else { db.outputs.pressed() = kExecutionAttributeStateDisabled; db.outputs.released() = kExecutionAttributeStateDisabled; } } return true; } }; REGISTER_OGN_NODE() } // ui } // graph } // omni
7,765
C++
39.238342
146
0.625113