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.ui.scene/omni/ui_scene/__init__.py
## Copyright (c) 2018-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. ## """ omni.ui.scene ------------- """ from .scene_extension import SceneExtension
523
Python
31.749998
77
0.762906
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/scene_extension.py
## Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from . import scene import omni.ext import omni.ui as ui from .compatibility import add_intersection_attributes class SceneExtension(omni.ext.IExt): """The entry point for MDL Material Graph""" def on_startup(self): self.subscription = ui.add_to_namespace(scene) # Compatibility with old intersections add_intersection_attributes() def on_shutdown(self): self.subscription = None
870
Python
32.499999
77
0.749425
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/compatibility.py
## Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["add_intersection_attributes"] from . import scene as sc import carb def _deprecate_warning(func, old, new): """Returns decorated function that prints a warning when it's executed""" def inner(*args, **kwargs): carb.log_warn(f"[omni.ui.scene] Method {old} is deprecated. Please use {new} instead.") return func(*args, **kwargs) return inner def _add_compatibility(obj, old, new, deprecate_warning=True): """Add the attribute old that equals to new""" new_obj = getattr(obj, new) if deprecate_warning: if isinstance(new_obj, property): setattr( obj, old, property( fget=_deprecate_warning(new_obj.fget, obj.__name__ + "." + old, obj.__name__ + "." + new), fset=_deprecate_warning(new_obj.fset, obj.__name__ + "." + old, obj.__name__ + "." + new), ), ) else: setattr(obj, old, _deprecate_warning(new_obj, obj.__name__ + "." + old, obj.__name__ + "." + new)) else: setattr(obj, old, new_obj) def add_intersection_attributes(): """Assigns deprecated methods that print warnings when executing""" for item in [ sc.AbstractGesture, sc.AbstractShape, sc.Arc, sc.Line, sc.Points, sc.PolygonMesh, sc.Rectangle, sc.Screen, ]: _add_compatibility(item, "intersection", "gesture_payload") _add_compatibility(item, "get_intersection", "get_gesture_payload") _add_compatibility(sc.AbstractGesture, "Intersection", "GesturePayload", False)
2,090
Python
33.849999
110
0.616268
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/gesture_manager_utils.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## """The utilities for ui.scene test""" from omni.ui_scene import scene as sc class Manager(sc.GestureManager): def __init__(self, mouse_action_sequence, mouse_position_sequence, scene_view): """ The gesture manager takes inputs to mimic the mouse operations for tests Args: mouse_action_sequence: a List which contains a sequence of (input.clicked, input.down, input.released) mouse_position_sequence: a List which contains a sequence of (input.mouse[0], input.mouse[1]) """ super().__init__() # The sequence of actions. In the future we need a way to record it. # mimic the mouse click, hold and move self.mouse_action_sequence = mouse_action_sequence self.mouse_position_sequence = mouse_position_sequence if len(self.mouse_action_sequence) != len(self.mouse_position_sequence): raise Exception(f"the mouse action sequence length doesn't match the mouse position sequence") self.scene_view = scene_view self.counter = 0 def amend_input(self, input): if self.counter >= len(self.mouse_action_sequence): # Don't amentd anything. return input # Move mouse input.mouse[0], input.mouse[1] = self.mouse_position_sequence[self.counter] # Get 3D cords of the mouse origin, direction = self.scene_view.get_ray_from_ndc(input.mouse) input.mouse_origin = origin input.mouse_direction = direction # Click, move and release input.clicked, input.down, input.released = self.mouse_action_sequence[self.counter] self.counter += 1 return input
2,124
Python
41.499999
114
0.678908
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_manipulator.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from omni.ui.tests.test_base import OmniUiTest from functools import partial from pathlib import Path from omni.ui_scene import scene as sc from omni.ui import color as cl import asyncio import carb import math import omni.kit import omni.kit.app import omni.ui as ui from .gesture_manager_utils import Manager KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent CURRENT_PATH = Path(__file__).parent.joinpath("../../../data") class TestManipulator(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_manipulator_update(self): class RotatingCube(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self._angle = 0 def on_build(self): transform = sc.Matrix44.get_rotation_matrix( 0, self._angle, 0, True) with sc.Transform(transform=transform): sc.Line([-1, -1, -1], [1, -1, -1]) sc.Line([-1, 1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [1, -1, 1]) sc.Line([-1, 1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, 1, -1]) sc.Line([1, -1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [-1, 1, 1]) sc.Line([1, -1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, -1, 1]) sc.Line([-1, 1, -1], [-1, 1, 1]) sc.Line([1, -1, -1], [1, -1, 1]) sc.Line([1, 1, -1], [1, 1, 1]) # Increase the angle self._angle += 5 def get_angle(self): return self._angle window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True) transl = sc.Matrix44.get_translation_matrix(0, 0, -6) view = transl * rotation with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: rcube = RotatingCube() rcube.invalidate() await self.wait_n_updates(1) self.assertEqual(rcube.get_angle(), 5) rcube.invalidate() await self.wait_n_updates(1) self.assertEqual(rcube.get_angle(), 10) rcube.invalidate() await self.wait_n_updates(1) self.assertEqual(rcube.get_angle(), 15) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_manipulator_model(self): class MovingRectangle(sc.Manipulator): """Manipulator that redraws when the model is changed""" def __init__(self, **kwargs): super().__init__(**kwargs) mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (0.15, 0), (0.3, 0), (0.3, 0), (0.3, 0)] mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) self._gesture = sc.DragGesture(on_changed_fn=self._move, manager=mgr) def on_build(self): position = self.model.get_as_floats(self.model.get_item("position")) transform = sc.Matrix44.get_translation_matrix(*position) with sc.Transform(transform=transform): sc.Rectangle(color=cl.blue, gesture=self._gesture) def on_model_updated(self, item): self.invalidate() def _move(self, shape: sc.AbstractShape): position = shape.gesture_payload.ray_closest_point item = self.model.get_item("position") self.model.set_floats(item, position) class Model(sc.AbstractManipulatorModel): """User part. Simple value holder.""" class PositionItem(sc.AbstractManipulatorItem): def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self): super().__init__() self.position = Model.PositionItem() def get_item(self, identifier): return self.position def get_as_floats(self, item): return item.value def set_floats(self, item, value): item.value = value self._item_changed(item) window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True) transl = sc.Matrix44.get_translation_matrix(0, 0, -6) view = transl * rotation with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: MovingRectangle(model=Model()) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_manipulator_image(self): """Check the image in manipulator doesn't crash when invalidation""" class ImageManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self.image = None def on_build(self): filename = f"{CURRENT_PATH}/main_ov_logo_square.png" self.image = sc.Image(filename) window = await self.create_test_window() with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: manipulator = ImageManipulator() # removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms! for _ in range(50): image_ready = manipulator.image and manipulator.image.image_provider.is_reference_valid if image_ready: break await asyncio.sleep(0.1) await self.wait_n_updates(1) # Check it doesn't crash manipulator.invalidate() await self.wait_n_updates(1) # Wait for Image for _ in range(50): image_ready = manipulator.image and manipulator.image.image_provider.is_reference_valid if image_ready: break await asyncio.sleep(0.1) await self.wait_n_updates(1) await self.finalize_test_no_image() async def test_manipulator_textured_mesh(self): """Check the TexturedMesh in manipulator doesn't crash when invalidation""" class TexturedMeshManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self.mesh = None def on_build(self): point_count = 4 # Form the mesh data points = [[1, -1, 0], [1, 1, 0], [0, 1, 0], [-1, -1, 0]] vertex_indices = [0, 1, 2, 3] colors = [[0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]] uvs = [[1, 1], [1, 0], [0.5, 0], [0, 1]] # Draw the mesh filename = f"{CURRENT_PATH}/main_ov_logo_square.png" self.mesh = sc.TexturedMesh(filename, uvs, points, colors, [point_count], vertex_indices) window = await self.create_test_window() with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: manipulator = TexturedMeshManipulator() # removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms! for _ in range(50): image_ready = manipulator.mesh and manipulator.mesh.image_provider.is_reference_valid if image_ready: break await asyncio.sleep(0.1) await self.wait_n_updates(1) # Check it doesn't crash manipulator.invalidate() await self.wait_n_updates(1) # Wait for Image for _ in range(50): image_ready = manipulator.mesh and manipulator.mesh.image_provider.is_reference_valid if image_ready: break await asyncio.sleep(0.1) await self.wait_n_updates(1) await self.finalize_test_no_image()
9,718
Python
36.670542
111
0.542498
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_scroll.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestScroll"] import omni.kit.test from omni.ui import scene as sc from omni.ui.tests.test_base import OmniUiTest import omni.kit.app import omni.ui as ui class TestScroll(OmniUiTest): async def test_scroll(self): import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) scrolled = [0, 0] class Scroll(sc.ScrollGesture): def on_ended(self): scrolled[0] += self.scroll[0] scrolled[1] += self.scroll[1] with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: sc.Screen(gesture=Scroll()) await self.wait_n_updates(1) ref = ui_test.WidgetRef(scene_view, "") await ui_test.emulate_mouse_move(ref.center) await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 0)) await self.wait_n_updates(1) self.assertTrue(scrolled[0] == 0) self.assertTrue(scrolled[1] > 0) await self.finalize_test_no_image() async def test_scroll_another_window(self): import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) scrolled = [0, 0] class Scroll(sc.ScrollGesture): def on_ended(self): scrolled[0] += self.scroll[0] scrolled[1] += self.scroll[1] with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: sc.Screen(gesture=Scroll()) another_window = ui.Window("cover it", width=128, height=128, position_x=64, position_y=64) await self.wait_n_updates(1) ref = ui_test.WidgetRef(scene_view, "") await ui_test.emulate_mouse_move(ref.center) await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 1)) await self.wait_n_updates(1) # Window covers SceneView. Scroll is not expected. self.assertTrue(scrolled[0] == 0) self.assertTrue(scrolled[1] == 0) await self.finalize_test_no_image()
3,104
Python
31.010309
99
0.601482
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_container.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from omni.ui_scene import scene as sc from omni.ui import color as cl import carb import math KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent class TestContainer(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_transform(self): window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True) transl = sc.Matrix44.get_translation_matrix(0, 0, -6) view = transl * rotation with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: line_count = 36 for i in range(line_count): weight = i / line_count angle = 2.0 * math.pi * weight # translation matrix move = sc.Matrix44.get_translation_matrix( 8 * (weight - 0.5), 0.5 * math.sin(angle), 0) # rotation matrix rotate = sc.Matrix44.get_rotation_matrix(0, 0, angle) # the final transformation transform = move * rotate color = cl(weight, 1.0 - weight, 1.0) # create transform and put line to it with sc.Transform(transform=transform): sc.Line([0, 0, 0], [0.5, 0, 0], color=color) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir)
2,610
Python
34.283783
90
0.592337
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_arc.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from .gesture_manager_utils import Manager from omni.ui import color as cl from omni.ui_scene import scene as sc from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import carb import math import omni.appwindow import omni.kit.app import omni.ui as ui KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent CURRENT_PATH = Path(__file__).parent.joinpath("../../../data") class TestArc(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_angle(self): """Test the angle""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) class MyDragGesture(sc.DragGesture): def __init__(self): super().__init__() self.began_called = False self.changed_called = False self.ended_called = False self.began_angle = 0.0 self.end_angle = 0.0 def can_be_prevented(self, gesture): return True def on_began(self): self.sender.begin = self.sender.gesture_payload.angle self.began_angle = self.sender.gesture_payload.angle self.began_called = True def on_changed(self): self.sender.end = self.sender.gesture_payload.angle self.changed_called = True def on_ended(self): self.sender.color = cl.blue self.end_angle = self.sender.gesture_payload.angle self.ended_called = True with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: transform = sc.Matrix44.get_translation_matrix(0, 0, 0) transform *= sc.Matrix44.get_scale_matrix(0.2, 0.2, 0.2) with sc.Transform(transform=transform): nsteps = 20 # Click, drag 360 deg, release drag = MyDragGesture() # Clicked, down, released mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * (nsteps + 1) + [(0, 0, 1), (0, 0, 0)] mouse_position_sequence = ( [(0, 1), (0, 1)] + [ (-math.sin(i * math.pi * 2.0 / nsteps), math.cos(i * math.pi * 2.0 / nsteps)) for i in range(nsteps + 1) ] + [(0, 1), (0, 1)] ) drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) sc.Arc(500, wireframe=True, color=cl.white, gesture=drag) await self.wait_n_updates(nsteps + 5) self.assertTrue(drag.began_called) self.assertTrue(drag.changed_called) self.assertTrue(drag.ended_called) self.assertEqual(drag.began_angle, math.pi * 0.5) self.assertEqual(drag.end_angle, math.pi * 2.5) await self.finalize_test(golden_img_dir=self._golden_img_dir)
4,129
Python
35.875
120
0.564301
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_scene.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestScene"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.ui_scene import scene as sc from pathlib import Path import carb import omni.kit.app import omni.ui as ui KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent CURRENT_PATH = Path(__file__).parent.joinpath("../../../data") class CameraModel(sc.AbstractManipulatorModel): def __init__(self): super().__init__() self._angle = 0 def append_angle(self, delta: float): self._angle += delta * 100 # Inform SceneView that view matrix is changed self._item_changed("view") def get_as_floats(self, item): """Called by SceneView to get projection and view matrices""" if item == self.get_item("projection"): # Projection matrix return [5, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, -1, 0, 0, -1, 0] if item == self.get_item("view"): # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, self._angle, 0, True) transl = sc.Matrix44.get_translation_matrix(0, 0, -8) view = transl * rotation return [view[i] for i in range(16)] class StereoModel(sc.AbstractManipulatorModel): def __init__(self, parent, offset): super().__init__() self._parent = parent self._offset = offset self._sub = self._parent.subscribe_item_changed_fn(lambda m, i: self.changed(m, i)) def changed(self, model, item): self._item_changed("view") def get_as_floats(self, item): """Called by SceneView to get projection and view matrices""" if item == self.get_item("projection"): return self._parent.get_as_floats(self._parent.get_item("projection")) if item == self.get_item("view"): parent = self._parent.get_as_floats(self._parent.get_item("view")) parent = sc.Matrix44(*parent) transl = sc.Matrix44.get_translation_matrix(0, 0, 8) rotation = sc.Matrix44.get_rotation_matrix(0, self._offset, 0, True) transl_inv = sc.Matrix44.get_translation_matrix(0, 0, -8) view = transl_inv * rotation * transl * parent return [view[i] for i in range(16)] class TestScene(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_stereo(self): """Test the stereo setup""" window = await self.create_test_window(block_devices=False) with window.frame: with ui.HStack(): camera = CameraModel() scene = sc.Scene() sc.SceneView(StereoModel(camera, 3), scene=scene) sc.SceneView(StereoModel(camera, -3), scene=scene) with scene: # Edges of cube sc.Line([-1, -1, -1], [1, -1, -1]) sc.Line([-1, 1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [1, -1, 1]) sc.Line([-1, 1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, 1, -1]) sc.Line([1, -1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [-1, 1, 1]) sc.Line([1, -1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, -1, 1]) sc.Line([-1, 1, -1], [-1, 1, 1]) sc.Line([1, -1, -1], [1, -1, 1]) sc.Line([1, 1, -1], [1, 1, 1]) with sc.Transform(transform=sc.Matrix44.get_scale_matrix(0.002, 0.002, 0.002)): widget = sc.Widget(1000, 500) with widget.frame: ui.Label(f"Hello test", style={"font_size": 250}) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_draw_list_buffer_count(self): class RotatingCube(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self._angle = 0 def on_build(self): transform = sc.Matrix44.get_rotation_matrix( 0, self._angle, 0, True) with sc.Transform(transform=transform): sc.Line([-1, -1, -1], [1, -1, -1]) sc.Line([-1, 1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [1, -1, 1]) sc.Line([-1, 1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, 1, -1]) sc.Line([1, -1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [-1, 1, 1]) sc.Line([1, -1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, -1, 1]) sc.Line([-1, 1, -1], [-1, 1, 1]) sc.Line([1, -1, -1], [1, -1, 1]) sc.Line([1, 1, -1], [1, 1, 1]) # Increase the angle self._angle += 5 def get_angle(self): return self._angle window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True) transl = sc.Matrix44.get_translation_matrix(0, 0, -6) view = transl * rotation with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: rcube = RotatingCube() for _ in range(2): rcube.invalidate() await self.wait_n_updates(1) draw_list_buffer_count = scene_view.scene.draw_list_buffer_count for _ in range(2): rcube.invalidate() await self.wait_n_updates(1) # Testing that the buffer count didn't change self.assertEqual(scene_view.scene.draw_list_buffer_count, draw_list_buffer_count) await self.finalize_test_no_image()
6,836
Python
36.77348
99
0.518432
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_shapes.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from omni.ui_scene import scene as sc from omni.ui import color as cl import omni.ui as ui import math import carb import omni.kit from omni.kit import ui_test from .gesture_manager_utils import Manager from functools import partial from numpy import pi, cos, sin, arccos import random import asyncio KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent CURRENT_PATH = Path(__file__).parent.joinpath("../../../data") class TestShapes(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") random.seed(10) # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): window = await self.create_test_window(width=512, height=256) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: # line sc.Line([-2.5, -1.0, 0], [-1.5, -1.0, 0], color=cl.red, thickness=5) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(1, 0.2, 0)): # Rectangle sc.Rectangle(color=cl.blue) # wireframe rectangle sc.Rectangle(2, 1.3, thickness=5, wireframe=True) # arc sc.Arc(3, begin=math.pi, end=4, thickness=5, wireframe=True, color=cl.yellow) # label with sc.Transform(transform=sc.Matrix44.get_translation_matrix(1, -2, 0)): sc.Label("NVIDIA Omniverse", alignment=ui.Alignment.CENTER, color=cl.green, size=50) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_image(self): window = await self.create_test_window(width=512, height=256) sc_image = None with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: # image filename = f"{CURRENT_PATH}/main_ov_logo_square.png" sc_image = sc.Image(filename) # removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms! for _ in range(50): image_ready = sc_image.image_provider.is_reference_valid if image_ready: break await asyncio.sleep(0.1) await self.wait_n_updates(1) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_distant_shape(self): window = await self.create_test_window(width=256, height=256) # Projection matrix proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0] # Move camera transl = sc.Matrix44.get_translation_matrix(100000000000, 100000000000, 119999998) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, transl), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: with sc.Transform( transform=sc.Matrix44.get_translation_matrix(-100000000000, -100000000000, -119999995) ): sc.Line([-1, -1, -1], [1, -1, -1]) sc.Line([-1, 1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [1, -1, 1]) sc.Line([-1, 1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, 1, -1]) sc.Line([1, -1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [-1, 1, 1]) sc.Line([1, -1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, -1, 1]) sc.Line([-1, 1, -1], [-1, 1, 1]) sc.Line([1, -1, -1], [1, -1, 1]) sc.Line([1, 1, -1], [1, 1, 1]) await self.wait_n_updates(10) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_points(self): window = await self.create_test_window(width=512, height=200) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: point_count = 36 points = [] sizes = [] colors = [] for i in range(point_count): weight = i / point_count angle = 2.0 * math.pi * weight points.append([math.cos(angle), math.sin(angle), 0]) colors.append([weight, 1 - weight, 1, 1]) sizes.append(6 * (weight + 1.0 / point_count)) sc.Points(points, colors=colors, sizes=sizes) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_polygon_mesh(self): window = await self.create_test_window(width=512, height=200) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: point_count = 36 # Form the mesh data points = [] vertex_indices = [] sizes = [] colors = [] for i in range(point_count): weight = i / point_count angle = 2.0 * math.pi * weight vertex_indices.append(i) points.append([math.cos(angle) * weight, -math.sin(angle) * weight, 0]) colors.append([weight, 1 - weight, 1, 1]) sizes.append(6 * (weight + 1.0 / point_count)) # Draw the mesh sc.PolygonMesh(points, colors, [point_count], vertex_indices) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_polygon_mesh_intersection(self): """Click on the different polygon mesh to get the s and t""" await self.create_test_area(width=1440, height=900, block_devices=False) self.intersection = False self.face_id = -1 self.s = -1.0 self.t = -1.0 def _on_shape_clicked(shape): """Called when the user clicks the point""" self.intersection = True self.face_id = shape.gesture_payload.face_id self.s = shape.gesture_payload.s self.t = shape.gesture_payload.t window = ui.Window("test_polygon_mesh_intersection", width=700, height=500) proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: select = sc.ClickGesture(_on_shape_clicked) # two triangles point_count = 3 points = [[-1, -1, 0], [2, -1, 0], [3, 1, 0], [2, -1, 0], [4, 0, -1], [3, 1, 0]] vertex_indices = [0, 1, 2, 3, 4, 5] colors = [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]] sc.PolygonMesh(points, colors, [point_count, point_count], vertex_indices, gesture=select) await ui_test.wait_n_updates(10) await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(850, 300)) await ui_test.wait_n_updates(10) self.assertEqual(self.intersection, True) self.assertEqual(self.face_id, 0) self.assertAlmostEqual(self.s, 0.18666667622178545) self.assertAlmostEqual(self.t, 0.7600000000000001) await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(870, 300)) await ui_test.wait_n_updates(10) self.assertEqual(self.intersection, True) self.assertEqual(self.face_id, 1) self.assertAlmostEqual(self.s, 0.16000002187854384) self.assertAlmostEqual(self.t, 0.6799999891122469) async def test_polygon_mesh_not_intersection(self): """Click on a polygon mesh to see shape is not clicked""" await self.create_test_area(width=1440, height=900, block_devices=False) self.intersection = False def _on_shape_clicked(shape): """Called when the user clicks the point""" self.intersection = True window = ui.Window("test_polygon_mesh_not_intersection", width=700, height=500) proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] view = sc.Matrix44.get_translation_matrix(0, 0, -6) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: select = sc.ClickGesture(_on_shape_clicked) # a concave quadrangle point_count = 4 points = [[-1, -1, 0], [1, -1, 0], [0, -0.5, 0], [1, 1, 0]] vertex_indices = [0, 1, 2, 3] colors = [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]] sc.PolygonMesh(points, colors, [point_count], vertex_indices, gesture=select) await ui_test.wait_n_updates(10) await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(740, 350)) await ui_test.wait_n_updates(10) self.assertEqual(self.intersection, False) await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(700, 350)) await ui_test.wait_n_updates(10) self.assertEqual(self.intersection, True) async def __test_textured_mesh(self, golden_img_name: str, **kwargs): """Test polygon mesh with texture""" window = await self.create_test_window(width=512, height=200) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: point_count = 4 # Form the mesh data vertex_indices = [0, 2, 3, 1] points = [(-1, -1, 0), (1, -1, 0), (-1, 1, 0), (1, 1, 0)] colors = [[0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1]] # UVs specified in USD coordinate system uvs = [(0, 0), (0, 1), (1, 1), (1, 0)] # Flip V coordinate is requested if kwargs.get("legacy_flipped_v") is None: uvs = [(uv[0], 1.0 - uv[1]) for uv in uvs] # Draw the mesh filename = f"{CURRENT_PATH}/main_ov_logo_square.png" tm = sc.TexturedMesh(filename, uvs, points, colors, [point_count], vertex_indices, **kwargs) # Test that get of uv property is equal to input in both cases self.assertTrue(tm.uvs, uvs) # removing this wait leads to an error of png unload wait time exceeded limit of 20000 ms! for _ in range(50): await asyncio.sleep(0.1) await self.wait_n_updates(1) await self.finalize_test(golden_img_name=golden_img_name, golden_img_dir=self._golden_img_dir) async def test_textured_mesh_legacy(self): """Test legacy polygon mesh with texture (flipped V)""" await self.__test_textured_mesh(golden_img_name="test_textured_mesh_legacy.png") async def test_textured_mesh(self): """Test polygon mesh with texture (USD coordinates)""" await self.__test_textured_mesh(golden_img_name="test_textured_mesh.png", legacy_flipped_v=False) async def test_textured_mesh_intersection(self): """Click on the different polygon mesh to get the s and t""" await self.create_test_area(width=1440, height=900, block_devices=False) self.intersection = False self.face_id = -1 self.u = -1.0 self.v = -1.0 self.s = -1.0 self.t = -1.0 def _on_shape_clicked(shape): """Called when the user clicks the point""" self.intersection = True self.face_id = shape.gesture_payload.face_id self.u = shape.gesture_payload.u self.v = shape.gesture_payload.v self.s = shape.gesture_payload.s self.t = shape.gesture_payload.t window = ui.Window("test_textured_mesh_intersection", width=700, height=700) proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] view = sc.Matrix44.get_translation_matrix(0, 0, -6) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: select = sc.ClickGesture(_on_shape_clicked) # Form the mesh data point_count = 4 points = [ [-3, -3, 0], [3, -3, 0], [3, 3, 0], [-3, 3, 0], [-3, -6, 0], [3, -6, 0], [3, -3, 0], [-3, -3, 0], ] vertex_indices = [0, 1, 2, 3, 4, 5, 6, 7] colors = [ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ] filename = f"{CURRENT_PATH}/main_ov_logo_square.png" uvs = [[0, 1], [1, 1], [1, 0], [0, 0], [0, 1], [1, 1], [1, 0], [0, 0]] sc.TexturedMesh( filename, uvs, points, colors, [point_count, point_count], vertex_indices, gesture=select ) await ui_test.wait_n_updates(10) await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(580, 130)) await ui_test.wait_n_updates(10) self.assertEqual(self.face_id, 0) self.assertAlmostEqual(self.u, 0.03333332762122154) self.assertAlmostEqual(self.v, 0.18000000715255737) self.assertAlmostEqual(self.s, 0.03333332818826966) self.assertAlmostEqual(self.t, 0.8200000000000001) await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(850, 500)) await ui_test.wait_n_updates(10) self.assertEqual(self.face_id, 1) self.assertAlmostEqual(self.u, 0.9333333373069763) self.assertAlmostEqual(self.v, 0.8266666680574417) self.assertAlmostEqual(self.s, 0.9333333381108925) self.assertAlmostEqual(self.t, 0.17333333333333378) async def test_linear_curve(self): window = await self.create_test_window(width=512, height=512) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: sc.Curve( [[-2.5, -1.0, 0], [-1.5, -1.0, 0], [-1.5, -2.0, 0], [1.0, 0.5, 0]], curve_type=sc.Curve.CurveType.LINEAR, colors=[cl.yellow, cl.blue, cl.yellow, cl.green], thicknesses=[3.0, 1.5, 3.0, 3], ) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_curve_properties(self): """test with different colors and thicknesses""" window = await self.create_test_window(width=600, height=800) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, 0, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], thicknesses=[1.0, 2.0, 3.0, 4.0], curve_type=sc.Curve.CurveType.LINEAR, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -2, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red], thicknesses=[1.0, 2.0, 3.0], curve_type=sc.Curve.CurveType.LINEAR, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -4, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red, cl.blue], thicknesses=[1.0, 2.0], curve_type=sc.Curve.CurveType.LINEAR, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -6, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red, [0, 1, 0, 1], cl.blue], thicknesses=[1.5], tessellation=7, curve_type=sc.Curve.CurveType.LINEAR, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-4, -8, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red, [0, 1, 0, 1], cl.blue, cl.yellow], tessellation=7, curve_type=sc.Curve.CurveType.LINEAR, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], thicknesses=[1.0, 2.0, 3.0, 4.0], tessellation=4, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -2, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red], thicknesses=[1.0, 2.0, 3.0], tessellation=4, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -4, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red, cl.blue], thicknesses=[1.0, 2.0], tessellation=4, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -6, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red, [0, 1, 0, 1], cl.blue], thicknesses=[1.5], tessellation=4, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -8, 0)): sc.Curve( [[0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0]], colors=[cl.red, [0, 1, 0, 1], cl.blue, cl.yellow], tessellation=4, ) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_curve_intersection_linear(self): """Click different segments of the curve sets the curve to different colors""" def _on_shape_clicked(shape): """Called when the user clicks the point""" shape.colors = [cl.yellow] window = await self.create_test_window(width=512, height=256) proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: select = sc.ClickGesture(_on_shape_clicked) mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * 10 + [(0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(-0.023809523809523836, -0.19333333333333336)] * 14 select.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) sc.Curve( [[-2.5, -1.0, 0], [-1.5, -1.0, 0], [-0.5, 0, 0], [0.5, -1, 0], [1.5, -1, 0]], curve_type=sc.Curve.CurveType.LINEAR, gesture=select, ) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_curve_intersection_distance(self): """Click different segments of the curve sets the curve to different colors""" self.curve_distance = 0.0 def _on_shape_clicked(shape): """Called when the user clicks the point""" shape.colors = [cl.red] self.curve_distance = shape.gesture_payload.curve_distance window = await self.create_test_window(width=512, height=256) proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: select = sc.ClickGesture(_on_shape_clicked) mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * 5 + [(0, 0, 1)] + [(0, 0, 0)] * 100 mouse_position_sequence = [(0.0978835978835979, 0.04)] * 108 select.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) sc.Curve( [[-1, 1.0, 0], [1, 0.2, 0], [1, -0.2, 0], [-1, -1, 0]], thicknesses=[5.0], colors=[cl.blue], gesture=select, ) await self.wait_n_updates(30) self.assertAlmostEqual(self.curve_distance, 0.4788618615426895) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_bezier_curve(self): window = await self.create_test_window(width=600, height=450) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=150) with scene_view.scene: sc.Curve( [ [-2.5, -1.0, 0], [-1.5, 0, 0], [-0.5, -1, 0], [0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0], ], colors=[cl.red], thicknesses=[3.0], curve_type=sc.Curve.CurveType.LINEAR, ) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, -2, 0)): sc.Curve( [ [-2.5, -1.0, 0], [-1.5, 0, 0], [-0.5, -1, 0], [0.5, -1, 0], [0.1, 0.6, 0], [2.0, 0.6, 0], [3.5, -1, 0], ], colors=[cl.red], thicknesses=[3.0], tessellation=9, ) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_bezier_curve_move(self): def move(transform: sc.Transform, shape: sc.AbstractShape): """Called by the gesture""" translate = shape.gesture_payload.moved # Move transform to the direction mouse moved current = sc.Matrix44.get_translation_matrix(*translate) transform.transform *= current window = await self.create_test_window(width=600, height=256) # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: transform = sc.Transform() with transform: mouse_action_sequence = [ (0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0), ] mouse_position_sequence = [ (0.009, 0.22667), (0.009, 0.22667), (0.009, 0.22667), (0.01126, 0.22667), (0.2207, 0.2), (0.5157, 0.186667), (0.5157, 0.186667), (0.5157, 0.186667), ] mrg = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) drag = sc.DragGesture(manager=mrg, on_changed_fn=partial(move, transform)) sc.Curve( [[-1.5, -1.0, 0], [-0.5, 1, 0], [0.5, 0.8, 0], [1.5, -1, 0]], colors=[cl.yellow], thicknesses=[5.0, 1.5], gesture=drag, ) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) def _curves_on_sphere(self, num_curves, num_segs): """generate curves points on a sphere""" curves = [] for i in range(0, num_curves): phi = arccos(1 - 2 * i / num_curves) theta = pi * (1 + 5**0.5) * i x, y, z = cos(theta) * sin(phi) + 0.5, sin(theta) * sin(phi) + 0.5, cos(phi) + 0.5 curve = [] curve.append([x, y, z]) for j in range(0, num_segs): rx = (random.random() - 0.5) * 0.2 ry = (random.random() - 0.5) * 0.2 rz = (random.random() - 0.5) * 0.2 curve.append([x + rx, y + ry, z + rz]) curves.append(curve) return curves async def test_linear_curve_scalability(self): """we can have maximum 21 segments per curve with 10000 linear 10000 curves 21 segments per curve which has 22 vertices per curve """ num_curves = 10000 num_segs = 21 curves = self._curves_on_sphere(num_curves, num_segs) window = await self.create_test_window(width=600, height=600) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300) with scene_view.scene: with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.5, -1, 0)): for curve in curves: sc.Curve( curve, colors=[[curve[0][0], curve[0][1], curve[0][2], 1.0]], curve_type=sc.Curve.CurveType.LINEAR, ) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_bezier_curve_scalability(self): """we can have maximum 8920 curves with 3 segments per bezier curve and default 9 tessellation 8920 curves 3 segments per curve 9 tessellation per curve which has 25 vertices per curve """ num_curves = 8920 num_segs = 3 curves = self._curves_on_sphere(num_curves, num_segs) window = await self.create_test_window(width=600, height=600) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300) with scene_view.scene: with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.5, -1, 0)): for curve in curves: sc.Curve( curve, colors=[[curve[0][0], curve[0][1], curve[0][2], 1.0]], thicknesses=[1.0], ) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_bezier_segment_scalability(self): """we can have maximum 27 curves per bezier curve with 999 segments and default 9 tessellation 27 curves 999 segments per curve 9 tessellation per curve which has 7993 vertices per curve """ num_curves = 27 num_segs = 999 # the number has to be dividable by 3 curves = [] for i in range(0, num_curves): x = i % 6 y = int(i / 6) z = random.random() curve = [] curve.append([x, y, z]) for j in range(0, num_segs): curve.append([x + random.random(), y + random.random(), z + random.random()]) curves.append(curve) window = await self.create_test_window(width=1000, height=800) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300) with scene_view.scene: with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-3, -4, 0)): for curve in curves: sc.Curve( curve, colors=[[1, 1, 0, 1.0]], thicknesses=[1.0], ) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_intersection_scalability(self): """for intersection workable, we can have maximum 3000 curves with 9 segments and 9 tessellation per curve 3000 curves 9 segments per curve 9 tessellation per curve which has 73 vertices per curve """ def move(transform: sc.Transform, shape: sc.AbstractShape): """Called by the gesture""" translate = shape.gesture_payload.moved # Move transform to the direction mouse moved current = sc.Matrix44.get_translation_matrix(*translate) transform.transform *= current num_curves = 3000 num_segs = 9 curves = self._curves_on_sphere(num_curves, num_segs) mouse_action_sequence = [(0, 0, 0), (1, 1, 0)] + [(0, 1, 0)] * 40 + [(0, 0, 1)] * 20 + [(0, 0, 0)] * 10 mouse_position_sequence = ( [(0.06981981981981988, -0.7333333333333334)] * 22 + [(0.12387387387387383, -0.8844444444444444)] * 10 + [(0.2635135135135136, -1.511111111111111)] * 10 + [(0.6265765765765767, -1.98844444444444444)] * 10 + [(1.84009009009009006, -2.9977777777777776)] * 20 ) window = await self.create_test_window(width=600, height=600) with window.frame: scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=300) mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) with scene_view.scene: for curve in curves: transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.5, -1, 0)) with transform: drag = sc.DragGesture(on_changed_fn=partial(move, transform), manager=mgr) sc.Curve(curve, colors=[[random.random(), random.random(), random.random(), 1.0]], gesture=drag) await self.wait_n_updates(100) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_transparency(self): window = await self.create_test_window() with window.frame: with ui.ZStack(): # Background ui.Rectangle(style={"background_color": ui.color(0.5, 0.5, 0.5)}) scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT) with scene_view.scene: with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0.25, 0.25, -0.1)): sc.Rectangle(1, 1, color=ui.color(1.0, 1.0, 0.0, 0.5)) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, 0)): sc.Rectangle(1, 1, color=ui.color(1.0, 1.0, 1.0, 0.5)) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(-0.25, -0.25, 0.1)): sc.Rectangle(1, 1, color=ui.color(1.0, 0.0, 1.0, 0.5)) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_vertexindices(self): window = await self.create_test_window(500, 250) with window.frame: proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: # two triangles, the first one is red and second one is blue point_count = 3 points = [[-1, -1, 0], [2, -1, 0], [3, 1, 0], [4, 0, -1], [3, 1, 0]] vertex_indices = [0, 1, 2, 1, 3, 2] colors = [[1, 0, 0, 1]] * 3 + [[0, 0, 1, 1]] * 3 sc.PolygonMesh(points, colors, [point_count, point_count], vertex_indices) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_polygon_mesh_wireframe(self): window = await self.create_test_window(500, 250) with window.frame: proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: # two triangles, the first one is red and second one is blue point_count = 3 points = [[-1, -1, 0], [2, -1, 0], [3, 1, 0], [4, 0, -1], [3, 1, 0]] vertex_indices = [0, 1, 2, 1, 3, 2] colors = [[1, 0, 0, 1]] * 3 + [[0, 0, 1, 1]] * 3 thicknesses = [3] * 6 sc.PolygonMesh( points, colors, [point_count, point_count], vertex_indices, thicknesses=thicknesses, wireframe=True ) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir)
36,449
Python
44.223325
120
0.515213
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_widget.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from omni.ui_scene import scene as sc from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import carb import omni.appwindow import omni.kit.app import omni.ui as ui from omni.ui import color as cl KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent CURRENT_PATH = Path(__file__).parent.joinpath("../../../data") class TestWidget(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): """General ability to use widgets""" window = await self.create_test_window() with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: transform = sc.Matrix44.get_translation_matrix(0, 0, 0) transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4) with sc.Transform(transform=transform): with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): widget = sc.Widget(500, 500, update_policy=sc.Widget.UpdatePolicy.ON_DEMAND) with widget.frame: ui.Label("Hello world", style={"font_size": 100}) await self.wait_n_updates(2) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_resolution(self): """General ability to use widgets""" window = await self.create_test_window() with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: transform = sc.Matrix44.get_translation_matrix(0, 0, 0) transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4) with sc.Transform(transform=transform): with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): widget = sc.Widget(500, 500, update_policy=sc.Widget.UpdatePolicy.ON_DEMAND) with widget.frame: ui.Label("Hello world", style={"font_size": 100}, word_wrap=True) await self.wait_n_updates(2) widget.resolution_width = 250 widget.resolution_height = 250 await self.wait_n_updates(2) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_transparency(self): """General ability to use widgets""" window = await self.create_test_window() with window.frame: with ui.ZStack(): # Background ui.Rectangle(style={"background_color": ui.color(0.5, 0.5, 0.5)}) # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: transform = sc.Matrix44.get_translation_matrix(0, 0, 0) transform *= sc.Matrix44.get_scale_matrix(0.3, 0.3, 0.3) with sc.Transform(transform=transform): with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): widget = sc.Widget(500, 500, update_policy=sc.Widget.UpdatePolicy.ON_DEMAND) with widget.frame: with ui.VStack(): ui.Label("NVIDIA", style={"font_size": 100, "color": ui.color(1.0, 1.0, 1.0, 0.5)}) ui.Label("NVIDIA", style={"font_size": 100, "color": ui.color(0.0, 0.0, 0.0, 0.5)}) ui.Label("NVIDIA", style={"font_size": 100, "color": ui.color(1.0, 1.0, 1.0, 1.0)}) await self.wait_n_updates(2) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_click(self): """General ability to use mouse with widgets""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) was_clicked = [False] was_pressed = [False, False, False] was_released = [False, False, False] def click(): was_clicked[0] = True def press(x, y, b, m): was_pressed[b] = True def release(x, y, b, m): was_released[b] = True with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: transform = sc.Matrix44.get_translation_matrix(0, 0, 0) transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4) with sc.Transform(transform=transform): with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): widget = sc.Widget(500, 500) with widget.frame: # Put the button to the center with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() ui.Button("Hello world", width=0, clicked_fn=click, mouse_pressed_fn=press, mouse_released_fn=release) ui.Spacer() ui.Spacer() ref = ui_test.WidgetRef(scene_view, "") await self.wait_n_updates(2) # Click in the center await ui_test.emulate_mouse_move_and_click(ref.center) await self.wait_n_updates(2) self.assertTrue(was_clicked[0]) self.assertTrue(was_pressed[0]) self.assertTrue(was_released[0]) self.assertFalse(was_pressed[1]) self.assertFalse(was_released[1]) self.assertFalse(was_pressed[2]) self.assertFalse(was_released[2]) # Right-click await ui_test.emulate_mouse_move_and_click(ref.center, right_click=True) await self.wait_n_updates(2) self.assertTrue(was_pressed[1]) self.assertTrue(was_released[1]) self.assertFalse(was_pressed[2]) self.assertFalse(was_released[2]) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_keyboard(self): """General ability to use mouse with widgets""" import omni.kit.ui_test as ui_test window = await self.create_test_window(block_devices=False) with window.frame: # Camera matrices projection = [1e-2 * 3, 0, 0, 0] projection += [0, 1e-2 * 3, 0, 0] projection += [0, 0, 2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -5) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: transform = sc.Matrix44.get_translation_matrix(0, 0, 0) transform *= sc.Matrix44.get_scale_matrix(0.4, 0.4, 0.4) with sc.Transform(transform=transform): with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): widget = sc.Widget(500, 500) with widget.frame: # Put the button to the center with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() ui.StringField() ui.Spacer() ui.Spacer() ref = ui_test.WidgetRef(scene_view, "") await self.wait_n_updates(2) # Click in the center await ui_test.emulate_mouse_move_and_click(ref.center) await self.wait_n_updates(2) await ui_test.emulate_char_press("NVIDIA Omniverse") await self.wait_n_updates(2) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_widget_color_not_leak(self): class Manipulator(sc.Manipulator): def on_build(self): with sc.Transform(scale_to=sc.Space.SCREEN): with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): widget = sc.Widget( 100, 100, update_policy=sc.Widget.UpdatePolicy.ALWAYS ) sc.Arc( radius=20, wireframe=False, thickness=2, tesselation=16, color=cl.red, ) window = await self.create_test_window(block_devices=False) with window.frame: projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, -2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, 5) with sc.SceneView(sc.CameraModel(projection, view)).scene: Manipulator() await self.wait_n_updates(2) await self.finalize_test(golden_img_dir=self._golden_img_dir)
10,896
Python
38.625454
119
0.530195
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_transform_basis.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## __all__ = ["TestTransformBasis"] import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from pathlib import Path from omni.ui_scene import scene as sc from omni.ui import color as cl import carb KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent class TestTransformBasis(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_transform_basis(self): class ConstantTransformBasis(sc.TransformBasis): def __init__(self, x: float, y: float, z: float, **kwargs): super().__init__(**kwargs) self.__matrix = sc.Matrix44.get_translation_matrix(x, y, z) def get_matrix(self): return self.__matrix window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True) transl = sc.Matrix44.get_translation_matrix(0, -1, -6) view = transl * rotation with window.frame: self.scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) positions = [0, 0, 0] sizes = [20] white = cl(1.0, 1.0, 1.0, 1.0) red = cl(1.0, 0.0, 0.0, 1.0) green = cl(0.0, 1.0, 0.0, 1.0) blue = cl(0.0, 0.0, 1.0, 1.0) yellow = cl(1.0, 1.0, 0.0, 1.0) with self.scene_view.scene: sc.Points(positions, sizes=sizes, colors=[white]) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(2, 0, 0)): sc.Points(positions, sizes=sizes, colors=[red]) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 2, 0)): sc.Points(positions, sizes=sizes, colors=[green]) # Now throw in a transform with a custom basis, overriding the parent transforms with sc.Transform(basis=ConstantTransformBasis(-2, 0, 0)): sc.Points(positions, sizes=sizes, colors=[blue]) with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 2, 0)): sc.Points(positions, sizes=sizes, colors=[yellow]) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) self.scene_view.scene.clear() self.scene_view = None del window async def test_transform_basis_python_class_deleted(self): self.was_deleted = False def do_delete(): self.was_deleted = True class LoggingTransformBasis(sc.TransformBasis): def __init__(self, **kwargs): super().__init__(**kwargs) self.__matrix = sc.Matrix44.get_translation_matrix(0, 0, 0) def __del__(self): do_delete() def get_matrix(self): return self.__matrix xform = sc.Transform(basis=LoggingTransformBasis()) self.assertFalse(self.was_deleted, "Python child class of sc.TransformBasis was deleted too soon") del xform self.assertTrue(self.was_deleted, "Python child class of sc.TransformBasis was not deleted") del self.was_deleted
4,181
Python
35.365217
116
0.596508
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .test_arc import TestArc from .test_camera import TestCamera from .test_shapes import TestShapes from .test_container import TestContainer from .test_gestures import TestGestures from .test_manipulator import TestManipulator from .test_widget import TestWidget from .test_scene import TestScene from .test_scroll import TestScroll from .test_transform_basis import TestTransformBasis
817
Python
42.052629
76
0.824969
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_camera.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from omni.ui.tests.test_base import OmniUiTest from omni.ui_scene import scene as sc from pathlib import Path import carb import omni.kit.test import omni.ui as ui KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent class TestCamera(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [1.7, 0, 0, 0, 0, 3, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, 50, 0, True) transl = sc.Matrix44.get_translation_matrix(0, 0, -6) view = transl * rotation with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: # Edges of cube sc.Line([-1, -1, -1], [1, -1, -1]) sc.Line([-1, 1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [1, -1, 1]) sc.Line([-1, 1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, 1, -1]) sc.Line([1, -1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [-1, 1, 1]) sc.Line([1, -1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, -1, 1]) sc.Line([-1, 1, -1], [-1, 1, 1]) sc.Line([1, -1, -1], [1, -1, 1]) sc.Line([1, 1, -1], [1, 1, 1]) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_distant_camera(self): window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0] # Move camera rotation = sc.Matrix44.get_rotation_matrix(-25, 55, 0, True) transl = sc.Matrix44.get_translation_matrix(-10000000000, 10000000000, -20000000000) view = transl * rotation with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: sc.Line([-10000000000, -10000000000, -10000000000], [-2000000000, -10000000000, -10000000000]) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_camera_model(self): class CameraModel(sc.AbstractManipulatorModel): def __init__(self): super().__init__() self._angle = 0 def append_angle(self, delta: float): self._angle += delta * 100 # Inform SceneView that view matrix is changed self._item_changed("view") def get_as_floats(self, item): """Called by SceneView to get projection and view matrices""" if item == self.get_item("projection"): # Projection matrix return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0] if item == self.get_item("view"): # Move camera rotation = sc.Matrix44.get_rotation_matrix(30, self._angle, 0, True) transl = sc.Matrix44.get_translation_matrix(0, 0, -8) view = transl * rotation return [view[i] for i in range(16)] def on_mouse_dragged(sender): # Change the model's angle according to mouse x offset mouse_moved = sender.gesture_payload.mouse_moved[0] sender.scene_view.model.append_angle(mouse_moved) window = await self.create_test_window(width=512, height=256) camera_model = CameraModel() # check initial projection and view matrix proj = camera_model.get_as_floats(camera_model.get_item("projection")) view = camera_model.get_as_floats(camera_model.get_item("view")) self.assertEqual(proj, [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, -1, 0, 0, -2, 0]) self.assertAlmostEqual(view[5], 0.866025, places=5) self.assertAlmostEqual(view[10], 0.866025, places=5) self.assertAlmostEqual(view[6], 0.5, places=5) self.assertAlmostEqual(view[9], -0.5, places=5) with window.frame: with sc.SceneView(camera_model, height=200).scene: # Camera control sender = sc.Screen(gesture=sc.DragGesture(on_changed_fn=on_mouse_dragged)) # Edges of cube sc.Line([-1, -1, -1], [1, -1, -1]) sc.Line([-1, 1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [1, -1, 1]) sc.Line([-1, 1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, 1, -1]) sc.Line([1, -1, -1], [1, 1, -1]) sc.Line([-1, -1, 1], [-1, 1, 1]) sc.Line([1, -1, 1], [1, 1, 1]) sc.Line([-1, -1, -1], [-1, -1, 1]) sc.Line([-1, 1, -1], [-1, 1, 1]) sc.Line([1, -1, -1], [1, -1, 1]) sc.Line([1, 1, -1], [1, 1, 1]) await self.wait_n_updates() await self.finalize_test(golden_img_dir=self._golden_img_dir)
6,090
Python
39.879194
116
0.534483
omniverse-code/kit/exts/omni.ui.scene/omni/ui_scene/tests/test_gestures.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .gesture_manager_utils import Manager from functools import partial from omni.ui import color as cl from omni.ui_scene import scene as sc from omni.ui.tests.test_base import OmniUiTest import omni.kit.ui_test as ui_test from pathlib import Path import carb import omni.kit import omni.ui as ui KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent class TestGestures(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = KIT_ROOT.joinpath("data/tests/omni.ui.tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_gesture_select(self): def _on_shape_clicked(shape): """Called when the user clicks the point""" shape.color = cl.red window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: select = sc.ClickGesture(_on_shape_clicked) mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)] select.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) sc.Rectangle(color=cl.blue, gesture=select) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_gesture_drag(self): class MyDragGesture(sc.DragGesture): def __init__(self): super().__init__() self.began_called = False self.changed_called = False self.ended_called = False def can_be_prevented(self, gesture): return True def on_began(self): self.began_called = True def on_changed(self): self.changed_called = True def on_ended(self): self.ended_called = True class PriorityManager(Manager): """ Manager makes the gesture high priority """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def can_be_prevented(self, gesture): return False def should_prevent(self, gesture, preventer): return gesture.state == sc.GestureState.CHANGED and ( preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED ) window = await self.create_test_window() # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, ) with scene_view.scene: # Click, move, release in the center drag = MyDragGesture() # Clicked, down, released mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0.1, 0), (0.1, 0), (0.1, 0)] drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) rectangle = sc.Rectangle(color=cl.blue, gesture=drag) await self.wait_n_updates(30) self.assertTrue(drag.began_called) self.assertTrue(drag.changed_called) self.assertTrue(drag.ended_called) # Click, move, release on the side drag = MyDragGesture() mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0.9), (0, 0.9), (0, 0.9), (0.1, 0.9), (0.1, 0.9), (0.1, 0.9)] drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) rectangle.gestures = [drag] await self.wait_n_updates(30) self.assertFalse(drag.began_called) self.assertFalse(drag.changed_called) self.assertFalse(drag.ended_called) # Testing preventing drag = MyDragGesture() mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0.1, 0), (0.1, 0), (0.1, 0)] drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) rectangle.gestures = [ sc.DragGesture(manager=PriorityManager(mouse_action_sequence, mouse_position_sequence, scene_view)), drag, ] await self.wait_n_updates(30) self.assertTrue(drag.began_called) self.assertFalse(drag.changed_called) self.assertTrue(drag.ended_called) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_gesture_callback(self): def move(transform: sc.Transform, shape: sc.AbstractShape): """Called by the gesture""" translate = shape.gesture_payload.moved # Move transform to the direction mouse moved current = sc.Matrix44.get_translation_matrix(*translate) transform.transform *= current window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (0.15, 0), (0.3, 0), (0.3, 0), (0.3, 0)] mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) with scene_view.scene: transform = sc.Transform() with transform: sc.Line( [-1, 0, 0], [1, 0, 0], color=cl.blue, thickness=5, gesture=sc.DragGesture( manager = mgr, on_changed_fn=partial(move, transform) ) ) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_gesture_override(self): class Move(sc.DragGesture): def __init__(self, transform: sc.Transform): super().__init__() self.__transform = transform def on_began(self): self.sender.color = cl.red def on_changed(self): translate = self.sender.gesture_payload.moved # Move transform to the direction mouse moved current = sc.Matrix44.get_translation_matrix(*translate) self.__transform.transform *= current def on_ended(self): self.sender.color = cl.blue window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: transform=sc.Transform() with transform: move = Move(transform) mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (-0.25, -0.07), (-0.6, -0.15), (-0.6, -0.15), (-0.6, -0.15)] move.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) sc.Rectangle(color=cl.blue, gesture=move) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_gesture_manager(self): class PrimeManager(Manager): def __init__(self, mouse_action_sequence, mouse_position_sequence, scene_view): super().__init__(mouse_action_sequence, mouse_position_sequence, scene_view) def should_prevent(self, gesture, preventer): # prime gesture always wins if preventer.name == "prime": return True def move(transform: sc.Transform, shape: sc.AbstractShape): """Called by the gesture""" translate = shape.gesture_payload.moved current = sc.Matrix44.get_translation_matrix(*translate) transform.transform *= current window = await self.create_test_window(width=512, height=256) # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0),(0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (-0.25, -0.15), (-0.6, -0.3), (-0.6, -0.3), (-0.6, -0.3)] mgr = PrimeManager(mouse_action_sequence, mouse_position_sequence, scene_view) # create two cubes overlap with each other # since the red one has the name of prime, it wins the gesture of move with scene_view.scene: transform1 = sc.Transform() with transform1: sc.Rectangle( color=cl.blue, gesture=sc.DragGesture( manager=mgr, on_changed_fn=partial(move, transform1) ) ) transform2 = sc.Transform() with transform2: sc.Rectangle( color=cl.red, gesture=sc.DragGesture( name="prime", manager=mgr, on_changed_fn=partial(move, transform2) ) ) await self.wait_n_updates(30) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_hover_gesture(self): class HoverGesture(sc.HoverGesture): def on_began(self): self.sender.color = cl.red def on_ended(self): self.sender.color = cl.blue window = await self.create_test_window() # Projection matrix proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -1) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT ) mouse_action_sequence = [(0, 0, 0)] * 10 # Move mouse close (2px) to the second line and after that on the # first line. The second line will be blue, the first one is the # red. mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0.028)] * 3 + [(0, 0)] * 5 mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) # create two cubes overlap with each other # since the red one has the name of prime, it wins the gesture of move with scene_view.scene: sc.Line([-1, -1, 0], [1, 1, 0], thickness=1, gesture=HoverGesture(manager=mgr)) sc.Line([-1, 1, 0], [1, -0.9, 0], thickness=4, gesture=HoverGesture(manager=mgr)) await self.wait_n_updates(9) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_hover_gesture_trigger_on_view_hover(self): """Testing trigger_on_view_hover""" class HoverGesture(sc.HoverGesture): def __init__(self, manager): super().__init__(trigger_on_view_hover=True, manager=manager) def on_began(self): self.sender.color = cl.red def on_ended(self): self.sender.color = cl.blue window = await self.create_test_window() # Projection matrix proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -1) with window.frame: # The same setup like in test_hover_gesture, but we have ZStack on top with ui.ZStack(): scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT ) ui.ZStack(content_clipping=1) mouse_action_sequence = [(0, 0, 0)] * 10 mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0.028)] * 3 + [(0, 0)] * 5 mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) with scene_view.scene: sc.Line([-1, -1, 0], [1, 1, 0], thickness=1, gesture=HoverGesture(manager=mgr)) sc.Line([-1, 1, 0], [1, -0.9, 0], thickness=4, gesture=HoverGesture(manager=mgr)) await self.wait_n_updates(9) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_intersection_thickness(self): class HoverGesture(sc.HoverGesture): def on_began(self): self.sender.color = cl.red def on_ended(self): self.sender.color = cl.blue window = await self.create_test_window() # Projection matrix proj = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -1) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT ) mouse_action_sequence = [(0, 0, 0)] * 10 # Move mouse close (about 4px) to the second line and after that on # the first line. The second line will be blue, the first one is the # red. mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0.43)] * 3 + [(0, 0)] * 5 mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) # create two cubes overlap with each other # since the red one has the name of prime, it wins the gesture of move with scene_view.scene: sc.Line([-1, -1, 0], [1, 1, 0], thickness=1, gesture=HoverGesture(manager=mgr)) sc.Line( [-1, 1, 0], [1, 0, 0], thickness=1, intersection_thickness=8, gesture=HoverGesture(manager=mgr) ) await self.wait_n_updates(9) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_hover_smallscale(self): # Flag that it was hovered hovered = [0, 0] class HoverGesture(sc.HoverGesture): def __init__(self, manager: sc.GestureManager): super().__init__(manager=manager) def on_began(self): if isinstance(self.sender, sc.Line): hovered[0] = 1 elif isinstance(self.sender, sc.Rectangle): hovered[1] = 1 self.sender.color = [0, 0, 1, 1] def on_ended(self): self.sender.color = [1, 1, 1, 1] class SmallScale(sc.Manipulator): def __init__(self, manager: sc.GestureManager): super().__init__() self.manager = manager def on_build(self): transform = sc.Matrix44.get_translation_matrix(-0.01, 0, 0) with sc.Transform(transform=transform): sc.Line([0, 0.005, 0], [0, 0.01, 0], gestures=HoverGesture(manager=self.manager)) sc.Rectangle(0.01, 0.01, gestures=HoverGesture(manager=self.manager)) window = await self.create_test_window() proj = [ 4.772131, 0.000000, 0.000000, 0.000000, 0.000000, 7.987040, 0.000000, 0.000000, 0.000000, 0.000000, -1.002002, -1.000000, 0.000000, 0.000000, -0.200200, 0.000000, ] view = [ 0.853374, -0.124604, 0.506188, 0.000000, -0.000000, 0.971013, 0.239026, 0.000000, -0.521299, -0.203979, 0.828638, 0.000000, 0.008796, -0.003659, -0.198528, 1.000000, ] with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT ) mouse_action_sequence = [(0, 0, 0)] * 10 # Move mouse close (about 4px) to the second line and after that on # the first line. The second line will be blue, the first one is the # red. mouse_position_sequence = [(-0, -1)] * 2 + [(0, 0)] * 3 + [(0, 0.1)] * 5 mgr = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) with scene_view.scene: SmallScale(mgr) await self.wait_n_updates(9) self.assertTrue(hovered[0]) self.assertTrue(hovered[1]) await self.finalize_test_no_image() async def test_gesture_click(self): single_click, double_click = False, False def _on_shape_clicked(shape): nonlocal single_click single_click = True def _on_shape_double_clicked(shape): nonlocal double_click double_click = True window = await self.create_test_window(width=1440, height=900, block_devices=False) # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with scene_view.scene: click_1 = sc.ClickGesture(_on_shape_clicked) click_2 = sc.DoubleClickGesture(_on_shape_double_clicked) sc.Rectangle(color=cl.blue, gestures=[click_1, click_2]) await self.wait_n_updates(15) single_click, double_click = False, False await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(720, 100), double=False) await self.wait_n_updates(15) self.assertTrue(single_click) self.assertFalse(double_click) await self.wait_n_updates(15) single_click, double_click = False, False await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(720, 100), double=True) await self.wait_n_updates(15) self.assertTrue(double_click) self.assertFalse(single_click) async def test_raw_input(self): class MyDragGesture(sc.DragGesture): def __init__(self): super().__init__() self.inputs = [] def on_began(self): self.inputs.append(self.raw_input) def on_changed(self): self.inputs.append(self.raw_input) def on_ended(self): self.inputs.append(self.raw_input) window = await self.create_test_window() # Projection matrix proj = [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, ) with scene_view.scene: # Click, move, release in the center drag = MyDragGesture() # Clicked, down, released mouse_action_sequence = [(0, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)] mouse_position_sequence = [(0, 0), (0, 0), (0, 0), (0.1, 0), (0.1, 0), (0.1, 0)] drag.manager = Manager(mouse_action_sequence, mouse_position_sequence, scene_view) sc.Rectangle(color=cl.blue, gesture=drag) for _ in range(30): await omni.kit.app.get_app().next_update_async() self.assertEqual(len(drag.inputs), 3) self.assertEqual(drag.inputs[0].mouse_origin, drag.inputs[1].mouse_origin) self.assertEqual(drag.inputs[1].mouse_origin, drag.inputs[2].mouse_origin) for i in drag.inputs: self.assertEqual(i.mouse_direction, sc.Vector3(0, 0, 1)) await self.finalize_test_no_image() async def test_check_mouse_moved_off(self): import omni.kit.ui_test as ui_test from carb.input import MouseEventType window = await self.create_test_window(block_devices=False) proj = [0.3, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: with ui.ZStack(): scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, ) class Move(sc.DragGesture): def __init__(self, transform: sc.Transform): super().__init__(check_mouse_moved=False) self.__transform = transform def on_began(self): self.sender.color = cl.red def on_changed(self): translate = self.sender.gesture_payload.moved # Move transform to the direction mouse moved current = sc.Matrix44.get_translation_matrix(*translate) self.__transform.transform *= current def on_ended(self): self.sender.color = cl.blue with scene_view.scene: transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, -1)) with transform: sc.Rectangle(color=cl.blue, gesture=Move(transform)) with sc.Transform(transform=sc.Matrix44.get_scale_matrix(3, 3, 3)): sc.Rectangle(color=cl.grey) scene_view_ref = ui_test.WidgetRef(scene_view, "") await ui_test.wait_n_updates() await ui_test.input.emulate_mouse(MouseEventType.MOVE, scene_view_ref.center) # Press mouse button await ui_test.wait_n_updates() await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN) # Move camera await ui_test.wait_n_updates() view *= sc.Matrix44.get_translation_matrix(0, 1.0, 0) scene_view.model = sc.CameraModel(proj, view) # Release mouse button await ui_test.wait_n_updates() await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP) await ui_test.wait_n_updates() await self.finalize_test() async def test_check_mouse_moved_on(self): import omni.kit.ui_test as ui_test from carb.input import MouseEventType window = await self.create_test_window(block_devices=False) proj = [0.3, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 2e-7, 0, 0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, -10) with window.frame: with ui.ZStack(): scene_view = sc.SceneView( sc.CameraModel(proj, view), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, ) class Move(sc.DragGesture): def __init__(self, transform: sc.Transform): super().__init__(check_mouse_moved=True) self.__transform = transform def on_began(self): self.sender.color = cl.red def on_changed(self): translate = self.sender.gesture_payload.moved # Move transform to the direction mouse moved current = sc.Matrix44.get_translation_matrix(*translate) self.__transform.transform *= current def on_ended(self): self.sender.color = cl.blue with scene_view.scene: transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, -1)) with transform: sc.Rectangle(color=cl.blue, gesture=Move(transform)) with sc.Transform(transform=sc.Matrix44.get_scale_matrix(3, 3, 3)): sc.Rectangle(color=cl.grey) scene_view_ref = ui_test.WidgetRef(scene_view, "") await ui_test.wait_n_updates() await ui_test.input.emulate_mouse(MouseEventType.MOVE, scene_view_ref.center) # Press mouse button await ui_test.wait_n_updates() await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN) # Move camera await ui_test.wait_n_updates() view *= sc.Matrix44.get_translation_matrix(0, 1.0, 0) scene_view.model = sc.CameraModel(proj, view) # Release mouse button await ui_test.wait_n_updates() await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP) await ui_test.wait_n_updates() await self.finalize_test() async def test_check_no_crash(self): class ClickGesture(sc.ClickGesture): def __init__(self, *args, **kwargs): # Passing `self` while using `super().__init__` is legal python, but not correct. # However, it shouldn't crash. super().__init__(self, *args, **kwargs) with self.assertRaises(TypeError) as cm: self.assertTrue(bool(ClickGesture())) await self.finalize_test_no_image()
27,877
Python
38.655761
123
0.5431
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/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") fl.welcome_extensions_scroll_size = 10 EXTENSIONS_PAGE_STYLE = { "Extensions.Label": {"color": cl.welcome_label}, "Extensions.Button": { "padding": 0, "background_color": cl.welcome_content_background, "stack_direction": ui.Direction.LEFT_TO_RIGHT, }, "Extensions.Button.Label": {"color": cl.welcome_label}, "Extensions.Button.Image::refresh": {"image_url": f"{ICON_PATH}/refresh.svg", "color": cl.welcome_label}, "Extensions.Button.Image::update": {"image_url": f"{ICON_PATH}/update_all.svg", "color": cl.welcome_label}, "Extensions.Frame": { "background_color": cl.transparent, "secondary_color": 0xFF666666, "border_radius": 0, "scrollbar_size": 10, }, "Card.Background": {"border_radius": 10, "border_width": 1, "border_color": 0xFF707070, "background_color": 0xFF2E2C29}, "Card.Name": {"color": 0xFF38B583, "font_size": 16}, "Card.Icon": {"padding": 0, "margin": 0}, "Card.Version": {"color": cl.welcome_label, "font_size": 10}, "Card.Description": {"color": cl.welcome_label, "font_size": 16}, "Card.Button": {"border_radius": 4, "background_color": 0xFF38B583, "margin": 10}, "Card.Button.Label": {"color": 0xFFD9F1E8}, }
1,471
Python
38.783783
124
0.647179
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/extension.py
import carb import omni.ext import omni.ui as ui from omni.kit.welcome.window import register_page from omni.ui import constant as fl from .extensions_widget import ExtensionsWidget from .style import EXTENSIONS_PAGE_STYLE, ICON_PATH _extension_instance = None class ExtensionsPageExtension(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) def on_shutdown(self): global _extension_instance _extension_instance = None def build_ui(self) -> None: with ui.ZStack(style=EXTENSIONS_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="Open Extension Manager", image_url=f"{ICON_PATH}/external_link.svg", width=0, spacing=10, clicked_fn=self.__show_extension_manager, style_type_name_override="Title.Button" ) ui.Spacer() ui.Spacer() ExtensionsWidget() def __show_extension_manager(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.window.extensions", True) from omni.kit.window.extensions import get_instance as get_extensions_instance inst_ref = get_extensions_instance() inst_ref().show_window(True) except Exception as e: carb.log_warn(f"Failed to show extension manager: {e}")
1,979
Python
35.666666
90
0.554826
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/extensions_widget.py
from typing import List import omni.kit.app import omni.ui as ui from omni.ui import constant as fl from .extensions_model import ExtensionItem, ExtensionsModel class ExtensionCard: def __init__(self, item: ExtensionItem): self._item = item self._build_ui() def _build_ui(self): ICON_SIZE = 40 with ui.ZStack(height=80): ui.Rectangle(style_type_name_override="Card.Background") with ui.HStack(): with ui.HStack(width=250): with ui.VStack(width=52): ui.Spacer() #with ui.Frame(height=ICON_SIZE, width=ICON_SIZE): # ui.Image(self._item.icon, style_type_name_override="Card.Icon") with ui.HStack(): ui.Spacer() ui.Image(self._item.icon, width=ICON_SIZE, height=ICON_SIZE, style_type_name_override="Card.Icon") ui.Spacer() ui.Label(f"v{self._item.version}", alignment=ui.Alignment.CENTER, style_type_name_override="Card.Version") ui.Spacer() ui.Label(self._item.name, alignment=ui.Alignment.LEFT_CENTER, style_type_name_override="Card.Name") with ui.ZStack(): ui.Label(self._item.description, alignment=ui.Alignment.LEFT_CENTER, style_type_name_override="Card.Description") with ui.VStack(width=130): ui.Spacer() ui.Button("UPDATE", height=32, style_type_name_override="Card.Button", mouse_pressed_fn=lambda x, y, b, a: self.__update()) ui.Spacer() def __update(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.window.extensions", True) from omni.kit.window.extensions import ext_controller # If autoload for that one is enabled, move it to latest: ''' # TODO: if ext_controller.is_autoload_enabled(self._item.enabled_id): ext_controller.toggle_autoload(self._item.enabled_id, False) if check_can_be_toggled(self._item.latest_id, for_autoload=True): ext_controller.toggle_autoload(self._item.latest_id, True) ''' # If extension is enabled, switch off to latest: if self._item.enabled: self._toggle_extension(self._item.enabled_id, False) self._toggle_extension(self._item.latest_id, True) except Exception as e: carb.log_warn(f"Faild to update {self._item.enabled_id} to {self._item.latest_id}: {e}") def _toggle_extension(self, ext_id: str, enable: bool): ''' # TODO: if enable and not check_can_be_toggled(ext_id): return False ''' omni.kit.commands.execute("ToggleExtension", ext_id=ext_id, enable=enable) return True class ExtensionsWidget: def __init__(self): self._build_ui() def _build_ui(self): with ui.HStack(): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.VStack(spacing=5): with ui.HStack(height=30): ui.Spacer(width=fl._find("welcome_extensions_scroll_size")) ui.Label("New Updates", style_type_name_override="Extensions.Label") ui.Spacer() ui.Button( "CHECK FOR UPDATES", width=0, image_width=16, spacing=4, name="refresh", style_type_name_override="Extensions.Button", clicked_fn=self.__refresh ) ui.Spacer(width=10) ui.Button( "UPDATE ALL", width=0, image_width=16, spacing=4, name="update", style_type_name_override="Extensions.Button", clicked_fn=self.__update_all ) ui.Spacer(width=fl._find("welcome_extensions_scroll_size")) with ui.HStack(): ui.Spacer(width=fl._find("welcome_extensions_scroll_size")) self._model = ExtensionsModel() self._frame = ui.Frame(build_fn=self._build_ext_cards) ui.Spacer(width=fl._find("welcome_content_padding_x")) def _build_exts(self): self._model = ExtensionsModel() self._frame = ui.Frame(build_fn=self._build_ext_cards) def _build_ext_cards(self): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="Extensions.Frame" ): with ui.VStack(spacing=5): for item in self._model.get_item_children(None): ExtensionCard(item) def __refresh(self): self._model.refresh() with self._frame: self._frame.call_build_fn() def __update_all(self): pass
5,453
Python
40.633587
143
0.526683
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/extensions_model.py
import os from functools import lru_cache from typing import List, Optional import omni.kit.app import omni.ui as ui ext_manager = None # Sync only once for now @lru_cache() def _sync_registry(): ext_manager.refresh_registry() @lru_cache() def get_extpath_git_ext(): try: import omni.kit.extpath.git as git_ext return git_ext except ImportError: return None class ExtensionItem(ui.AbstractItem): def __init__(self, ext_info: dict): super().__init__() self.name = ext_info.get("fullname") enabled_version = ext_info.get("enabled_version") self.enabled_id = enabled_version.get("id") self.version = self.__get_version(self.enabled_id) latest_version = ext_info.get("latest_version") self.latest_id = latest_version.get("id") self.flags = ext_info.get("flags") self.enabled = bool(self.flags & omni.ext.EXTENSION_SUMMARY_FLAG_ANY_ENABLED) ext_info_local = ext_manager.get_extension_dict(self.enabled_id) self.path = ext_info_local.get("path", "") package_dict = ext_info_local.get("package", {}) self.icon = self.__get_icon(package_dict) self.description = package_dict.get("description", "") or "No Description" def __get_version(self, ext_id: str) -> str: """Convert 'omni.foo-tag-1.2.3' to '1.2.3'""" a, b, *_ = ext_id.split("-") + [""] if b and b[0:1].isdigit(): return f"{b}" return "" def __get_icon(self, package_dict: dict) -> str: path = package_dict.get("icon", None) if path: icon_path = os.path.join(self.path, path) if os.path.exists(icon_path): return icon_path return "" class ExtensionsModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._items: List[ExtensionItem] = [] global ext_manager app = omni.kit.app.get_app() ext_manager = app.get_extension_manager() self.refresh() def get_item_children(self, item: Optional[ExtensionItem]) -> List[ExtensionItem]: return self._items def refresh(self): # Refresh exts (comes from omni.kit.window.extensions) get_extpath_git_ext.cache_clear() _sync_registry() ext_summaries = ext_manager.fetch_extension_summaries() updates_exts = [ ext for ext in ext_summaries if ext["enabled_version"]["id"] and ext["enabled_version"]["id"] != ext["latest_version"]["id"] ] self._items = [ExtensionItem(ext) for ext in updates_exts]
2,619
Python
29.823529
136
0.599847
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/tests/test_page.py
from pathlib import Path import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from ..extension import ExtensionsPageExtension 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 = ExtensionsPageExtension() ext.on_startup("omni.kit.welcome.extensions-1.1.0") ext.build_ui() await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="page.png")
1,012
Python
30.656249
99
0.670949
omniverse-code/kit/exts/omni.kit.welcome.extensions/omni/kit/welcome/extensions/tests/__init__.py
from .test_page import *
24
Python
23.999976
24
0.75
omniverse-code/kit/exts/omni.kit.welcome.extensions/docs/index.rst
omni.kit.welcome.extensions ########################### .. toctree:: :maxdepth: 1 CHANGELOG
100
reStructuredText
11.624999
27
0.49
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/tools.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 pathlib import Path from typing import List import traceback import carb import carb.dictionary import carb.events import carb.settings import omni.kit.app import omni.kit.context_menu import omni.usd from omni.kit.manipulator.tool.snap import SnapToolButton from omni.kit.manipulator.transform.manipulator import TransformManipulator from omni.kit.manipulator.transform.toolbar_tool import SimpleToolButton from omni.kit.manipulator.transform.types import Operation from .settings_constants import Constants as prim_c from .tool_models import LocalGlobalModeModel from .toolbar_registry import get_toolbar_registry ICON_FOLDER_PATH = Path( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) TOOLS_ENABLED_SETTING_PATH = "/exts/omni.kit.manipulator.prim2.core/tools/enabled" class SelectionPivotTool(SimpleToolButton): # menu entry only needs to register once __menu_entries = [] @classmethod def register_menu(cls): def build_placement_setting_entry(setting: str): menu = { "name": setting, "checked_fn": lambda _: carb.settings.get_settings().get(prim_c.MANIPULATOR_PLACEMENT_SETTING) == setting, "onclick_fn": lambda _: carb.settings.get_settings().set(prim_c.MANIPULATOR_PLACEMENT_SETTING, setting), } return menu menu = [ build_placement_setting_entry(s) for s in [ prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE, prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER, prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER, prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM, ] ] for item in menu: cls.__menu_entries.append(omni.kit.context_menu.add_menu(item, "sel_pivot", "omni.kit.manipulator.prim")) @classmethod def unregister_menu(cls): for sub in cls.__menu_entries: sub.release() cls.__menu_entries.clear() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO assume the context is "" for VP1 self._usd_context = omni.usd.get_context(self._toolbar_payload.get("usd_context_name", "")) self._selection = self._usd_context.get_selection() enabled_img_url = f"{ICON_FOLDER_PATH}/pivot_location.svg" self._build_widget( button_name="sel_pivot", enabled_img_url=enabled_img_url, model=None, menu_index="sel_pivot", menu_extension_id="omni.kit.manipulator.prim", no_toggle=True, menu_on_left_click=True, tooltip="Selection Pivot Placement", ) # order=1 to register after prim manipulator so _on_selection_changed gets updated len of xformable_prim_paths self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop_by_type( int(omni.usd.StageEventType.SELECTION_CHANGED), self._on_stage_selection_event, name="SelectionPivotTool stage event", order=1, ) if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_selection_changed() def destroy(self): super().destroy() self._stage_event_sub = None if self._model: self._model.destroy() self._model = None @classmethod def can_build(cls, manipulator: TransformManipulator, operation: Operation) -> bool: return operation == Operation.TRANSLATE or operation == Operation.ROTATE or operation == Operation.SCALE def _on_stage_selection_event(self, event: carb.events.IEvent): self._on_selection_changed() def _on_selection_changed(self): selected_xformable_paths_count = ( len(self._manipulator.model.xformable_prim_paths) if self._manipulator.model else 0 ) if self._stack: visible = selected_xformable_paths_count > 0 if self._stack.visible != visible: self._stack.visible = visible self._manipulator.refresh_toolbar() class LocalGlobalTool(SimpleToolButton): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._operation == Operation.TRANSLATE: setting_path = "/app/transform/moveMode" elif self._operation == Operation.ROTATE: setting_path = "/app/transform/rotateMode" else: raise RuntimeError("Invalid operation") self._model = LocalGlobalModeModel(setting_path) enabled_img_url = f"{ICON_FOLDER_PATH}/transformspace_global_dark.svg" disabled_img_url = f"{ICON_FOLDER_PATH}/transformspace_local_dark.svg" self._build_widget( button_name="local_global", enabled_img_url=enabled_img_url, disabled_img_url=disabled_img_url, model=self._model, tooltip="Current Transform Space: World", disabled_tooltip="Current Transform Space: Local" ) def destroy(self): super().destroy() if self._model: self._model.destroy() self._model = None @classmethod def can_build(cls, manipulator: TransformManipulator, operation: Operation) -> bool: return operation == Operation.TRANSLATE or operation == Operation.ROTATE class PrimManipTools: def __init__(self): self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._toolbar_reg = get_toolbar_registry() SelectionPivotTool.register_menu() # one time startup self._builtin_tool_classes = { "prim:1space": LocalGlobalTool, "prim:2snap": SnapToolButton, "prim:3sel_pivot": SelectionPivotTool, } self._registered_tool_ids: List[str] = [] self._sub = self._settings.subscribe_to_node_change_events(TOOLS_ENABLED_SETTING_PATH, self._on_setting_changed) if self._settings.get(TOOLS_ENABLED_SETTING_PATH) is True: self._register_tools() self._pivot_button_group = None # register pivot placement to "factory explorer" toolbar app_name = omni.kit.app.get_app().get_app_filename() if "omni.factory_explorer" in app_name: # add manu entry to factory explorer toolbar manager = omni.kit.app.get_app().get_extension_manager() self._hooks = manager.subscribe_to_extension_enable( lambda _: self._register_main_toolbar_button(), lambda _: self._unregister_main_toolbar_button(), ext_name="omni.explore.toolbar", hook_name="omni.kit.manipulator.prim.pivot_placement listener", ) def __del__(self): self.destroy() def destroy(self): self._hooks = None if self._pivot_button_group is not None: self._unregister_main_toolbar_button() self._unregister_tools() if self._sub is not None: self._settings.unsubscribe_to_change_events(self._sub) self._sub = None SelectionPivotTool.unregister_menu() # one time shutdown def _register_tools(self): for id, tool_class in self._builtin_tool_classes.items(): self._toolbar_reg.register_tool(tool_class, id) self._registered_tool_ids.append(id) def _unregister_tools(self): for id in self._registered_tool_ids: self._toolbar_reg.unregister_tool(id) self._registered_tool_ids.clear() def _on_setting_changed(self, item, event_type): enabled = self._dict.get(item) if enabled and not self._registered_tool_ids: self._register_tools() elif not enabled: self._unregister_tools() def _register_main_toolbar_button(self): try: if not self._pivot_button_group: import omni.explore.toolbar from .pivot_button_group import PivotButtonGroup self._pivot_button_group = PivotButtonGroup() explorer_toolbar_ext = omni.explore.toolbar.get_toolbar_instance() explorer_toolbar_ext.toolbar.add_widget_group(self._pivot_button_group, 1) # also add to MODIFY_TOOLS list, when menu Modify is selected # all items in toolbar will be cleared and re-added from MODIFY_TOOLS list explorer_tools = omni.explore.toolbar.groups.MODIFY_TOOLS explorer_tools.append(self._pivot_button_group) except Exception: carb.log_warn(traceback.format_exc()) def _unregister_main_toolbar_button(self): try: if self._pivot_button_group: import omni.explore.toolbar explorer_toolbar_ext = omni.explore.toolbar.get_toolbar_instance() explorer_toolbar_ext.toolbar.remove_widget_group(self._pivot_button_group) # remove from MODIFY_TOOLS list as well explorer_tools = omni.explore.toolbar.groups.MODIFY_TOOLS if self._pivot_button_group in explorer_tools: explorer_tools.remove(self._pivot_button_group) self._pivot_button_group.clean() self._pivot_button_group = None except Exception: carb.log_warn(traceback.format_exc())
10,032
Python
36.576779
120
0.627691
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext from omni.kit.manipulator.viewport import ManipulatorFactory from .prim_transform_manipulator import PrimTransformManipulator from .prim_transform_manipulator_registry import TransformManipulatorRegistry from .reference_prim_marker import ReferencePrimMarker from .tools import PrimManipTools class ManipulatorPrim(omni.ext.IExt): def on_startup(self, ext_id): self._tools = PrimManipTools() # For VP1 self._legacy_manipulator = PrimTransformManipulator() self._legacy_marker = ManipulatorFactory.create_manipulator( ReferencePrimMarker, usd_context_name="", manipulator_model=self._legacy_manipulator.model, legacy=True ) # For VP2 self._manipulator_registry = TransformManipulatorRegistry() def on_shutdown(self): if self._legacy_manipulator is not None: self._legacy_manipulator.destroy() self._legacy_manipulator = None if self._legacy_marker is not None: ManipulatorFactory.destroy_manipulator(self._legacy_marker) self._legacy_marker = None if self._manipulator_registry is not None: self._manipulator_registry.destroy() self._manipulator_registry = None if self._tools is not None: self._tools.destroy() self._tools = None
1,788
Python
36.270833
115
0.714765
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/__init__.py
from .extension import * from .model import * from .toolbar_registry import *
78
Python
18.749995
31
0.75641
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/prim_transform_manipulator.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import copy from typing import List, Union import carb.dictionary import carb.events import carb.settings import omni.ext import omni.usd from omni.kit.manipulator.selector import ManipulatorBase from omni.kit.manipulator.tool.snap import SnapProviderManager from omni.kit.manipulator.tool.snap import settings_constants as snap_c from omni.kit.manipulator.transform import get_default_style from omni.kit.manipulator.transform.manipulator import TransformManipulator from omni.kit.manipulator.transform.settings_constants import c from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener from omni.kit.manipulator.viewport import ManipulatorFactory from pxr import Sdf, Usd, UsdGeom from .model import PrimRotateChangedGesture, PrimScaleChangedGesture, PrimTransformModel, PrimTranslateChangedGesture from .toolbar_registry import get_toolbar_registry TRANSFORM_GIZMO_HIDDEN_OVERRIDE = "/app/transform/gizmoHiddenOverride" class PrimTransformManipulator(ManipulatorBase): def __init__( self, usd_context_name: str = "", viewport_api=None, name="omni.kit.manipulator.prim2.core", model: PrimTransformModel = None, size: float = 1.0, ): super().__init__(name=name, usd_context_name=usd_context_name) self._dict = carb.dictionary.get_dictionary() self._settings = carb.settings.get_settings() self._usd_context = omni.usd.get_context(usd_context_name) self._selection = self._usd_context.get_selection() self._model_is_external = model is not None self._model = model if self._model_is_external else PrimTransformModel(usd_context_name, viewport_api) self._legacy_mode = viewport_api is None # if no viewport_api is supplied, it is from VP1 self._snap_manager = SnapProviderManager(viewport_api=viewport_api) if self._legacy_mode: self._manipulator = ManipulatorFactory.create_manipulator( TransformManipulator, size=size, model=self._model, enabled=False, gestures=[ PrimTranslateChangedGesture( self._snap_manager, usd_context_name=usd_context_name, viewport_api=viewport_api ), PrimRotateChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), PrimScaleChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), ], tool_registry=get_toolbar_registry(), ) else: self._manipulator = TransformManipulator( size=size, model=self._model, enabled=False, gestures=[ PrimTranslateChangedGesture( self._snap_manager, usd_context_name=usd_context_name, viewport_api=viewport_api ), PrimRotateChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), PrimScaleChangedGesture(usd_context_name=usd_context_name, viewport_api=viewport_api), ], tool_registry=get_toolbar_registry(), tool_button_additional_payload={"viewport_api": viewport_api, "usd_context_name": usd_context_name}, ) # Hide the old C++ imguizmo when omni.ui.scene manipulator is enabled self._prev_transform_hidden_override = self._settings.get(TRANSFORM_GIZMO_HIDDEN_OVERRIDE) self._settings.set(TRANSFORM_GIZMO_HIDDEN_OVERRIDE, True) self._set_default_settings() self._create_local_global_styles() self._op_settings_listener = OpSettingsListener() self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed) self._snap_settings_listener = SnapSettingsListener( enabled_setting_path=None, move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH, scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH, provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, ) self._snap_settings_listener_sub = self._snap_settings_listener.subscribe_listener( self._on_snap_listener_changed ) self._enabled: bool = self._manipulator.enabled self._prim_style_applied: bool = False self._set_style() def __del__(self): self.destroy() def destroy(self): super().destroy() self._op_settings_listener_sub = None self._snap_settings_listener_sub = None if self._op_settings_listener: self._op_settings_listener.destroy() self._op_settings_listener = None if self._manipulator: if self._legacy_mode: ManipulatorFactory.destroy_manipulator(self._manipulator) else: self._manipulator.destroy() self._manipulator = None if self._model and not self._model_is_external: self._model.destroy() self._model = None if self._snap_manager: self._snap_manager.destroy() self._snap_manager = None # restore imguizmo visibility self._settings.set(TRANSFORM_GIZMO_HIDDEN_OVERRIDE, self._prev_transform_hidden_override) @property def model(self) -> PrimTransformModel: return self._model @property def snap_manager(self) -> SnapProviderManager: return self._snap_manager @property def enabled(self): return self._manipulator.enabled @enabled.setter def enabled(self, value: bool): if value != self._enabled: self._enabled = value self._update_manipulator_enable() def _set_default_settings(self): self._settings.set_default_string(c.TRANSFORM_OP_SETTING, c.TRANSFORM_OP_MOVE) self._settings.set_default_string(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) self._settings.set_default_string(c.TRANSFORM_ROTATE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) def _create_local_global_styles(self): COLOR_LOCAL = 0x8A248AE3 local_style = get_default_style() local_style["Translate.Point"]["color"] = COLOR_LOCAL local_style["Rotate.Arc::screen"]["color"] = COLOR_LOCAL local_style["Scale.Point"]["color"] = COLOR_LOCAL self._styles = {c.TRANSFORM_MODE_GLOBAL: get_default_style(), c.TRANSFORM_MODE_LOCAL: local_style} self._snap_styles = copy.deepcopy(self._styles) self._snap_styles[c.TRANSFORM_MODE_GLOBAL]["Translate.Focal"]["visible"] = True self._snap_styles[c.TRANSFORM_MODE_LOCAL]["Translate.Focal"]["visible"] = True def on_selection_changed(self, stage: Usd.Stage, selection: Union[List[Sdf.Path], None], *args, **kwargs) -> bool: if selection is None: if self.model: self.model.on_selection_changed([]) return False if self.model: self.model.on_selection_changed(selection) for path in selection: prim = stage.GetPrimAtPath(path) if prim.IsA(UsdGeom.Xformable): return True return False def _update_manipulator_enable(self) -> None: if not self._manipulator: return is_enabled: bool = self._prim_style_applied and self._enabled if not self._manipulator.enabled and is_enabled: self._manipulator.enabled = True elif self._manipulator.enabled and not is_enabled: self._manipulator.enabled = False def _set_style(self) -> None: def set_manipulator_style(styles, mode: str): # An unknown style will return false here. if mode in styles: self._manipulator.style = styles[mode] return True else: return False if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: styles = ( self._snap_styles if self._snap_settings_listener.snap_enabled and self._snap_settings_listener.snap_to_surface else self._styles ) self._prim_style_applied = set_manipulator_style(styles, self._op_settings_listener.translation_mode) elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: self._prim_style_applied = set_manipulator_style(self._styles, self._op_settings_listener.rotation_mode) elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE: self._prim_style_applied = set_manipulator_style(self._styles, c.TRANSFORM_MODE_LOCAL) else: # unknown op disables. self._prim_style_applied = False self._update_manipulator_enable() def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str): if ( type == OpSettingsListener.CallbackType.OP_CHANGED or type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED or type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED ): self._set_style() def _on_snap_listener_changed(self, setting_val_name: str, value: str): if setting_val_name == "snap_enabled" or setting_val_name == "snap_to_surface": self._set_style()
10,126
Python
41.372385
118
0.644381
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/tool_models.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import carb.dictionary import carb.settings import omni.ui as ui class LocalGlobalModeModel(ui.AbstractValueModel): TRANSFORM_MODE_GLOBAL = "global" TRANSFORM_MODE_LOCAL = "local" def __init__(self, op_space_setting_path): super().__init__() self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._setting_path = op_space_setting_path self._op_space_sub = self._settings.subscribe_to_node_change_events( self._setting_path, self._on_op_space_changed ) self._op_space = self._settings.get(self._setting_path) def __del__(self): self.destroy() def destroy(self): if self._op_space_sub is not None: self._settings.unsubscribe_to_change_events(self._op_space_sub) self._op_space_sub = None def _on_op_space_changed(self, item, event_type): self._op_space = self._dict.get(item) self._value_changed() def get_value_as_bool(self): return self._op_space != self.TRANSFORM_MODE_LOCAL def set_value(self, value): self._settings.set( self._setting_path, self.TRANSFORM_MODE_LOCAL if value == False else self.TRANSFORM_MODE_GLOBAL, )
1,719
Python
32.72549
88
0.669575
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/settings_constants.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # class Constants: MANIPULATOR_PLACEMENT_SETTING = "/persistent/exts/omni.kit.manipulator.prim2.core/manipulator/placement" MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT = "Authored Pivot" MANIPULATOR_PLACEMENT_SELECTION_CENTER = "Selection Center" MANIPULATOR_PLACEMENT_BBOX_BASE = "Bounding Box Base" MANIPULATOR_PLACEMENT_BBOX_CENTER = "Bounding Box Center" MANIPULATOR_PLACEMENT_PICK_REF_PRIM = "Pick Reference Prim"
865
Python
47.111108
108
0.788439
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/utils.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import math from typing import List import carb import carb.profiler import carb.settings from pxr import Gf, Usd, UsdGeom @carb.profiler.profile def flatten(transform): """Convert array[4][4] to array[16]""" # flatten the matrix by hand # USING LIST COMPREHENSION IS VERY SLOW (e.g. return [item for sublist in transform for item in sublist]), which takes around 10ms. m0, m1, m2, m3 = transform[0], transform[1], transform[2], transform[3] return [ m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3], ] @carb.profiler.profile def get_local_transform_pivot_inv(prim: Usd.Prim, time: Usd.TimeCode = Usd.TimeCode): xform = UsdGeom.Xformable(prim) xform_ops = xform.GetOrderedXformOps() if len(xform_ops): pivot_op_inv = xform_ops[-1] if ( pivot_op_inv.GetOpType() == UsdGeom.XformOp.TypeTranslate and pivot_op_inv.IsInverseOp() and pivot_op_inv.GetName().endswith("pivot") ): return pivot_op_inv.GetOpTransform(time) return Gf.Matrix4d(1.0) def compose_transform_ops_to_matrix( translation: Gf.Vec3d, rotation: Gf.Vec3d, rotation_order: Gf.Vec3i, scale: Gf.Vec3d ): axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] rot = [] for i in range(3): axis_idx = rotation_order[i] rot.append(Gf.Rotation(axes[axis_idx], rotation[axis_idx])) rotation_mtx = Gf.Matrix4d(1.0) rotation_mtx.SetRotate(rot[0] * rot[1] * rot[2]) valid_scale = Gf.Vec3d(0.0) for i in range(3): if abs(scale[i]) == 0: valid_scale[i] = 0.001 else: valid_scale[i] = scale[i] scale_mtx = Gf.Matrix4d(1.0) scale_mtx.SetScale(valid_scale) translate_mtx = Gf.Matrix4d(1.0) translate_mtx.SetTranslate(translation) return scale_mtx * rotation_mtx * translate_mtx def repeat(t: float, length: float) -> float: return t - (math.floor(t / length) * length) def generate_compatible_euler_angles(euler: Gf.Vec3d, rotation_order: Gf.Vec3i) -> List[Gf.Vec3d]: equal_eulers = [euler] mid_order = rotation_order[1] equal = Gf.Vec3d() for i in range(3): if i == mid_order: equal[i] = 180 - euler[i] else: equal[i] = euler[i] + 180 equal_eulers.append(equal) for i in range(3): equal[i] -= 360 equal_eulers.append(equal) return equal_eulers def find_best_euler_angles(old_rot_vec: Gf.Vec3d, new_rot_vec: Gf.Vec3d, rotation_order: Gf.Vec3i) -> Gf.Vec3d: equal_eulers = generate_compatible_euler_angles(new_rot_vec, rotation_order) nearest_euler = None for euler in equal_eulers: for i in range(3): euler[i] = repeat(euler[i] - old_rot_vec[i] + 180.0, 360.0) + old_rot_vec[i] - 180.0 if nearest_euler is None: nearest_euler = euler else: distance_1 = (nearest_euler - old_rot_vec).GetLength() distance_2 = (euler - old_rot_vec).GetLength() if distance_2 < distance_1: nearest_euler = euler return nearest_euler
3,734
Python
26.873134
135
0.61248
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/toolbar_registry.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.kit.manipulator.transform.toolbar_registry import ToolbarRegistry _toolbar_registry = ToolbarRegistry() def get_toolbar_registry() -> ToolbarRegistry: return _toolbar_registry
622
Python
35.647057
76
0.803859
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/reference_prim_marker.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 __future__ import annotations import asyncio import colorsys import weakref from collections import defaultdict from typing import DefaultDict, Dict, Set, Union from weakref import ProxyType import concurrent.futures import carb import carb.dictionary import carb.events import carb.profiler import carb.settings import omni.timeline import omni.usd from omni.kit.async_engine import run_coroutine from omni.kit.manipulator.transform.style import COLOR_X, COLOR_Y, COLOR_Z, abgr_to_color from omni.kit.manipulator.transform.settings_constants import Constants as TrCon from omni.ui import color as cl from omni.ui import scene as sc from pxr import Sdf, Tf, Usd, UsdGeom from .model import PrimTransformModel from omni.kit.viewport.manipulator.transform import Viewport1WindowState from .settings_constants import Constants from .utils import flatten, get_local_transform_pivot_inv LARGE_SELECTION_CAP = 20 class PreventViewportOthers(sc.GestureManager): def can_be_prevented(self, gesture): return True def should_prevent(self, gesture, preventer): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: if issubclass(type(preventer), ClickMarkerGesture): if issubclass(type(gesture), ClickMarkerGesture): return gesture.gesture_payload.ray_distance > preventer.gesture_payload.ray_distance elif isinstance(gesture, ClickMarkerGesture): return False else: return True else: return True return super().should_prevent(gesture, preventer) class ClickMarkerGesture(sc.DragGesture): def __init__( self, prim_path: Sdf.Path, marker: ProxyType[ReferencePrimMarker], ): super().__init__(manager=PreventViewportOthers()) self._prim_path = prim_path self._marker = marker self._vp1_window_state = None def on_began(self): self._viewport_on_began() def on_canceled(self): self._viewport_on_ended() def on_ended(self): self._viewport_on_ended() self._marker.on_pivot_marker_picked(self._prim_path) def _viewport_on_began(self): self._viewport_on_ended() if self._marker.legacy: self._vp1_window_state = Viewport1WindowState() def _viewport_on_ended(self): if self._vp1_window_state: self._vp1_window_state.destroy() self._vp1_window_state = None class MarkerHoverGesture(sc.HoverGesture): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.items = [] self._began_count = 0 self._original_colors = [] self._original_ends = [] def on_began(self): self._began_count += 1 if self._began_count == 1: self._original_colors = [None] * len(self.items) self._original_ends = [None] * len(self.items) for i, item in enumerate(self.items): self._original_colors[i] = item.color item.color = self._make_brighter(item.color) if isinstance(item, sc.Line): self._original_ends[i] = item.end end = [dim * 1.2 for dim in item.end] item.end = end if isinstance(item, sc.Arc): ... # TODO change color to white, blocked by OM-56044 def on_ended(self): self._began_count -= 1 if self._began_count <= 0: self._began_count = 0 for i, item in enumerate(self.items): item.color = self._original_colors[i] if isinstance(item, sc.Line): item.end = self._original_ends[i] if isinstance(item, sc.Arc): ... # TODO change color back, blocked by OM-56044 def _make_brighter(self, color): hsv = colorsys.rgb_to_hsv(color[0], color[1], color[2]) rgb = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2] * 1.2) return cl(rgb[0], rgb[1], rgb[2], color[3]) class ReferencePrimMarker(sc.Manipulator): def __init__( self, usd_context_name: str = "", manipulator_model: ProxyType[PrimTransformModel] = None, legacy: bool = False ): super().__init__() self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._usd_context_name = usd_context_name self._usd_context = omni.usd.get_context(self._usd_context_name) self._manipulator_model = manipulator_model self._legacy = legacy self._selection = self._usd_context.get_selection() self._timeline = omni.timeline.get_timeline_interface() self._current_time = self._timeline.get_current_time() # dict from prefixes -> dict of affected markers. self._markers: DefaultDict[Dict] = defaultdict(dict) self._stage_listener = None self._pending_changed_paths: Set[Sdf.Path] = set() self._process_pending_change_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None # order=1 to ensure the event handler is called after prim manipulator self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="ReferencePrimMarker stage event", order=1 ) self._placement_sub = self._settings.subscribe_to_node_change_events( Constants.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_changed ) self._placement = self._settings.get(Constants.MANIPULATOR_PLACEMENT_SETTING) self._op_sub = self._settings.subscribe_to_node_change_events(TrCon.TRANSFORM_OP_SETTING, self._on_op_changed) self._selected_op = self._settings.get(TrCon.TRANSFORM_OP_SETTING) def destroy(self): self._stage_event_sub = None if self._placement_sub: self._settings.unsubscribe_to_change_events(self._placement_sub) self._placement_sub = None if self._op_sub: self._settings.unsubscribe_to_change_events(self._op_sub) self._op_sub = None if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None if self._process_pending_change_task_or_future and not self._process_pending_change_task_or_future.done(): self._process_pending_change_task_or_future.cancel() self._process_pending_change_task_or_future = None self._timeline_sub = None @property def usd_context_name(self) -> str: return self._usd_context_name @usd_context_name.setter def usd_context_name(self, value: str): if value != self._usd_context_name: new_usd_context = omni.usd.get_context(value) if not new_usd_context: carb.log_error(f"Invalid usd context name {value}") return if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None self._usd_context_name = value self._usd_context = new_usd_context # order=1 to ensure the event handler is called after prim manipulator self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="ReferencePrimMarker stage event", order=1 ) self.invalidate() @property def manipulator_model(self) -> ProxyType[PrimTransformModel]: return self._manipulator_model @manipulator_model.setter def manipulator_model(self, value): if value != self._manipulator_model: self._manipulator_model = value self.invalidate() @property def legacy(self) -> bool: return self._legacy @legacy.setter def legacy(self, value): self._legacy = value def on_pivot_marker_picked(self, path: Sdf.Path): if self._manipulator_model.set_pivot_prim_path(path): # Hide marker on the new pivot prim and show marker on old pivot prim old_pivot_marker = self._markers.get(self._pivot_prim_path, {}).get(self._pivot_prim_path, None) if old_pivot_marker: old_pivot_marker.visible = True self._pivot_prim_path = self._manipulator_model.get_pivot_prim_path() new_pivot_marker = self._markers.get(self._pivot_prim_path, {}).get(self._pivot_prim_path, None) if new_pivot_marker: new_pivot_marker.visible = False def on_build(self): if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None self._timeline_sub = None self._markers.clear() if self._placement != Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: return # don't build marker on "select" mode if self._selected_op == TrCon.TRANSFORM_OP_SELECT: return selected_xformable_paths = self._manipulator_model.xformable_prim_paths stage = self._usd_context.get_stage() self._current_time = self._timeline.get_current_time() selection_count = len(selected_xformable_paths) # skip if there's only one xformable if selection_count <= 1: return if selection_count > LARGE_SELECTION_CAP: carb.log_warn( f"{selection_count} is greater than the maximum selection cap {LARGE_SELECTION_CAP}, " f"{Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM} mode will be disabled and fallback to " f"{Constants.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT} due to performance concern." ) return timecode = self._get_current_time_code() self._pivot_prim_path = self._manipulator_model.get_pivot_prim_path() xform_cache = UsdGeom.XformCache(timecode) for path in selected_xformable_paths: prim = stage.GetPrimAtPath(path) pivot_inv = get_local_transform_pivot_inv(prim, timecode) transform = pivot_inv.GetInverse() * xform_cache.GetLocalToWorldTransform(prim) transform.Orthonormalize() # in case of a none uniform scale marker_transform = sc.Transform(transform=flatten(transform), visible=self._pivot_prim_path != path) with marker_transform: with sc.Transform(scale_to=sc.Space.SCREEN): gesture = ClickMarkerGesture(path, marker=weakref.proxy(self)) hover_gesture = MarkerHoverGesture() x_line = sc.Line( (0, 0, 0), (50, 0, 0), color=abgr_to_color(COLOR_X), thickness=2, intersection_thickness=8, gestures=[gesture, hover_gesture], ) y_line = sc.Line( (0, 0, 0), (0, 50, 0), color=abgr_to_color(COLOR_Y), thickness=2, intersection_thickness=8, gestures=[gesture, hover_gesture], ) z_line = sc.Line( (0, 0, 0), (0, 0, 50), color=abgr_to_color(COLOR_Z), thickness=2, intersection_thickness=8, gestures=[gesture, hover_gesture], ) with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): point = sc.Arc( radius=6, wireframe=False, tesselation=8, color=cl.white, # TODO default color grey, blocked by OM-56044 ) hover_gesture.items = [x_line, y_line, z_line, point] prefixes = path.GetPrefixes() for prefix in prefixes: self._markers[prefix][path] = marker_transform if self._markers: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, stage) self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop( self._on_timeline_event ) def _on_stage_event(self, event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): if self._placement == Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: self.invalidate() def _on_placement_changed(self, item, event_type): placement = self._dict.get(item) if placement != self._placement: self._placement = placement self.invalidate() def _on_op_changed(self, item, event_type): selected_op = self._dict.get(item) if selected_op != self._selected_op: if selected_op == TrCon.TRANSFORM_OP_SELECT or self._selected_op == TrCon.TRANSFORM_OP_SELECT: self.invalidate() self._selected_op = selected_op def _on_timeline_event(self, e: carb.events.IEvent): if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED): current_time = e.payload["currentTime"] if current_time != self._current_time: self._current_time = current_time if self._placement != Constants.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: # TODO only invalidate transform if this prim or ancestors transforms are time varying? self.invalidate() @carb.profiler.profile async def _process_pending_change(self): processed_transforms = set() timecode = self._get_current_time_code() xform_cache = UsdGeom.XformCache(timecode) stage = self._usd_context.get_stage() for path in self._pending_changed_paths: prim_path = path.GetPrimPath() affected_transforms = self._markers.get(prim_path, {}) if affected_transforms: if not UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name): continue for path, transform in affected_transforms.items(): if transform in processed_transforms: continue prim = stage.GetPrimAtPath(path) if not prim: continue pivot_inv = get_local_transform_pivot_inv(prim, timecode) xform = pivot_inv.GetInverse() * xform_cache.GetLocalToWorldTransform(prim) xform.Orthonormalize() # in case of a none uniform scale transform_value = flatten(xform) transform.transform = transform_value processed_transforms.add(transform) self._pending_changed_paths.clear() @carb.profiler.profile def _on_objects_changed(self, notice, sender): self._pending_changed_paths.update(notice.GetChangedInfoOnlyPaths()) if self._process_pending_change_task_or_future is None or self._process_pending_change_task_or_future.done(): self._process_pending_change_task_or_future = run_coroutine(self._process_pending_change()) def _get_current_time_code(self): return Usd.TimeCode( omni.usd.get_frame_time_code(self._current_time, self._usd_context.get_stage().GetTimeCodesPerSecond()) )
16,316
Python
38.70073
119
0.59647
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/model.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from __future__ import annotations import asyncio import math import traceback from enum import Enum, Flag, IntEnum, auto from typing import Dict, List, Sequence, Set, Tuple, Union import concurrent.futures import carb import carb.dictionary import carb.events import carb.profiler import carb.settings import omni.kit.app from omni.kit.async_engine import run_coroutine import omni.kit.commands import omni.kit.undo import omni.timeline from omni.kit.manipulator.tool.snap import SnapProviderManager from omni.kit.manipulator.tool.snap import settings_constants as snap_c from omni.kit.manipulator.transform import AbstractTransformManipulatorModel, Operation from omni.kit.viewport.manipulator.transform import ( ViewportTransformModel, DataAccessor, DataAccessorRegistry, ManipulationMode, ) from omni.kit.viewport.manipulator.transform.gestures import ( ViewportTranslateChangedGesture, ViewportRotateChangedGesture, ViewportScaleChangedGesture, ) from omni.kit.manipulator.transform.settings_constants import c from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener from omni.ui import scene as sc from pxr import Gf, Sdf, Tf, Usd, UsdGeom, UsdUtils from .settings_constants import Constants as prim_c from .utils import * # Settings needed for zero-gravity TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED = "/app/transform/gizmoCustomManipulatorEnabled" TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS = "/app/transform/gizmoCustomManipulatorPrims" TRANSFORM_GIZMO_IS_USING = "/app/transform/gizmoIsUsing" TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ = "/app/transform/gizmoTranslateDeltaXYZ" TRANSFORM_GIZMO_PIVOT_WORLD_POSITION = "/app/transform/tempPivotWorldPosition" TRANSFORM_GIZMO_ROTATE_DELTA_XYZW = "/app/transform/gizmoRotateDeltaXYZW" TRANSFORM_GIZMO_SCALE_DELTA_XYZ = "/app/transform/gizmoScaleDeltaXYZ" TRANSLATE_DELAY_FRAME_SETTING = "/exts/omni.kit.manipulator.prim2.core/visual/delayFrame" class OpFlag(Flag): TRANSLATE = auto() ROTATE = auto() SCALE = auto() class Placement(Enum): LAST_PRIM_PIVOT = auto() SELECTION_CENTER = auto() BBOX_CENTER = auto() REF_PRIM = auto() BBOX_BASE = auto() class PrimTranslateChangedGesture(ViewportTranslateChangedGesture): def _get_model(self, payload_type) -> PrimTransformModel: if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return None return self.sender.model class PrimRotateChangedGesture(ViewportRotateChangedGesture): ... class PrimScaleChangedGesture(ViewportScaleChangedGesture): ... class PrimTransformModel(ViewportTransformModel): def __init__(self, usd_context_name: str = "", viewport_api=None): ViewportTransformModel.__init__(self, usd_context_name=usd_context_name, viewport_api=viewport_api) self._dataAccessor = None self._transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # visual transform of manipulator self._no_scale_transform_manipulator = Gf.Matrix4d(1.0) # transform of manipulator without scale self._scale_manipulator = Gf.Vec3d(1.0) # scale of manipulator self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._timeline = omni.timeline.get_timeline_interface() self._app = omni.kit.app.get_app() self._usd_context_name = usd_context_name self._usd_context = omni.usd.get_context(usd_context_name) self.dataAccessorRegistry = PrimDataAccessorRegistry(dataType = "USD") self._dataAccessor = self.dataAccessorRegistry.getDataAccessor(model = self) self._enabled_hosting_widget_count: int = 0 self._stage_listener = None self._xformable_prim_paths: List[Sdf.Path] = [] self._xformable_prim_paths_sorted: List[Sdf.Path] = [] self._xformable_prim_paths_set: Set[Sdf.Path] = set() self._xformable_prim_paths_prefix_set: Set[Sdf.Path] = set() self._consolidated_xformable_prim_paths: List[Sdf.Path] = [] self._pending_changed_paths_for_xform_data: Set[Sdf.Path] = set() self._pivot_prim: Usd.Prim = None self._update_prim_xform_from_prim_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None self._current_editing_op: Operation = None self._ignore_xform_data_change = False self._timeline_sub = None self._pending_changed_paths: Dict[Sdf.Path, bool] = {} self._mode = ManipulationMode.PIVOT self._viewport_fps: float = 0.0 # needed this as heuristic for delaying the visual update of manipulator to match rendering self._viewport_api = viewport_api self._delay_dirty_tasks_or_futures: Dict[int, Union[asyncio.Task, concurrent.futures.Future]] = {} self._no_scale_transform_manipulator_item = sc.AbstractManipulatorItem() self._items["no_scale_transform_manipulator"] = self._no_scale_transform_manipulator_item self._scale_manipulator_item = sc.AbstractManipulatorItem() self._items["scale_manipulator"] = self._scale_manipulator_item self._transform_manipulator_item = sc.AbstractManipulatorItem() self._items["transform_manipulator"] = self._transform_manipulator_item self._manipulator_mode_item = sc.AbstractManipulatorItem() self._items["manipulator_mode"] = self._manipulator_mode_item self._viewport_fps_item = sc.AbstractManipulatorItem() self._items["viewport_fps"] = self._viewport_fps_item self._set_default_settings() # subscribe to snap events self._snap_settings_listener = SnapSettingsListener( enabled_setting_path=None, move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH, scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH, provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, ) # subscribe to operation/mode events self._op_settings_listener = OpSettingsListener() self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed) self._placement_sub = self._settings.subscribe_to_node_change_events( prim_c.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_setting_changed ) self._placement = Placement.LAST_PRIM_PIVOT placement = self._settings.get(prim_c.MANIPULATOR_PLACEMENT_SETTING) self._update_placement(placement) # cache unique setting path for selection pivot position # vp1 default self._selection_pivot_position_path = TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/Viewport" # vp2 if self._viewport_api: self._selection_pivot_position_path = ( TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/" + self._viewport_api.id.split("/")[0] ) # update setting with pivot placement position on init self._update_temp_pivot_world_position() def subscribe_to_value_and_get_current(setting_val_name: str, setting_path: str): sub = self._settings.subscribe_to_node_change_events( setting_path, lambda item, type: setattr(self, setting_val_name, self._dict.get(item)) ) setattr(self, setting_val_name, self._settings.get(setting_path)) return sub # subscribe to zero-gravity settings self._custom_manipulator_enabled_sub = subscribe_to_value_and_get_current( "_custom_manipulator_enabled", TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED ) self._warning_notification = None self._selected_instance_proxy_paths = set() # subscribe to USD related events self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="PrimTransformModel stage event" ) if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_opened() def _on_timeline_event(self, e: carb.events.IEvent): if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED): current_time = e.payload["currentTime"] if current_time != self._current_time: self._current_time = current_time self._dataAccessor.xform_set_time() # TODO only update transform if this prim or ancestors transforms are time varying? if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _on_stage_event(self, event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.OPENED): self._on_stage_opened() elif event.type == int(omni.usd.StageEventType.CLOSING): self._on_stage_closing() def _on_stage_opened(self): self._dataAccessor._stage = self._usd_context.get_stage() self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop( self._on_timeline_event ) self._current_time = self._timeline.get_current_time() self._dataAccessor.update_xform_cache() #commands def _on_ended_transform( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], old_translations: List[float], old_rotation_eulers: List[float], old_rotation_orders: List[int], old_scales: List[float], ): self._alert_if_selection_has_instance_proxies() self._dataAccessor._on_ended_transform( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales, old_translations, old_rotation_eulers, old_rotation_orders, old_scales, ) def _do_transform_selected_prims( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): """Function ran by _transform_selected_prims(). Can be overridden to change the behavior Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() self._dataAccessor._do_transform_selected_prims( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales ) def _do_transform_all_selected_prims_to_manipulator_pivot( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): """Function ran by _transform_all_selected_prims_to_manipulator_pivot(). Can be overridden to change the behavior. Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() self._dataAccessor._do_transform_all_selected_prims_to_manipulator_pivot( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales ) def __del__(self): self.destroy() def destroy(self): if self._warning_notification: self._warning_notification.dismiss() self._warning_notification= None self._op_settings_listener_sub = None if self._op_settings_listener: self._op_settings_listener.destroy() self._op_settings_listener = None self._stage_event_sub = None if self._stage_listener: self._stage_listener = self._dataAccessor.remove_update_callback(self._stage_listener) # if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_closing() self._timeline_sub = None if self._snap_settings_listener: self._snap_settings_listener.destroy() self._snap_settings_listener = None if self._custom_manipulator_enabled_sub: self._settings.unsubscribe_to_change_events(self._custom_manipulator_enabled_sub) self._custom_manipulator_enabled_sub = None if self._placement_sub: self._settings.unsubscribe_to_change_events(self._placement_sub) self._placement_sub = None for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() def set_pivot_prim_path(self, path: Sdf.Path) -> bool: if path not in self._xformable_prim_paths_set: carb.log_warn(f"Cannot set pivot prim path to {path}") return False if not self._pivot_prim or self._pivot_prim.GetPath() != path: self._pivot_prim = self._dataAccessor.get_prim_at_path(path) else: return False if self._update_transform_from_prims(): self._item_changed(self._transform_item) return True def get_pivot_prim_path(self) -> Sdf.Path: if self._pivot_prim: return self._pivot_prim.GetPath() return None def _update_xform_data_from_dirty_paths(self): for p in self._pending_changed_paths_for_xform_data: prim_path = p.GetPrimPath() if prim_path in self.all_xformable_prim_data_curr and self._path_may_affect_transform(p): prim = self._dataAccessor.get_prim_at_path(prim_path) xform_tuple = self._dataAccessor.get_local_transform_SRT(prim, self._dataAccessor.get_current_time_code(self._current_time)) pivot = get_local_transform_pivot_inv(prim, self._dataAccessor.get_current_time_code(self._current_time)).GetInverse() self.all_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,) if prim_path in self._consolidated_xformable_prim_paths: self.consolidated_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,) self._pending_changed_paths_for_xform_data.clear() def on_began(self, payload): item = payload.changing_item self._current_editing_op = item.operation # All selected xformable prims' transforms. Store this for when `Keep Spacing` option is off during snapping, # because it can modify parent's and child're transform differently. self._all_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d, Gf.Vec3d]] = {} # consolidated xformable prims' transforms. If parent is in the dict, child will be excluded. self._consolidated_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d]] = {} for path in self._xformable_prim_paths: prim = self._dataAccessor.get_prim_at_path(path) xform_tuple = self._dataAccessor.get_local_transform_SRT(prim, self._dataAccessor.get_current_time_code(self._current_time)) pivot = get_local_transform_pivot_inv(prim, self._dataAccessor.get_current_time_code(self._current_time)).GetInverse() self._all_xformable_prim_data_prev[path] = xform_tuple + (pivot,) if path in self._consolidated_xformable_prim_paths: self._consolidated_xformable_prim_data_prev[path] = xform_tuple + (pivot,) self.all_xformable_prim_data_curr = self._all_xformable_prim_data_prev.copy() self.consolidated_xformable_prim_data_curr = self._consolidated_xformable_prim_data_prev.copy() self._pending_changed_paths_for_xform_data.clear() if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, True) def on_changed(self, payload): # Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator, # prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest. self._update_xform_data_from_dirty_paths() def on_ended(self, payload): # Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator, # prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest. self._update_xform_data_from_dirty_paths() carb.profiler.begin(1, "PrimTransformChangedGestureBase.TransformPrimSRT.all") paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] old_translations = [] old_rotation_eulers = [] old_rotation_orders = [] old_scales = [] for path, (s, r, ro, t, pivot) in self.all_xformable_prim_data_curr.items(): # Data didn't change if self._all_xformable_prim_data_prev[path] == self.all_xformable_prim_data_curr[path]: # carb.log_info(f"Skip {path}") continue (old_s, old_r, old_ro, old_t, old_pivot) = self._all_xformable_prim_data_prev[path] paths.append(path.pathString) new_translations += [t[0], t[1], t[2]] new_rotation_eulers += [r[0], r[1], r[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [s[0], s[1], s[2]] old_translations += [old_t[0], old_t[1], old_t[2]] old_rotation_eulers += [old_r[0], old_r[1], old_r[2]] old_rotation_orders += [old_ro[0], old_ro[1], old_ro[2]] old_scales += [old_s[0], old_s[1], old_s[2]] self._ignore_xform_data_change = True self._on_ended_transform( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales, old_translations, old_rotation_eulers, old_rotation_orders, old_scales, ) self._ignore_xform_data_change = False carb.profiler.end(1) if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, False) # if the manipulator was locked to orientation or translation, # refresh it on_ended so the transform is up to date mode = self._get_transform_mode_for_current_op() if self._should_keep_manipulator_orientation_unchanged( mode ) or self._should_keep_manipulator_translation_unchanged(mode): # set editing op to None AFTER _should_keep_manipulator_*_unchanged but # BEFORE self._update_transform_from_prims self._current_editing_op = None if self._update_transform_from_prims(): self._item_changed(self._transform_item) self._current_editing_op = None def on_canceled(self, payload): if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, False) self._current_editing_op = None def widget_enabled(self): self._enabled_hosting_widget_count += 1 # just changed from no active widget to 1 active widget if self._enabled_hosting_widget_count == 1: # listener only needs to be activated if manipulator is visible if self._consolidated_xformable_prim_paths: assert self._stage_listener is None self._stage_listener = self._dataAccessor.setup_update_callback(self._on_objects_changed) def _clear_temp_pivot_position_setting(self): if self._settings.get(self._selection_pivot_position_path): self._settings.destroy_item(self._selection_pivot_position_path) def widget_disabled(self): self._enabled_hosting_widget_count -= 1 self._clear_temp_pivot_position_setting() assert self._enabled_hosting_widget_count >= 0 if self._enabled_hosting_widget_count < 0: carb.log_error(f"manipulator enabled widget tracker out of sync: {self._enabled_hosting_widget_count}") self._enabled_hosting_widget_count = 0 # If no hosting manipulator is active, revoke the listener since there's no need to sync Transform if self._enabled_hosting_widget_count == 0: if self._stage_listener: self._stage_listener = self._dataAccessor.remove_update_callback(self._stage_listener) for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() def set_floats(self, item: sc.AbstractManipulatorItem, value: Sequence[float]): if item == self._viewport_fps_item: self._viewport_fps = value[0] return flag = None if issubclass(type(item), AbstractTransformManipulatorModel.OperationItem): if ( item.operation == Operation.TRANSLATE_DELTA or item.operation == Operation.ROTATE_DELTA or item.operation == Operation.SCALE_DELTA ): return if item.operation == Operation.TRANSLATE: flag = OpFlag.TRANSLATE elif item.operation == Operation.ROTATE: flag = OpFlag.ROTATE elif item.operation == Operation.SCALE: flag = OpFlag.SCALE transform = Gf.Matrix4d(*value) elif item == self._transform_manipulator_item: flag = OpFlag.TRANSLATE | OpFlag.ROTATE | OpFlag.SCALE transform = Gf.Matrix4d(*value) elif item == self._no_scale_transform_manipulator_item: flag = OpFlag.TRANSLATE | OpFlag.ROTATE old_manipulator_scale_mtx = Gf.Matrix4d(1.0) old_manipulator_scale_mtx.SetScale(self._scale_manipulator) transform = old_manipulator_scale_mtx * Gf.Matrix4d(*value) if flag is not None: if self._mode == ManipulationMode.PIVOT: self._transform_selected_prims( transform, self._no_scale_transform_manipulator, self._scale_manipulator, flag ) elif self._mode == ManipulationMode.UNIFORM: self._transform_all_selected_prims_to_manipulator_pivot(transform, flag) else: carb.log_warn(f"Unsupported item {item}") def set_ints(self, item: sc.AbstractManipulatorItem, value: Sequence[int]): if item == self._manipulator_mode_item: try: self._mode = ManipulationMode(value[0]) except: carb.log_error(traceback.format_exc()) else: carb.log_warn(f"unsupported item {item}") return None def get_as_floats(self, item: sc.AbstractManipulatorItem): if item == self._transform_item: return self._transform elif item == self._no_scale_transform_manipulator_item: return flatten(self._no_scale_transform_manipulator) elif item == self._scale_manipulator_item: return [self._scale_manipulator[0], self._scale_manipulator[1], self._scale_manipulator[2]] elif item == self._transform_manipulator_item: scale_mtx = Gf.Matrix4d(1) scale_mtx.SetScale(self._scale_manipulator) return flatten(scale_mtx * self._no_scale_transform_manipulator) else: carb.log_warn(f"unsupported item {item}") return None def get_as_ints(self, item: sc.AbstractManipulatorItem): if item == self._manipulator_mode_item: return [int(self._mode)] else: carb.log_warn(f"unsupported item {item}") return None def get_operation(self) -> Operation: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: return Operation.TRANSLATE elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: return Operation.ROTATE elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE: return Operation.SCALE return Operation.NONE def get_snap(self, item: AbstractTransformManipulatorModel.OperationItem): if not self._snap_settings_listener.snap_enabled: return None if item.operation == Operation.TRANSLATE: if self._snap_settings_listener.snap_provider: return None return ( self._snap_settings_listener.snap_move_x, self._snap_settings_listener.snap_move_y, self._snap_settings_listener.snap_move_z, ) elif item.operation == Operation.ROTATE: return self._snap_settings_listener.snap_rotate elif item.operation == Operation.SCALE: return self._snap_settings_listener.snap_scale return None @carb.profiler.profile def _transform_selected_prims( self, new_manipulator_transform: Gf.Matrix4d, old_manipulator_transform_no_scale: Gf.Matrix4d, old_manipulator_scale: Gf.Vec3d, dirty_ops: OpFlag, ): carb.profiler.begin(1, "omni.kit.manipulator.prim2.core.model._transform_selected_prims.prepare_data") paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] self._dataAccessor.clear_xform_cache() # any op may trigger a translation change if multi-manipulating should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(self._xformable_prim_paths) > 1 or self._placement != Placement.LAST_PRIM_PIVOT should_update_rotate = dirty_ops & OpFlag.ROTATE should_update_scale = dirty_ops & OpFlag.SCALE old_manipulator_scale_mtx = Gf.Matrix4d(1.0) old_manipulator_scale_mtx.SetScale(old_manipulator_scale) old_manipulator_transform_inv = (old_manipulator_scale_mtx * old_manipulator_transform_no_scale).GetInverse() for path in self._consolidated_xformable_prim_paths: if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString): continue selected_prim = self._dataAccessor.get_prim_at_path(path) # We check whether path is in consolidated_xformable_prim_data_curr because it may have not made it the dictionary if an error occured if not selected_prim or path not in self.consolidated_xformable_prim_data_curr: continue (s, r, ro, t, selected_pivot) = self.consolidated_xformable_prim_data_curr[path] selected_pivot_inv = selected_pivot.GetInverse() selected_local_to_world_mtx = self._dataAccessor.get_local_to_world_transform(selected_prim) selected_parent_to_world_mtx = self._dataAccessor.get_parent_to_world_transform(selected_prim) # Transform the prim from world space to pivot's space # Then apply the new pivotPrim-to-world-space transform matrix selected_local_to_world_pivot_mtx = ( selected_pivot * selected_local_to_world_mtx * old_manipulator_transform_inv * new_manipulator_transform ) world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse() selected_local_mtx_new = selected_local_to_world_pivot_mtx * world_to_parent_mtx * selected_pivot_inv if should_update_translate: translation = selected_local_mtx_new.ExtractTranslation() if should_update_rotate: # Construct the new rotation from old scale and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_s_mtx = Gf.Matrix4d(1.0) old_s_mtx.SetScale(Gf.Vec3d(s)) old_t_mtx = Gf.Matrix4d(1.0) old_t_mtx.SetTranslate(Gf.Vec3d(t)) rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro) if should_update_scale: # Construct the new scale from old rotation and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1)) new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse() scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2]) translation = translation if should_update_translate else t rotation = rotation if should_update_rotate else r scale = scale if should_update_scale else s paths.append(path.pathString) new_translations += [translation[0], translation[1], translation[2]] new_rotation_eulers += [rotation[0], rotation[1], rotation[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [scale[0], scale[1], scale[2]] xform_tuple = (scale, rotation, ro, translation, selected_pivot) self.consolidated_xformable_prim_data_curr[path] = xform_tuple self.all_xformable_prim_data_curr[path] = xform_tuple carb.profiler.end(1) self._ignore_xform_data_change = True self._do_transform_selected_prims(paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales) self._ignore_xform_data_change = False @carb.profiler.profile def _transform_all_selected_prims_to_manipulator_pivot( self, new_manipulator_transform: Gf.Matrix4d, dirty_ops: OpFlag, ): paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] old_translations = [] old_rotation_eulers = [] old_rotation_orders = [] old_scales = [] self._dataAccessor.clear_xform_cache() # any op may trigger a translation change if multi-manipulating should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(self._xformable_prim_paths) > 1 should_update_rotate = dirty_ops & OpFlag.ROTATE should_update_scale = dirty_ops & OpFlag.SCALE for path in self._xformable_prim_paths_sorted: if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString): continue selected_prim = self._dataAccessor.get_prim_at_path(path) # We check whether path is in all_xformable_prim_data_curr because it may have not made it the dictionary if an error occured if not selected_prim or path not in self.all_xformable_prim_data_curr: continue (s, r, ro, t, selected_pivot) = self.all_xformable_prim_data_curr[path] selected_parent_to_world_mtx = self._dataAccessor.get_parent_to_world_transform(selected_prim) world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse() selected_local_mtx_new = new_manipulator_transform * world_to_parent_mtx * selected_pivot.GetInverse() if should_update_translate: translation = selected_local_mtx_new.ExtractTranslation() if should_update_rotate: # Construct the new rotation from old scale and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_s_mtx = Gf.Matrix4d(1.0) old_s_mtx.SetScale(Gf.Vec3d(s)) old_t_mtx = Gf.Matrix4d(1.0) old_t_mtx.SetTranslate(Gf.Vec3d(t)) rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro) if should_update_scale: # Construct the new scale from old rotation and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1)) new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse() scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2]) # any op may trigger a translation change if multi-manipulating translation = translation if should_update_translate else t rotation = rotation if should_update_rotate else r scale = scale if should_update_scale else s paths.append(path.pathString) new_translations += [translation[0], translation[1], translation[2]] new_rotation_eulers += [rotation[0], rotation[1], rotation[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [scale[0], scale[1], scale[2]] old_translations += [t[0], t[1], t[2]] old_rotation_eulers += [r[0], r[1], r[2]] old_rotation_orders += [ro[0], ro[1], ro[2]] old_scales += [s[0], s[1], s[2]] xform_tuple = (scale, rotation, ro, translation, selected_pivot) self.all_xformable_prim_data_curr[path] = xform_tuple if path in self.consolidated_xformable_prim_data_curr: self.consolidated_xformable_prim_data_curr[path] = xform_tuple self._ignore_xform_data_change = True self._do_transform_all_selected_prims_to_manipulator_pivot( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales ) self._ignore_xform_data_change = False def _alert_if_selection_has_instance_proxies(self): if self._selected_instance_proxy_paths and (not self._warning_notification or self._warning_notification.dismissed): try: import omni.kit.notification_manager as nm self._warning_notification = nm.post_notification( "Children of an instanced prim cannot be modified, uncheck Instanceable on the instanced prim to modify child prims.", status=nm.NotificationStatus.WARNING ) except ImportError: pass def _on_stage_closing(self): self._dataAccessor.free_stage() self._dataAccessor.free_xform_cache() self._xformable_prim_paths.clear() self._xformable_prim_paths_sorted.clear() self._xformable_prim_paths_set.clear() self._xformable_prim_paths_prefix_set.clear() self._consolidated_xformable_prim_paths.clear() self._pivot_prim = None self._timeline_sub = None if self._stage_listener: self._stage_listener = self._dataAccessor.remove_update_callback(self._stage_listener) self._pending_changed_paths.clear() if self._update_prim_xform_from_prim_task_or_future is not None: self._update_prim_xform_from_prim_task_or_future.cancel() self._update_prim_xform_from_prim_task_or_future = None def on_selection_changed(self, selection: List[Sdf.Path]): if self._update_prim_xform_from_prim_task_or_future is not None: self._update_prim_xform_from_prim_task_or_future.cancel() self._update_prim_xform_from_prim_task_or_future = None self._selected_instance_proxy_paths.clear() self._xformable_prim_paths.clear() self._xformable_prim_paths_set.clear() self._xformable_prim_paths_prefix_set.clear() self._consolidated_xformable_prim_paths.clear() self._pivot_prim = None for sdf_path in selection: prim = self._dataAccessor.get_prim_at_path(sdf_path) if prim and prim.IsA(UsdGeom.Xformable) and prim.IsActive(): self._xformable_prim_paths.append(sdf_path) if self._xformable_prim_paths: # Make a sorted list so parents always appears before child self._xformable_prim_paths_sorted = self._xformable_prim_paths.copy() self._xformable_prim_paths_sorted.sort() # Find the most recently selected valid xformable prim as the pivot prim where the transform gizmo is located at. self._pivot_prim = self._dataAccessor.get_prim_at_path(self._xformable_prim_paths[-1]) # Get least common prims ancestors. # We do this so that if one selected prim is a descendant of other selected prim, the descendant prim won't be # transformed twice. self._consolidated_xformable_prim_paths = Sdf.Path.RemoveDescendentPaths(self._xformable_prim_paths) # Filter all instance proxy paths. for path in self._consolidated_xformable_prim_paths: prim = self._dataAccessor.get_prim_at_path(path) if prim.IsInstanceProxy(): self._selected_instance_proxy_paths.add(sdf_path) self._xformable_prim_paths_set.update(self._xformable_prim_paths) for path in self._xformable_prim_paths_set: self._xformable_prim_paths_prefix_set.update(path.GetPrefixes()) if self._update_transform_from_prims(): self._item_changed(self._transform_item) # Happens when host widget is already enabled and first selection in a new stage if self._enabled_hosting_widget_count > 0 and self._stage_listener is None: self._stage_listener = self._dataAccessor.setup_update_callback(self._on_objects_changed) def _should_keep_manipulator_orientation_unchanged(self, mode: str) -> bool: # Exclude snap_to_face. During snap_to_face operation, it may modify the orientation of object to confrom to surface # normal and the `new_manipulator_transform` param for `_transform_selected_prims` is set to the final transform # of the manipulated prim. However, if we use old rotation in the condition below, _no_scale_transform_manipulator # will not confrom to the new orientation, and _transform_selected_prims would double rotate the prims because it # sees the rotation diff between the old prim orientation (captured at on_began) vs new normal orient, instead of # current prim orientation vs new normal orientation. # Plus, it is nice to see the normal of the object changing while snapping. snap_provider_enabled = self.snap_settings_listener.snap_enabled and self.snap_settings_listener.snap_provider # When the manipulator is being manipulated as local translate or scale, we do not want to change the rotation of # the manipulator even if it's rotated, otherwise the direction of moving or scaling will change and can be very hard to control. # It can happen when you move a prim that has a constraint on it (e.g. lookAt) # In this case keep the rotation the same as on_began return ( mode == c.TRANSFORM_MODE_LOCAL and (self._current_editing_op == Operation.TRANSLATE or self._current_editing_op == Operation.SCALE) and not snap_provider_enabled ) def _should_keep_manipulator_translation_unchanged(self, mode: str) -> bool: # When the pivot placement is BBOX_CENTER and multiple prims being rotated, the bbox center may shifts, and the # rotation center will shift with them. This causes weird user experience. So we pin the rotation center until # mouse is released. return ( self._current_editing_op == Operation.ROTATE and (self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE) ) def _get_transform_mode_for_current_op(self) -> str: mode = c.TRANSFORM_MODE_LOCAL if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: mode = self._op_settings_listener.rotation_mode elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: mode = self._op_settings_listener.translation_mode return mode # Adds a delay to the visual update during translate (only) manipulation # It's due to the renderer having a delay of rendering the mesh and the manipulator appears to drift apart. # It's only an estimation and may varying from scene/renderer setup. async def _delay_dirty(self, transform, id): if self._viewport_fps: render_frame_time = 1.0 / self._viewport_fps * self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) while True: dt = await self._app.next_update_async() render_frame_time -= dt # break a frame early if render_frame_time < dt: break # cancel earlier job if a later one catches up (fps suddenly changed?) earlier_tasks_or_futures = [] for key, task_or_future in self._delay_dirty_tasks_or_futures.items(): if key < id: earlier_tasks_or_futures.append(key) task_or_future.cancel() else: break for key in earlier_tasks_or_futures: self._delay_dirty_tasks_or_futures.pop(key) self._transform = transform self._item_changed(self._transform_item) self._delay_dirty_tasks_or_futures.pop(id) def _update_temp_pivot_world_position(self): if type(self._transform) is not list: return new_world_position = self._transform[12:15] self._settings.set_float_array( self._selection_pivot_position_path, new_world_position ) @carb.profiler.profile def _update_transform_from_prims(self): xform_flattened = self._calculate_transform_from_prim() if self._transform != xform_flattened: self._transform = xform_flattened # update setting with new pivot placement position self._update_temp_pivot_world_position() return True return False #def _calculate_transform_from_obj(self): def _calculate_transform_from_prim(self): if not self._dataAccessor.get_stage(): return False if not self._pivot_prim: return False self._dataAccessor.clear_xform_cache() cur_time = self._dataAccessor.get_current_time_code(self._current_time) mode = self._get_transform_mode_for_current_op() pivot_inv = get_local_transform_pivot_inv(self._pivot_prim, cur_time) if self._should_keep_manipulator_orientation_unchanged(mode): pivot_prim_path = self._pivot_prim.GetPath() (s, r, ro, t) = self._dataAccessor.get_local_transform_SRT(self._pivot_prim, cur_time) pivot = get_local_transform_pivot_inv(self._pivot_prim, self._dataAccessor.get_current_time_code(self._current_time)).GetInverse() self.all_xformable_prim_data_curr[pivot_prim_path] = (s, r, ro, t) + (pivot,) # This method may be called from _on_op_listener_changed, before any gesture has started # in which case _all_xformable_prim_data_prev would be empty piv_xf_tuple = self._all_xformable_prim_data_prev.get(pivot_prim_path, False) if not piv_xf_tuple: piv_xf_tuple = self._dataAccessor.get_local_transform_SRT(self._pivot_prim, cur_time) pv_xf_pivot = get_local_transform_pivot_inv( self._pivot_prim, self._dataAccessor.get_current_time_code(self._current_time) ).GetInverse() self._all_xformable_prim_data_prev[self._pivot_prim.GetPath()] = piv_xf_tuple + (pv_xf_pivot,) (s_p, r_p, ro_p, t_p, t_piv) = piv_xf_tuple xform = self._construct_transform_matrix_from_SRT(t, r_p, ro_p, s, pivot_inv) parent = self._dataAccessor.get_local_to_world_transform(self._pivot_prim.GetParent()) xform *= parent else: xform = self._dataAccessor.get_local_to_world_transform(self._pivot_prim) xform = pivot_inv.GetInverse() * xform if self._should_keep_manipulator_translation_unchanged(mode): xform.SetTranslateOnly((self._transform[12], self._transform[13], self._transform[14])) else: # if there's only one selection, we always use LAST_PRIM_PIVOT though if ( self._placement != Placement.LAST_PRIM_PIVOT and self._placement != Placement.REF_PRIM ): average_translation = Gf.Vec3d(0.0) if self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE: world_bound = Gf.Range3d() def get_prim_translation(xformable): xformable_world_mtx = self._dataAccessor.get_local_to_world_transform(xformable) xformable_pivot_inv = get_local_transform_pivot_inv(xformable, cur_time) xformable_world_mtx = xformable_pivot_inv.GetInverse() * xformable_world_mtx return xformable_world_mtx.ExtractTranslation() for path in self._xformable_prim_paths: xformable = self._dataAccessor.get_prim_at_path(path) if self._placement == Placement.SELECTION_CENTER: average_translation += get_prim_translation(xformable) elif self._placement == Placement.BBOX_CENTER or Placement.BBOX_BASE: bound_range = self._usd_context.compute_path_world_bounding_box(path.pathString) bound_range = Gf.Range3d(Gf.Vec3d(*bound_range[0]), Gf.Vec3d(*bound_range[1])) if not bound_range.IsEmpty(): world_bound = Gf.Range3d.GetUnion(world_bound, bound_range) else: # extend world bound with tranlation for prims with zero bbox, e.g. Xform, Camera prim_translation = get_prim_translation(xformable) world_bound.UnionWith(prim_translation) if self._placement == Placement.SELECTION_CENTER: average_translation /= len(self._xformable_prim_paths) elif self._placement == Placement.BBOX_CENTER: average_translation = world_bound.GetMidpoint() elif self._placement == Placement.BBOX_BASE: # xform may not have bbox but its descendants may have, exclude cases that only xform are selected if not world_bound.IsEmpty(): bbox_center = world_bound.GetMidpoint() bbox_size = world_bound.GetSize() if UsdGeom.GetStageUpAxis(self._dataAccessor.get_stage()) == UsdGeom.Tokens.y: # Y-up world average_translation = bbox_center - Gf.Vec3d(0.0, bbox_size[1]/2.0, 0.0) else: # Z-up world average_translation = bbox_center - Gf.Vec3d(0.0, 0.0, bbox_size[2]/2.0) else: # fallback to SELECTION_CENTER average_translation /= len(self._xformable_prim_paths) # Only take the translate from selected prim average. # The rotation and scale still comes from pivot prim xform.SetTranslateOnly(average_translation) # instead of using RemoveScaleShear, additional steps made to handle negative scale properly scale, _, _, _ = self._dataAccessor.get_local_transform_SRT(self._pivot_prim, cur_time) scale_epsilon = 1e-6 for i in range(3): if Gf.IsClose(scale[i], 0.0, scale_epsilon): scale[i] = -scale_epsilon if scale[i] < 0 else scale_epsilon inverse_scale = Gf.Matrix4d().SetScale(Gf.Vec3d(1.0 / scale[0], 1.0 / scale[1], 1.0 / scale[2])) xform = inverse_scale * xform # this is the average xform without scale self._no_scale_transform_manipulator = Gf.Matrix4d(xform) # store the scale separately self._scale_manipulator = Gf.Vec3d(scale) # Visual transform of the manipulator xform = xform.RemoveScaleShear() if mode == c.TRANSFORM_MODE_GLOBAL: xform = xform.SetTranslate(xform.ExtractTranslation()) return flatten(xform) def _construct_transform_matrix_from_SRT( self, translation: Gf.Vec3d, rotation_euler: Gf.Vec3d, rotation_order: Gf.Vec3i, scale: Gf.Vec3d, pivot_inv: Gf.Matrix4d, ): trans_mtx = Gf.Matrix4d() rot_mtx = Gf.Matrix4d() scale_mtx = Gf.Matrix4d() trans_mtx.SetTranslate(Gf.Vec3d(translation)) axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] rotation = ( Gf.Rotation(axes[rotation_order[0]], rotation_euler[rotation_order[0]]) * Gf.Rotation(axes[rotation_order[1]], rotation_euler[rotation_order[1]]) * Gf.Rotation(axes[rotation_order[2]], rotation_euler[rotation_order[2]]) ) rot_mtx.SetRotate(rotation) scale_mtx.SetScale(Gf.Vec3d(scale)) return pivot_inv * scale_mtx * rot_mtx * pivot_inv.GetInverse() * trans_mtx def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str): if type == OpSettingsListener.CallbackType.OP_CHANGED: # cancel all delayed tasks for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() self._update_transform_from_prims() self._item_changed(self._transform_item) elif type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: if self._update_transform_from_prims(): self._item_changed(self._transform_item) elif type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _update_placement(self, placement_str: str): if placement_str == prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER: placement = Placement.SELECTION_CENTER elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER: placement = Placement.BBOX_CENTER elif placement_str == prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: placement = Placement.REF_PRIM elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE: placement = Placement.BBOX_BASE else: # placement == prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT or bad values placement = Placement.LAST_PRIM_PIVOT if placement != self._placement: if placement == Placement.LAST_PRIM_PIVOT and self._placement == Placement.REF_PRIM: # reset the pivot prim in case it was changed by MANIPULATOR_PLACEMENT_PICK_REF_PRIM if self._xformable_prim_paths: self._pivot_prim = self._dataAccessor.get_prim_at_path(self._xformable_prim_paths[-1]) self._placement = placement if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _on_placement_setting_changed(self, item, event_type): placement_str = self._dict.get(item) self._update_placement(placement_str) def _check_update_selected_instance_proxy_list(self, path: Sdf.Path, resynced): def track_or_remove_from_instance_proxy_list(prim): valid_proxy = prim and prim.IsActive() and prim.IsInstanceProxy() if valid_proxy: self._selected_instance_proxy_paths.add(prim.GetPath()) else: self._selected_instance_proxy_paths.discard(prim.GetPath()) prim_path = path.GetPrimPath() changed_prim = self._dataAccessor.get_prim_at_path(prim_path) # Update list of instance proxy paths. if resynced and path.IsPrimPath(): if prim_path in self._consolidated_xformable_prim_paths: # Quick path if it's selected already. track_or_remove_from_instance_proxy_list(changed_prim) else: # Slow path to verify if any of its ancestors are changed. for path in self._consolidated_xformable_prim_paths: if not path.HasPrefix(prim_path): continue prim = self._dataAccessor.get_prim_at_path(path) track_or_remove_from_instance_proxy_list(prim) @carb.profiler.profile async def _update_transform_from_prims_async(self): try: check_all_prims = ( self._placement != Placement.LAST_PRIM_PIVOT and self._placement != Placement.REF_PRIM and len(self._xformable_prim_paths) > 1 ) pivot_prim_path = self._pivot_prim.GetPath() for p, resynced in self._pending_changed_paths.items(): self._check_update_selected_instance_proxy_list(p, resynced) prim_path = p.GetPrimPath() # Update either check_all_prims # or prim_path is a prefix of pivot_prim_path (pivot prim's parent affect pivot prim transform) # Note: If you move the manipulator and the prim flies away while manipulator stays in place, check this # condition! if ( # check _xformable_prim_paths_prefix_set so that if the parent path of selected prim(s) changed, it # can still update manipulator transform prim_path in self._xformable_prim_paths_prefix_set if check_all_prims else pivot_prim_path.HasPrefix(prim_path) ): if self._path_may_affect_transform(p): # only delay the visual update in translate mode. should_delay_frame = self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) > 0 if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE and should_delay_frame: xform = self._calculate_transform_from_prim() id = self._app.get_update_number() self._delay_dirty_tasks_or_futures[id] = run_coroutine(self._delay_dirty(xform, id)) else: if self._update_transform_from_prims(): self._item_changed(self._transform_item) break except Exception as e: carb.log_error(traceback.format_exc()) finally: self._pending_changed_paths.clear() self._update_prim_xform_from_prim_task_or_future = None @carb.profiler.profile def _on_objects_changed(self, notice, sender): if not self._pivot_prim: return # collect resynced paths so that removed/added xformOps triggers refresh for path in notice.GetResyncedPaths(): self._pending_changed_paths[path] = True # collect changed only paths for path in notice.GetChangedInfoOnlyPaths(): self._pending_changed_paths[path] = False # if an operation is in progess, record all dirty xform path if self._current_editing_op is not None and not self._ignore_xform_data_change: self._pending_changed_paths_for_xform_data.update(notice.GetChangedInfoOnlyPaths()) if self._update_prim_xform_from_prim_task_or_future is None or self._update_prim_xform_from_prim_task_or_future.done(): self._update_prim_xform_from_prim_task_or_future = run_coroutine(self._update_transform_from_prims_async()) def _set_default_settings(self): self._settings.set_default(TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED, False) self._settings.set_default(TRANSFORM_GIZMO_IS_USING, False) self._settings.set_default(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, [0, 0, 0]) self._settings.set_default(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, [0, 0, 0, 1]) self._settings.set_default(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, [0, 0, 0]) def _should_skip_custom_manipulator_path(self, path: str) -> bool: custom_manipulator_path_prims_settings_path = TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS + path return self._settings.get(custom_manipulator_path_prims_settings_path) def _path_may_affect_transform(self, path: Sdf.Path) -> bool: # Batched changes sent in a SdfChangeBlock may not have property name but only the prim path return not path.ContainsPropertyElements() or UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name) @property def stage(self): return self._dataAccessor.get_stage() @property def custom_manipulator_enabled(self): return self._custom_manipulator_enabled @property def snap_settings_listener(self): return self._snap_settings_listener @property def op_settings_listener(self): return self._op_settings_listener @property def usd_context(self) -> omni.usd.UsdContext: return self._usd_context @property def xformable_prim_paths(self) -> List[Sdf.Path]: return self._xformable_prim_paths class PrimDataAccessorRegistry(DataAccessorRegistry): def __init__(self, dataType = "USD"): self._dataType = dataType def getDataAccessor(self, model): if self._dataType == "USD": self.dataAccessor = UsdDataAccessor(model = model) elif self._dataType == "Fabric": self.dataAccessor = FabricDataAccessor(model = model) else: self.dataAccessor = None #self.dataAccessor = FabricDataAccessor() return self.dataAccessor #to be moved to omni.kit.manipulator.prim2.usd class UsdDataAccessor(DataAccessor): def __init__(self, usd_context_name: str = "", model = None): super().__init__() self._model = model self._xform_cache = None self._stage: Usd.Stage = None def _update_transform_from_prims(self): ... def _update_xform_data_from_dirty_paths(self): ... def get_prim_at_path(self, path): return self._stage.GetPrimAtPath(path) def get_current_time_code(self, currentTime): return Usd.TimeCode(omni.usd.get_frame_time_code(currentTime, self._stage.GetTimeCodesPerSecond())) def get_local_transform_SRT(self, prim, time): return omni.usd.get_local_transform_SRT(prim, time) #xform cache def get_local_to_world_transform(self, obj): return self._xform_cache.GetLocalToWorldTransform(obj) def get_parent_to_world_transform(self, obj): return self._xform_cache.GetParentToWorldTransform(obj) def clear_xform_cache(self): self._xform_cache.Clear() def free_xform_cache(self): self._xform_cache = None def xform_set_time(self): self._xform_cache.SetTime(self.get_current_time_code(self._model._current_time)) def update_xform_cache(self): self._xform_cache = UsdGeom.XformCache(self.get_current_time_code(self._model._current_time)) #stage def free_stage(self): self._stage = None def get_stage(self): return self._stage #callbacks def setup_update_callback(self, function): res = Tf.Notice.Register(Usd.Notice.ObjectsChanged, function, self._stage) carb.log_info("Tf.Notice.Register in PrimTransformModel") return res def remove_update_callback(self, listener): #removeUpdateCallback listener.Revoke() carb.log_info("Tf.Notice.Revoke in PrimTransformModel") return None #USD specific commands def _do_transform_all_selected_prims_to_manipulator_pivot( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): omni.kit.commands.create( "TransformMultiPrimsSRTCpp", count=len(paths), no_undo=True, paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, usd_context_name=self._model._usd_context_name, time_code=self.get_current_time_code(self._model._current_time).GetValue(), ).do() def _do_transform_selected_prims( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): omni.kit.commands.create( "TransformMultiPrimsSRTCpp", count=len(paths), no_undo=True, paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, usd_context_name=self._model._usd_context_name, time_code=self.get_current_time_code(self._model._current_time).GetValue(), ).do() def _on_ended_transform( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], old_translations: List[float], old_rotation_eulers: List[float], old_rotation_orders: List[int], old_scales: List[float], ): omni.kit.commands.execute( "TransformMultiPrimsSRTCpp", count=len(paths), paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, old_translations=old_translations, old_rotation_eulers=old_rotation_eulers, old_rotation_orders=old_rotation_orders, old_scales=old_scales, usd_context_name=self._model._usd_context_name, time_code=self.get_current_time_code(self._model._current_time).GetValue(), ) #to be moved to omni.kit.manipulator.prim2.fabric class FabricDataAccessor(DataAccessor): #TODO def __init__(self, usd_context_name: str = "", model = None): ...
64,918
Python
45.140014
149
0.627191
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/pivot_button_group.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 pathlib import Path import carb.input import carb.settings import omni.kit.context_menu import omni.ui as ui from omni.kit.widget.toolbar.widget_group import WidgetGroup ICON_FOLDER_PATH = Path( f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons" ) class PivotButtonGroup(WidgetGroup): """ Toolbar entry for pivot placement """ def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._settings = carb.settings.get_settings() def clean(self): super().clean() def __del__(self): self.clean() def get_style(self): style = { "Button.Image::pivot_placement": {"image_url": f"{ICON_FOLDER_PATH}/pivot_location.svg"} } return style def get_button(self) -> ui.ToolButton: return self._button def create(self, default_size): self._button = ui.Button( name="pivot_placement", width=default_size, height=default_size, tooltip="Pivot Placement", mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "multi_sel_pivot", min_menu_entries=1), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b) ) return {"pivot": self._button} def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2): # override default behavior, left or right click will show menu without delay self._acquire_toolbar_context() if button == 0 or button == 1: self._invoke_context_menu(button_id, min_menu_entries) def _invoke_context_menu(self, button_id: str, min_menu_entries: int = 1): """ Function to invoke context menu. Args: button_id: button_id of the context menu to be invoked. min_menu_entries: minimal number of menu entries required for menu to be visible (default 1). """ button_id = "multi_sel_pivot" context_menu = omni.kit.context_menu.get_instance() objects = {"widget_name": button_id, "main_toolbar": True} menu_list = omni.kit.context_menu.get_menu_dict(button_id, "omni.kit.manipulator.prim2.core") context_menu.show_context_menu( button_id, objects, menu_list, min_menu_entries, delegate=ui.MenuDelegate() )
2,892
Python
32.639535
113
0.633126
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/prim_transform_manipulator_registry.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__ = ["TransformManipulatorRegistry"] import weakref from omni.kit.viewport.registry import RegisterScene from .prim_transform_manipulator import PrimTransformManipulator from .reference_prim_marker import ReferencePrimMarker class PrimTransformManipulatorScene: def __init__(self, desc: dict): usd_context_name = desc.get("usd_context_name") self.__transform_manip = PrimTransformManipulator( usd_context_name=usd_context_name, viewport_api=desc.get("viewport_api") ) self.__reference_prim_marker = ReferencePrimMarker( usd_context_name=usd_context_name, manipulator_model=weakref.proxy(self.__transform_manip.model) ) def destroy(self): if self.__transform_manip: self.__transform_manip.destroy() self.__transform_manip = None if self.__reference_prim_marker: self.__reference_prim_marker.destroy() self.__reference_prim_marker = None # PrimTransformManipulator & TransformManipulator don't have their own visibility @property def visible(self): return True @visible.setter def visible(self, value): pass @property def categories(self): return ("manipulator",) @property def name(self): return "Prim Transform" class TransformManipulatorRegistry: def __init__(self): self._scene = RegisterScene(PrimTransformManipulatorScene, "omni.kit.manipulator.prim2.core") def __del__(self): self.destroy() def destroy(self): self._scene = None
2,024
Python
29.681818
108
0.692194
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .test_manipulator_prim import TestTransform
478
Python
42.545451
76
0.811715
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/omni/kit/manipulator/prim2/core/tests/test_manipulator_prim.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 inspect import logging import math import os from pathlib import Path from typing import Awaitable, Callable, List import carb import carb.input import carb.settings import omni.kit.commands import omni.kit.ui_test as ui_test import omni.kit.undo import omni.usd from carb.input import MouseEventType from omni.kit.manipulator.prim2.core.settings_constants import Constants as prim_c from omni.kit.manipulator.tool.snap import settings_constants as snap_c from omni.kit.manipulator.tool.snap.builtin_snap_tools import SURFACE_SNAP_NAME from omni.kit.manipulator.transform.settings_constants import c from omni.kit.ui_test import Vec2 from omni.ui.tests.test_base import OmniUiTest from omni.kit.test_helpers_gfx.compare_utils import capture_and_compare, ComparisonMetric from pxr import UsdGeom, Gf CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.prim2.core}/data")) OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()).resolve().absolute() logger = logging.getLogger(__name__) class TestTransform(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._context = omni.usd.get_context() self._selection = self._context.get_selection() self._settings = carb.settings.get_settings() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("golden") self._usd_scene_dir = CURRENT_PATH.absolute().resolve().joinpath("tests").joinpath("usd") self._window_width = self._settings.get("/app/window/width") self._window_height = self._settings.get("/app/window/height") # Load renderer before USD is loaded await self._context.new_stage_async() # After running each test async def tearDown(self): # Move and close the stage so selections are reset to avoid triggering ghost gestures. await ui_test.emulate_mouse_move(Vec2(0, 0)) await ui_test.human_delay() await self._context.close_stage_async() self._golden_img_dir = None await super().tearDown() async def _snapshot(self, golden_img_name: str = "", threshold: float = 2e-4): await ui_test.human_delay() test_fn_name = "" for frame_info in inspect.stack(): if os.path.samefile(frame_info[1], __file__): test_fn_name = frame_info[3] golden_img_name = f"{test_fn_name}.{golden_img_name}.png" # Because we're testing RTX renderered pixels, use a better threshold filter for differences diff = await capture_and_compare( golden_img_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=self._golden_img_dir, metric=ComparisonMetric.MEAN_ERROR_SQUARED, ) self.assertLessEqual( diff, threshold, f"The generated image {golden_img_name} has a difference of {diff}, but max difference is {threshold}", ) async def _setup_global( self, op: str, enable_toolbar: bool = False, file_name: str = "test_scene.usda", prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"], placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, ): await self._setup(file_name, c.TRANSFORM_MODE_GLOBAL, op, enable_toolbar, prims_to_select, placement) async def _setup_local( self, op: str, enable_toolbar: bool = False, file_name: str = "test_scene.usda", prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"], placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, ): await self._setup(file_name, c.TRANSFORM_MODE_LOCAL, op, enable_toolbar, prims_to_select, placement) async def _setup( self, scene_file: str, mode: str, op: str, enable_toolbar: bool = False, prims_to_select=["/World/Cube", "/World/Xform", "/World/Xform/Cube_01"], placement=prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, ): usd_path = self._usd_scene_dir.joinpath(scene_file) success, error = await self._context.open_stage_async(str(usd_path)) self.assertTrue(success, error) # move the mouse out of the way await ui_test.emulate_mouse_move(Vec2(0, 0)) await ui_test.human_delay() self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, placement) self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, mode) self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, mode) self._settings.set(c.TRANSFORM_OP_SETTING, op) self._settings.set("/app/viewport/snapEnabled", False) self._settings.set("/persistent/app/viewport/snapToSurface", False) self._settings.set("/exts/omni.kit.manipulator.prim2.core/tools/enabled", enable_toolbar) self._selection.set_selected_prim_paths([], True) await ui_test.human_delay(human_delay_speed=10) self._selection.set_selected_prim_paths(prims_to_select, True) await ui_test.human_delay(human_delay_speed=10) # Save prims initial state to restore to. stage = self._context.get_stage() self._restore_transform = {} for prim_path in prims_to_select: xform_ops = [] for xform_op in UsdGeom.Xformable(stage.GetPrimAtPath(prim_path)).GetOrderedXformOps(): if not xform_op.IsInverseOp(): xform_ops.append((xform_op, xform_op.Get())) self._restore_transform[prim_path] = xform_ops async def _restore_initial_state(self): for xform_op_list in self._restore_transform.values(): for xform_op_tuple in xform_op_list: xform_op, start_value = xform_op_tuple[0], xform_op_tuple[1] xform_op.Set(start_value) async def _emulate_mouse_drag_and_drop_multiple_waypoints( self, waypoints: List[Vec2], right_click=False, human_delay_speed: int = 4, num_steps: int = 8, on_before_drop: Callable[[int], Awaitable[None]] = None, ): """Emulate Mouse Drag & Drop. Click at start position and slowly move to end position.""" logger.info(f"emulate_mouse_drag_and_drop poses: {waypoints} (right_click: {right_click})") count = len(waypoints) if count < 2: return await ui_test.input.emulate_mouse(MouseEventType.MOVE, waypoints[0]) await ui_test.human_delay(human_delay_speed) await ui_test.input.emulate_mouse( MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN ) await ui_test.human_delay(human_delay_speed) for i in range(1, count): await ui_test.input.emulate_mouse_slow_move( waypoints[i - 1], waypoints[i], num_steps=num_steps, human_delay_speed=human_delay_speed ) if on_before_drop: await ui_test.human_delay(human_delay_speed) await on_before_drop() await ui_test.input.emulate_mouse( MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP ) await ui_test.human_delay(human_delay_speed) ################################################################ ################## test manipulator placement ################## ################################################################ async def test_placement(self): await self._setup_global(c.TRANSFORM_OP_MOVE) PLACEMENTS = { "placement_selection_center": prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER, "placement_bbox_center": prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER, "placement_authored_pivot": prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT, "placement_bbox_base": prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE } for test_name, val in PLACEMENTS.items(): self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, val) await ui_test.human_delay() await self._snapshot(test_name) async def test_tmp_placement(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01", "/World/Cube"]) self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM) await ui_test.human_delay() await self._snapshot("pick_default") center = Vec2(self._window_width, self._window_height) / 2 # pick the other prim as tmp pivot prim await ui_test.emulate_mouse_move_and_click(center) await ui_test.human_delay() await self._snapshot("pick") # reset placement to last prim, the manipulator should go to last prim and marker disappears self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT) await ui_test.human_delay() await self._snapshot("last_selected") async def test_bbox_placement_for_xform(self): await self._setup_global(c.TRANSFORM_OP_MOVE, file_name="test_pivot_with_invalid_bbox.usda", prims_to_select=["/World/Xform"]) self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER) await ui_test.human_delay() await self._snapshot("placement_bbox_center") self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE) await ui_test.human_delay() await self._snapshot("placement_bbox_base") ################################################################ ####################### test translation ####################### ################################################################ ################## test manipulator move axis ################## async def test_move_global_axis(self): await self._setup_global(c.TRANSFORM_OP_MOVE) await self._test_move_axis() async def test_move_local_axis(self): await self._setup_local(c.TRANSFORM_OP_MOVE) await self._test_move_axis(180) async def _test_move_axis(self, angle_offset: float = 0, distance: float = 50): OFFSET = 50 MOVEMENT = ["x", "y", "z"] center = Vec2(self._window_width, self._window_height) / 2 for i, test_name in enumerate(MOVEMENT): await ui_test.human_delay() dir = Vec2( math.cos(math.radians(-i * 120 + 30 + angle_offset)), math.sin(math.radians(-i * 120 + 30 + angle_offset)), ) try: await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance)) await self._snapshot(f"{test_name}.{angle_offset}.{distance}") finally: await self._restore_initial_state() ################## test manipulator move plane ################## async def test_move_global_plane(self): await self._setup_global(c.TRANSFORM_OP_MOVE) await self._test_move_plane() async def test_move_local_plane(self): await self._setup_local(c.TRANSFORM_OP_MOVE) await self._test_move_plane(180) async def _test_move_plane(self, angle_offset: float = 0, distance=75): OFFSET = 50 MOVEMENT = ["xz", "zy", "yx"] center = Vec2(self._window_width, self._window_height) / 2 for i, test_name in enumerate(MOVEMENT): await ui_test.human_delay() dir = Vec2( math.cos(math.radians(-i * 120 + 90 + angle_offset)), math.sin(math.radians(-i * 120 + 90 + angle_offset)), ) try: await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance)) await self._snapshot(f"{test_name}.{angle_offset}.{distance}") finally: await self._restore_initial_state() ################## test manipulator move center ################## async def test_move_global_center(self): await self._setup_global(c.TRANSFORM_OP_MOVE) await self._test_move_center() await self._test_move_center( modifier=carb.input.KeyboardInput.LEFT_ALT ) # with alt down, transform is not changed async def test_move_local_center(self): await self._setup_local(c.TRANSFORM_OP_MOVE) await self._test_move_center() async def _test_move_center(self, dirs=[Vec2(50, 0)], modifier: carb.input.KeyboardInput = None): try: center = Vec2(self._window_width, self._window_height) / 2 waypoints = [center] for dir in dirs: waypoints.append(center + dir) if modifier: await ui_test.input.emulate_keyboard(carb.input.KeyboardEventType.KEY_PRESS, modifier) await ui_test.human_delay() await self._emulate_mouse_drag_and_drop_multiple_waypoints(waypoints) if modifier: await ui_test.input.emulate_keyboard(carb.input.KeyboardEventType.KEY_RELEASE, modifier) await ui_test.human_delay() test_name = f"xyz.{len(dirs)}" if modifier: test_name += str(modifier).split(".")[-1] await self._snapshot(test_name) # todo better hash name? finally: await self._restore_initial_state() # Test manipulator is placed correctly if the selected prim's parent is moved async def test_move_selected_parent(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01"]) stage = self._context.get_stage() parent_translate_attr = stage.GetAttributeAtPath("/World/Xform.xformOp:translate") try: parent_translate_attr.Set((0, 100, -100)) await ui_test.human_delay(4) await self._snapshot() finally: await self._restore_initial_state() ################################################################ ######################## test rotation ######################### ################################################################ ################## test manipulator rotate arc ################## async def test_rotate_global_arc(self): await self._setup_global(c.TRANSFORM_OP_ROTATE) await self._test_rotate_arc() # add a test to only select prims in the same hierarchy and pivot prim being the child # to cover the bug when consolidated prim path has one entry and is not the pivot prim async def test_rotate_global_arc_single_hierarchy(self): await self._setup_global(c.TRANSFORM_OP_ROTATE, prims_to_select=["/World/Xform", "/World/Xform/Cube_01"]) await self._test_rotate_arc() async def test_rotate_local_arc(self): await self._setup_local(c.TRANSFORM_OP_ROTATE) await self._test_rotate_arc(180) async def test_free_rotation_clamped(self): await self._setup_global(c.TRANSFORM_OP_ROTATE) self._settings.set(c.FREE_ROTATION_TYPE_SETTING, c.FREE_ROTATION_TYPE_CLAMPED) await self._test_move_center(dirs=[Vec2(100, 100)]) async def test_free_rotation_continuous(self): await self._setup_global(c.TRANSFORM_OP_ROTATE) self._settings.set(c.FREE_ROTATION_TYPE_SETTING, c.FREE_ROTATION_TYPE_CONTINUOUS) await self._test_move_center(dirs=[Vec2(100, 100)]) async def test_bbox_center_multi_prim_rotate_global(self): await self._test_bbox_center_multi_prim_rotate(self._setup_global) async def test_bbox_center_multi_prim_rotate_local(self): await self._test_bbox_center_multi_prim_rotate(self._setup_local) async def _test_bbox_center_multi_prim_rotate(self, test_fn): await test_fn( c.TRANSFORM_OP_ROTATE, file_name="test_bbox_rotation.usda", prims_to_select=["/World/Cube", "/World/Cube_01", "/World/Cube_02"], placement=prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER, ) await self._test_rotate_arc(post_snap=True) async def _test_rotate_arc(self, offset: float = 0, post_snap=False): OFFSET = 45 MOVEMENT = ["x", "y", "z", "screen"] SEGMENT_COUNT = 12 center = Vec2(self._window_width, self._window_height) / 2 for i, test_name in enumerate(MOVEMENT): await ui_test.human_delay() waypoints = [] step = 360 / SEGMENT_COUNT for wi in range(int(SEGMENT_COUNT * 1.5)): dir = Vec2( math.cos(math.radians(-i * 120 - 30 + wi * step + offset)), math.sin(math.radians(-i * 120 - 30 + wi * step + offset)), ) waypoints.append(center + dir * (OFFSET if i < 3 else 80)) try: async def before_drop(): await self._snapshot(test_name) await self._emulate_mouse_drag_and_drop_multiple_waypoints(waypoints, on_before_drop=before_drop) if post_snap: await ui_test.human_delay(human_delay_speed=4) await self._snapshot(f"{test_name}.post") finally: await self._restore_initial_state() ################################################################ ########################## test scale ########################## ################################################################ # Given the complexity of multi-manipulating with non-uniform scale and potential shear from parents, # we reduce the test complexity using a simpler manipulating case. # Revisit when there's more complicated scaling needs. ################## test manipulator scale axis ################## async def test_scale_local_axis(self): await self._setup_local(c.TRANSFORM_OP_SCALE) self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await ui_test.human_delay() # test scale up await self._test_move_axis(180) # test scale down await self._test_move_axis(180, distance=-100) ################## test manipulator move plane ################## async def test_scale_local_plane(self): await self._setup_local(c.TRANSFORM_OP_SCALE) self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await ui_test.human_delay() # test scale up await self._test_move_plane(180) # test scale down await self._test_move_plane(180, distance=-100) ################## test manipulator move center ################## async def test_scale_local_center(self): await self._setup_local(c.TRANSFORM_OP_SCALE) self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await ui_test.human_delay() await self._test_move_center() await ui_test.human_delay() await self._test_move_center(dirs=[Vec2(50, 0), Vec2(-100, 0)]) ################################################################ ################### test manipulator toolbar ################### ################################################################ async def test_toolbar(self): await self._setup_global(c.TRANSFORM_OP_MOVE, True) await ui_test.human_delay(30) await ui_test.emulate_mouse_move_and_click(Vec2(210, 340), human_delay_speed=20) # expand the toolbar and take a snapshot to make sure the render/layout is correct. # if you changed the look of toolbar button or toolbar layout, update the golden image for this test. # added since OM-65012 for a broken button image await self._snapshot("visual") # Test the local/global button await ui_test.human_delay(30) await ui_test.emulate_mouse_move_and_click(Vec2(215, 365), human_delay_speed=20) self.assertEqual(self._settings.get(c.TRANSFORM_MOVE_MODE_SETTING), c.TRANSFORM_MODE_LOCAL) await ui_test.human_delay(30) await ui_test.emulate_mouse_move_and_click(Vec2(215, 365), human_delay_speed=20) self.assertEqual(self._settings.get(c.TRANSFORM_MOVE_MODE_SETTING), c.TRANSFORM_MODE_GLOBAL) ################################################################ #################### test manipulator snap ##################### ################################################################ async def _run_snap_test(self, keep_spacing: bool): await self._setup_global(c.TRANSFORM_OP_MOVE, True, "test_snap.usda", ["/World/Cube", "/World/Cube_01"]) stage = self._context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") cube01_prim = stage.GetPrimAtPath("/World/Cube_01") _, _, _, translate_cube_original = omni.usd.get_local_transform_SRT(cube_prim) _, _, _, translate_cube01_original = omni.usd.get_local_transform_SRT(cube01_prim) self._settings.set(prim_c.MANIPULATOR_PLACEMENT_SETTING, prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER) self._settings.set(snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, [SURFACE_SNAP_NAME]) self._settings.set(snap_c.CONFORM_TO_TARGET_SETTING_PATH, True) self._settings.set(snap_c.KEEP_SPACING_SETTING_PATH, keep_spacing) self._settings.set("/app/viewport/snapEnabled", True) center = Vec2(self._window_width, self._window_height) / 2 await ui_test.human_delay() await ui_test.emulate_mouse_move(center, 10) await self._emulate_mouse_drag_and_drop_multiple_waypoints( [center, center / 1.5], human_delay_speed=1, num_steps=50 ) _, _, _, translate_cube = omni.usd.get_local_transform_SRT(cube_prim) _, _, _, translate_cube01 = omni.usd.get_local_transform_SRT(cube01_prim) self._settings.set("/app/viewport/snapEnabled", False) return translate_cube, translate_cube_original, translate_cube01, translate_cube01_original async def test_snap_keep_spacing(self): ( translate_cube, translate_cube_original, translate_cube01, translate_cube01_original, ) = await self._run_snap_test(True) # Make sure start conditions aren't already on Plane self.assertFalse(Gf.IsClose(translate_cube_original[1], -100, 0.02)) self.assertFalse(Gf.IsClose(translate_cube01_original[1], -100, 0.02)) # Y position should be snapped to surface at -100 Y (within a tolerance for Storm) self.assertTrue(Gf.IsClose(translate_cube[1], -100, 0.02)) self.assertTrue(Gf.IsClose(translate_cube01[1], -100, 0.02)) # X and Z should be greater than original self.assertTrue(translate_cube[0] > translate_cube_original[0]) self.assertTrue(translate_cube[2] > translate_cube_original[2]) # X and Z should be greater than original self.assertTrue(translate_cube01[2] > translate_cube01_original[2]) self.assertTrue(translate_cube01[0] > translate_cube01_original[0]) # Workaround for testing on new Viewport, needs delay before running test_snap_no_keep_spacing test. self._selection.set_selected_prim_paths([], True) await ui_test.human_delay(10) async def test_snap_no_keep_spacing(self): ( translate_cube, translate_cube_original, translate_cube01, translate_cube01_original, ) = await self._run_snap_test(False) self.assertFalse(Gf.IsClose(translate_cube_original[1], -100, 0.02)) self.assertFalse(Gf.IsClose(translate_cube01_original[1], -100, 0.02)) # cube and cube01 should be at same location since keep spacing is off self.assertTrue(Gf.IsClose(translate_cube, translate_cube01, 1e-6)) # Y position should be snapped to surface at -100 Y self.assertTrue(Gf.IsClose(translate_cube[1], -100, 0.02)) # X and Z should be greater than original self.assertTrue(translate_cube[0] > translate_cube_original[0]) self.assertTrue(translate_cube[2] > translate_cube_original[2]) # Workaround for testing on new Viewport, needs delay before running test_snap_no_keep_spacing test. self._selection.set_selected_prim_paths([], True) await ui_test.human_delay(10) ################################################################ ##################### test prim with pivot ##################### ################################################################ async def _test_move_axis_one_dir(self, dir: Vec2 = Vec2(0, 1), distance: float = 50): OFFSET = 50 center = Vec2(self._window_width, self._window_height) / 2 try: await ui_test.emulate_mouse_drag_and_drop(center + dir * OFFSET, center + dir * (OFFSET + distance)) await self._snapshot(f"{distance}") finally: await self._restore_initial_state() async def test_move_local_axis_with_pivot(self): # tests for when _should_keep_manipulator_orientation_unchanged is true await self._setup_local(c.TRANSFORM_OP_MOVE, file_name="test_pivot.usda", prims_to_select=["/World/Cube"]) await self._test_move_axis_one_dir() async def test_scale_local_axis_with_pivot(self): # tests for when _should_keep_manipulator_orientation_unchanged is true await self._setup_local(c.TRANSFORM_OP_SCALE, file_name="test_pivot.usda", prims_to_select=["/World/Cube"]) await self._test_move_axis_one_dir() ################################################################ ##################### test remove xformOps ##################### ################################################################ async def test_remove_xform_ops_pivot(self): # remove the xformOps attributes, the manipulator position should update await self._setup_local( c.TRANSFORM_OP_MOVE, file_name="test_remove_xformOps.usda", prims_to_select=["/World/Cube"] ) stage = self._context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") attrs_to_remove = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] for attr in attrs_to_remove: cube_prim.RemoveProperty(attr) await ui_test.human_delay(10) await self._snapshot() async def test_remove_xform_op_order_pivot(self): # remove the xformOpOrder attribute, the manipulator position should update await self._setup_local( c.TRANSFORM_OP_MOVE, file_name="test_remove_xformOps.usda", prims_to_select=["/World/Cube"] ) stage = self._context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cube") cube_prim.RemoveProperty("xformOpOrder") await ui_test.human_delay(10) await self._snapshot() ################################################################ ################### test unknown op & modes #################### ################################################################ async def test_unknown_move_mode(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=["/World/Xform/Cube_01"]) await self._snapshot("pre-unknown-mode") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, "UNKNOWN") await self._snapshot("post-unknown-mode") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_LOCAL) await self._snapshot("reset-known-mode") async def test_unknown_rotate_mode(self): await self._setup_global(c.TRANSFORM_OP_ROTATE, prims_to_select=["/World/Xform/Cube_01"]) await self._snapshot("pre-unknown-mode") self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, "UNKNOWN") await self._snapshot("post-unknown-mode") self._settings.set(c.TRANSFORM_ROTATE_MODE_SETTING, c.TRANSFORM_MODE_LOCAL) await self._snapshot("reset-known-mode") async def test_unknown_mode_enabled(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=[]) await self._snapshot("known-mode-unselected") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, "UNKNOWN") await self._snapshot("unknown-mode-unselected") self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await self._snapshot("unknown-mode-selected") self._settings.set(c.TRANSFORM_MOVE_MODE_SETTING, c.TRANSFORM_MODE_GLOBAL) await self._snapshot("known-mode-selected") async def test_unknown_op_enabled(self): await self._setup_global(c.TRANSFORM_OP_MOVE, prims_to_select=[]) await self._snapshot("move-op-unselected") self._settings.set(c.TRANSFORM_OP_SETTING, "UNKNOWN") await self._snapshot("unknown-op-selected") self._selection.set_selected_prim_paths(["/World/Xform/Cube_01"], True) await self._snapshot("unknown-op-selected") self._settings.set(c.TRANSFORM_OP_SETTING, c.TRANSFORM_OP_ROTATE) await self._snapshot("rotate-op-selected")
29,723
Python
42.711765
134
0.600949
omniverse-code/kit/exts/omni.kit.manipulator.prim2.core/docs/index.rst
omni.kit.manipulator.prim2.core ########################### Prim 2 Manipulator Extension WIP .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule:: omni.kit.manipulator.prim2.core :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
360
reStructuredText
16.190475
47
0.638889
omniverse-code/kit/exts/omni.hydra.pxr/omni/hydra/pxr/engine/tests/__init__.py
from .render_test import *
27
Python
12.999994
26
0.740741
omniverse-code/kit/exts/omni.hydra.pxr/omni/hydra/pxr/engine/tests/render_test.py
import omni.kit.test import omni.usd import carb from omni.kit.viewport.utility.tests import capture_viewport_and_compare from omni.kit.test.teamcity import is_running_in_teamcity import sys import unittest from pathlib import Path EXTENSION_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${omni.hydra.pxr}")).resolve().absolute() TESTS_ROOT = EXTENSION_ROOT.joinpath("data", "tests") USD_SCENES = TESTS_ROOT.joinpath("usd") GOLDEN_IMAGES = TESTS_ROOT.joinpath("images") OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) class HydraTextureTest(omni.kit.test.AsyncTestCase): async def setUp(self): self.usd_context = omni.usd.get_context() await self.usd_context.new_stage_async() async def tearDown(self): await self.usd_context.new_stage_async() async def run_imge_test(self, usd_file: str, image_name: str, fn = None, wait_iterations: int = 5, threshold: int = 10): await self.usd_context.open_stage_async(str(USD_SCENES.joinpath(usd_file))) app = omni.kit.app.get_app() for i in range(wait_iterations): await app.next_update_async() if fn: fn() for i in range(wait_iterations): await app.next_update_async() passed, fail_msg = await capture_viewport_and_compare(image_name, threshold=threshold, output_img_dir=OUTPUTS_DIR, golden_img_dir=GOLDEN_IMAGES) self.assertTrue(passed, msg=fail_msg) @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_render_cube(self): """Test rendering produces an image""" await self.run_imge_test('cube.usda', 'render_cube.png') @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_render_cubes(self): """Test rendering produces an image after re-open""" await self.run_imge_test('cubes.usda', 'render_cubes.png') @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_select_cube_x(self): """Test selection on cube_x hilights correct prim""" await self.run_imge_test('cubes.usda', 'select_cube_x.png', lambda: self.usd_context.get_selection().set_selected_prim_paths(['/World/cube_x'], True) ) @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_select_cube_y(self): """Test selection on cube_y hilights correct prim""" await self.run_imge_test('cubes.usda', 'select_cube_y.png', lambda: self.usd_context.get_selection().set_selected_prim_paths(['/World/cube_y'], True) ) @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_select_cube_z(self): """Test selection on cube_z hilights correct prim""" await self.run_imge_test('cubes.usda', 'select_cube_z.png', lambda: self.usd_context.get_selection().set_selected_prim_paths(['/World/cube_z'], True) ) @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_display_purpose(self): """Test the carb display purpose settings""" def set_puposes(guide: bool, proxy: bool, render: bool): settings = carb.settings.get_settings() settings.set('/persistent/app/hydra/displayPurpose/guide', guide) settings.set('/persistent/app/hydra/displayPurpose/proxy', proxy) settings.set('/persistent/app/hydra/displayPurpose/render', render) try: # Test, guide, proxy, and render purposes render by default await self.run_imge_test('purpose.usda', 'all_purposes.png') # Test with proxy purpose disabled set_puposes(False, True, True) await self.run_imge_test('purpose.usda', 'proxy_purposes.png') # Test with guide purpose disabled set_puposes(True, False, True) await self.run_imge_test('purpose.usda', 'guide_purposes.png') # Test with render purpose disabled set_puposes(True, True, False) await self.run_imge_test('purpose.usda', 'render_purposes.png') finally: set_puposes(True, True, True) # Run the all purpose test once more now that all have been re-enabled await self.run_imge_test('purpose.usda', 'all_purposes.png') @unittest.skipIf(is_running_in_teamcity() and sys.platform.startswith("linux"), "OM-84020") async def test_rtx_render_modes(self): """Test some RTX render settings are honored""" settings = carb.settings.get_settings() settings.set("/rtx/debugMaterialType", -1) settings.set("/rtx/wireframe/mode", 0) try: # Test, guide, proxy, and render purposes render by default await self.run_imge_test('render_modes.usda', 'render_modes_default.png') settings.set("/rtx/debugMaterialType", 0) await self.run_imge_test('render_modes.usda', 'render_modes_no_material.png') # Tests below create images that are outside a meaningful range/image test on Windows with Vulkan # Since they are highly specific test of wireframe rendering, just skip them in that case import sys if sys.platform.startswith('win') and ("--vulkan" in sys.argv): return settings.set("/rtx/wireframe/mode", 2) await self.run_imge_test('render_modes.usda', 'render_modes_no_material_wire.png') settings.set("/rtx/debugMaterialType", -1) await self.run_imge_test('render_modes.usda', 'render_modes_wire_material.png') finally: settings.set("/rtx/debugMaterialType", -1) settings.set("/rtx/wireframe/mode", 0)
5,984
Python
43.333333
152
0.642714
omniverse-code/kit/exts/omni.kit.window.reshade_editor/PACKAGE-LICENSES/omni.kit.window.reshade_editor-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.reshade_editor/config/extension.toml
[package] title = "ReShade preset editor window" version = "0.1.1" repository = "" keywords = ["kit", "reshade"] [dependencies] "omni.ui" = {} "omni.kit.viewport.utility" = {} "omni.hydra.rtx" = {} [[python.module]] name = "omni.kit.window.reshade_editor" [[test]] viewport_legacy_only = true args = [ "--/rtx/reshade/enable=true" ] dependencies = [ "omni.kit.mainwindow", "omni.hydra.rtx", "omni.kit.window.viewport" ] timeout = 600 # OM-51983 stdoutFailPatterns.exclude = [ "*Tried to call pure virtual function \"AbstractItemModel::get_item_children\"*", ]
584
TOML
18.499999
85
0.659247
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/reshade_window.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.ui as ui import rtx.reshade from typing import Callable reshade = rtx.reshade.acquire_reshade_interface() class ComboListItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.model = ui.SimpleStringModel(text) class ComboListModel(ui.AbstractItemModel): def __init__(self, parent_model, items): super().__init__() self._current_index = parent_model self._current_index.add_value_changed_fn(lambda a: self._item_changed(None)) self._items = [ComboListItem(item) for item in items] def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model class ReshadeUniformValue(ui.AbstractItem, ui.AbstractValueModel): def __init__(self, handle, component: int, reshade_ctx): ui.AbstractItem.__init__(self) ui.AbstractValueModel.__init__(self) self._handle = handle self._component = component self._reshade_ctx = reshade_ctx def get_value_as_int(self) -> int: return reshade.get_uniform_value_as_int(self._reshade_ctx, self._handle, self._component) def get_value_as_bool(self) -> bool: return reshade.get_uniform_value_as_bool(self._reshade_ctx, self._handle, self._component) def get_value_as_float(self) -> float: return reshade.get_uniform_value_as_float(self._reshade_ctx, self._handle, self._component) def set_value(self, value): if isinstance(value, int): reshade.set_uniform_value_as_int(self._reshade_ctx, self._handle, self._component, value) else: reshade.set_uniform_value_as_float(self._reshade_ctx, self._handle, self._component, float(value)) self._value_changed() class ReshadeUniformVectorValue(ui.AbstractItemModel): def __init__(self, handle, component_count: int, reshade_ctx): super().__init__() self._items = [ ReshadeUniformValue(handle, component, reshade_ctx) for component in range(component_count) ] for item in self._items: item.add_value_changed_fn(lambda a, item=item: self._item_changed(item)) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): return item def begin_edit(self, item): pass # Crashes without this def end_edit(self, item): pass # Crashes without this class ReshadeUniformItem(ui.AbstractItem): def __init__(self, handle, reshade_ctx): super().__init__() type_info = reshade.get_uniform_type(handle) self._name = reshade.get_uniform_name(handle) self._base_type = type_info[0] self._components = type_info[1] self._ui_type = reshade.get_uniform_annotation_as_string(handle, "ui_type") self._ui_label = reshade.get_uniform_annotation_as_string(handle, "ui_label") self._ui_tooltip = reshade.get_uniform_annotation_as_string(handle, "ui_tooltip") ui_min = reshade.get_uniform_annotation_as_float(handle, "ui_min") ui_max = reshade.get_uniform_annotation_as_float(handle, "ui_max") if (ui_min == ui_max): self._ui_min = 0 self._ui_max = 1 else: self._ui_min = ui_min self._ui_max = ui_max self._ui_step = reshade.get_uniform_annotation_as_float(handle, "ui_step") ui_items = reshade.get_uniform_annotation_as_string(handle, "ui_items") self._ui_items = ui_items.split(';') if ui_items else [] if self._ui_items and not self._ui_items[-1]: # Delete last item if empty del self._ui_items[-1] self.model = ReshadeUniformValue(handle, 0, reshade_ctx) if self._components == 1 else ReshadeUniformVectorValue(handle, self._components, reshade_ctx) class ReshadeEffectListItem(ui.AbstractItem): def __init__(self, effect, reshade_ctx): super().__init__() self._name = reshade.get_effect_name(effect) self._uniforms = [] for handle in reshade.get_uniform_list(reshade_ctx, effect): if reshade.get_uniform_annotation_as_string(handle, "source"): continue # Skip uniforms that have a custom source self._uniforms.append(ReshadeUniformItem(handle, reshade_ctx)) class ReshadeVariableEditorModel(ui.AbstractItemModel): def __init__(self, reshade_ctx): super().__init__() self._effects = [] for handle in reshade.get_effect_list(reshade_ctx): effect = ReshadeEffectListItem(handle, reshade_ctx) if not effect._uniforms: continue # Skip effects that have not configurable uniforms self._effects.append(effect) def get_item_children(self, item): if item is None: return self._effects elif isinstance(item, ReshadeEffectListItem): return item._uniforms def get_item_value_model(self, item, column_id): if item is None: return None else: return item.model def get_item_value_model_count(self, item): return 1 class ReshadeVariableEditorDelegate(ui.AbstractItemDelegate): def build_branch(self, model, item, column_id, level, expanded): with ui.HStack(width=20*level, height=0): if level == 0: triangle_alignment = ui.Alignment.RIGHT_CENTER if expanded: triangle_alignment = ui.Alignment.CENTER_BOTTOM ui.Spacer(width=3) ui.Triangle(alignment=triangle_alignment, width=10, height=10, style={"background_color": 0xFFFFFFFF}) ui.Spacer(width=7) else: ui.Spacer() def build_widget(self, model, item, column_id, level, expanded): with ui.VStack(): ui.Spacer(height=2.5) if level == 1: # Effect list level ui.Label(item._name) else: # Uniform list level with ui.HStack(width=500, spacing=5): if item._base_type == 1: self.create_bool_widget(item) elif item._base_type >= 2 and item._base_type <= 5: self.create_int_widget(item) elif item._base_type >= 6 and item._base_type <= 7: self.create_float_widget(item) else: return label = ui.Label(item._ui_label if item._ui_label else item._name) if item._ui_tooltip: label.set_tooltip(item._ui_tooltip) ui.Spacer(height=2.5) def create_bool_widget(self, uniform): if uniform._components != 1: return if uniform._ui_type == "combo": return ui.ComboBox(ComboListModel(uniform.model, ["False", "True"])) else: return ui.CheckBox(uniform.model) def create_int_widget(self, uniform): if uniform._components == 1: return self.create_int_widget_scalar(uniform) else: return self.create_int_widget_vector(uniform) def create_int_widget_scalar(self, uniform): if uniform._ui_type == "combo" or uniform._ui_type == "list" or uniform._ui_type == "radio": return ui.ComboBox(ComboListModel(uniform.model, uniform._ui_items)) if uniform._ui_type == "slider": return ui.IntSlider(uniform.model, min=int(uniform._ui_min), max=int(uniform._ui_max), step=int(uniform._ui_step)) elif uniform._ui_type == "drag": return ui.IntDrag(uniform.model, min=int(uniform._ui_min), max=int(uniform._ui_max)) else: return ui.IntField(uniform.model) def create_int_widget_vector(self, uniform): if uniform._ui_type == "drag": return ui.MultiIntDragField(uniform.model, min=int(uniform._ui_min), max=int(uniform._ui_max), h_spacing=2) else: return ui.MultiIntField(uniform.model, h_spacing=2) def create_float_widget(self, uniform): if uniform._components == 1: return self.create_float_widget_scalar(uniform) else: return self.create_float_widget_vector(uniform) def create_float_widget_scalar(self, uniform): if uniform._ui_type == "slider": return ui.FloatSlider(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max), step=float(uniform._ui_step)) elif uniform._ui_type == "drag": return ui.FloatDrag(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max)) else: return ui.FloatField(uniform.model) def create_float_widget_vector(self, uniform): if uniform._ui_type == "drag": return ui.MultiFloatDragField(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max), h_spacing=2) elif uniform._ui_type == "color": with ui.HStack(spacing=2): widget = ui.MultiFloatDragField(uniform.model, min=float(uniform._ui_min), max=float(uniform._ui_max), h_spacing=2) ui.ColorWidget(uniform.model, width=0, height=0) return widget else: return ui.MultiFloatField(uniform.model, h_spacing=2) class ReshadeTechniqueModel(ui.AbstractValueModel): def __init__(self, handle, reshade_ctx): super().__init__() self._handle = handle self._reshade_ctx = reshade_ctx def get_value_as_bool(self) -> bool: return reshade.get_technique_enabled(self._reshade_ctx, self._handle) def set_value(self, value: bool): reshade.set_technique_enabled(self._reshade_ctx, self._handle, value) self._value_changed() class ReshadeTechniqueListItem(ui.AbstractItem): def __init__(self, handle, reshade_ctx): super().__init__() self._name = reshade.get_technique_name(handle) self._ui_label = reshade.get_technique_annotation_as_string(handle, "ui_label") self._ui_tooltip = reshade.get_technique_annotation_as_string(handle, "ui_tooltip") self.model = ReshadeTechniqueModel(handle, reshade_ctx) class ReshadeTechniqueEditorModel(ui.AbstractItemModel): def __init__(self, reshade_ctx): super().__init__() self._techniques = [ ReshadeTechniqueListItem(handle, reshade_ctx) for handle in reshade.get_technique_list(reshade_ctx) ] def get_item_children(self, item): if item is not None: return [] return self._techniques def get_item_value_model(self, item, column_id): if item is None: return None return item.model def get_item_value_model_count(self, item): return 1 class ReshadeTechniqueEditorDelegate(ui.AbstractItemDelegate): def build_branch(self, model, item, column_id, level, expanded): pass def build_widget(self, model, item, column_id, level, expanded): with ui.VStack(): ui.Spacer(height=2.5) with ui.HStack(width=0, height=0, spacing=5): ui.CheckBox(item.model) label = ui.Label(item._ui_label if item._ui_label else item._name) if item._ui_tooltip: label.set_tooltip(item._ui_tooltip) ui.Spacer(height=2.5) class ReshadeWindow: def __init__(self, on_visibility_changed_fn: Callable): self._window = ui.Window("ReShade", width=500, height=500) self._window.set_visibility_changed_fn(on_visibility_changed_fn) self._reshade_ctx = None try: from omni.kit.viewport.utility import get_active_viewport viewport = get_active_viewport() self._reshade_ctx = reshade.get_context(viewport.usd_context_name) except (ImportError, AttributeError): pass if self._reshade_ctx is None: with self._window.frame: with ui.VStack(): ui.Spacer() ui.Label("ReShade context not available", alignment=ui.Alignment.CENTER, style={"font_size": 48}) ui.Spacer() import carb carb.log_error(f"ReShade context not available for Viewport {viewport}") return self._update_sub = reshade.subscribe_to_update_events(self._reshade_ctx, self._on_update) self._build_ui() def destroy(self): self._window = None self._update_sub = None def _build_ui(self): reshade_ctx = self._reshade_ctx self._tmodel = ReshadeTechniqueEditorModel(reshade_ctx) self._tdelegate = ReshadeTechniqueEditorDelegate() self._vmodel = ReshadeVariableEditorModel(reshade_ctx) self._vdelegate = ReshadeVariableEditorDelegate() with self._window.frame: with ui.VStack(height=0, spacing=5): self._tview = ui.TreeView( self._tmodel, delegate=self._tdelegate, root_visible=False, header_visible=False) ui.Line() self._vview = ui.TreeView( self._vmodel, delegate=self._vdelegate, root_visible=False, header_visible=False, expand_on_branch_click=True) def _on_update(self): self._build_ui()
13,948
Python
38.854286
159
0.610984
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.ext import omni.kit.ui from .reshade_window import ReshadeWindow MENU_PATH = "Window/ReShade Editor" class ReshadeWindowExtension(omni.ext.IExt): def on_startup(self): self._window = None try: self._menu = omni.kit.ui.get_editor_menu().add_item( MENU_PATH, lambda m, v: self.show_window(v), toggle=True, value=False ) except: pass def on_shutdown(self): self._menu = None def show_window(self, value): if value: def on_visibility_changed(visible): omni.kit.ui.get_editor_menu().set_value(MENU_PATH, visible) self._window = ReshadeWindow(on_visibility_changed if self._menu else None) else: if self._window: self._window.destroy() self._window = None
1,291
Python
32.128204
87
0.654531
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/__init__.py
from .extension import ReshadeWindowExtension
46
Python
22.499989
45
0.891304
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/tests/__init__.py
from .test_extension import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.window.reshade_editor/omni/kit/window/reshade_editor/tests/test_extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.kit.test import pathlib import carb import omni.usd import omni.kit.app from omni.kit.test import AsyncTestCase from omni.kit.window.reshade_editor.reshade_window import ReshadeWindow EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) TESTS_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") class TestReshadeEditor(AsyncTestCase): async def setUp(self): super().setUp() await omni.usd.get_context().new_stage_async() settings = carb.settings.get_settings() settings.set("/rtx/reshade/enable", "true") settings.set("/rtx/reshade/presetFilePath", f"{TESTS_PATH}/preset.ini") settings.set("/rtx/reshade/effectSearchDirPath", f"{TESTS_PATH}") # Update app a few times for effects to load and compile for i in range(20): await omni.kit.app.get_app().next_update_async() async def test_variable_list(self): w = ReshadeWindow(None) self.assertIsNotNone(w._window) effects = w._vmodel.get_item_children(None) self.assertIsNotNone(effects) self.assertTrue(len(effects) == 1) # data/tests/simple.fx variables = w._vmodel.get_item_children(effects[0]) self.assertIsNotNone(effects) self.assertTrue(len(variables) == 1) # "fill_color" in data/tests/simple.fx async def test_technique_list(self): w = ReshadeWindow(None) self.assertIsNotNone(w._window) techniques = w._tmodel.get_item_children(None) self.assertIsNotNone(techniques) self.assertTrue(len(techniques) == 1) # technique "simple" in data/tests/simple.fx
2,119
Python
40.568627
123
0.706937
omniverse-code/kit/exts/omni.kit.window.reshade_editor/docs/CHANGELOG.md
# Changelog ## [0.1.1] - 2022-05-23 ### Changed - Support new Viewport API - Add dependency on omni.kit.viewport.utility
122
Markdown
16.571426
45
0.696721
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/style.py
__all__ = ["HOTKEYS_WINDOW_STYLE", "FILTER_WINDOW_STYLE", "WARNING_WINDOW_STYLE", "WINDOW_PICK_STYLE", "CONTEXT_MENU_STYLE"] from pathlib import Path import omni.ui as ui from omni.ui import color as cl # OM-63810: Happens in Create only which has different font from Kit. # Must set height to big enough for Add Actions button VIEW_ROW_HEIGHT = 28 CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("icons") """Style colors""" # https://confluence.nvidia.com/pages/viewpage.action?pageId=1218553472&preview=/1218553472/1359943485/image2022-6-7_13-20-4.png cl.hotkey_edit_icon = cl.shade(cl('#9E9E9E')) cl.hotkey_hint = cl.shade(cl('#5A5A5A')) cl.hotkey_warning = cl.shade(cl('#DFCB4A')) cl.hotkey_text_active = cl.shade(cl('#CCCCCC')) cl.hotkey_text_user = cl.shade(cl('#F2F2F2')) HOTKEYS_WINDOW_STYLE = { "TreeView.Item:selected": {"color": 0xFF8A8777}, "ActionsView.Window.Text": {"color": cl.actions_text, "margin": 4}, "ActionsView.Item.Text::warning": {"color": cl.hotkey_warning}, "Button.Background": {"background_color": 0x0}, "Button::add": {"background_color": cl.actions_background, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "border_radius": 4}, "Button::add:hovered": {"background_color": cl.actions_background_hovered}, "Button.Label::add": {"alignment": ui.Alignment.LEFT, "color": cl.actions_text}, "Button.Image::add": {"image_url": f"{ICON_PATH}/add.svg", "color": 0xFF5E6C5F, "alignment": ui.Alignment.LEFT}, "ComboBox": { "color": cl.actions_text, "secondary_color": cl.actions_background, "border_radius": 4, "margin": 1 }, "Image": {"border_radius": 4}, "Field": {"border_radius": 4, "margin": 1}, "Image::delete": {"image_url": f"{ICON_PATH}/delete.svg", "color": cl.hotkey_edit_icon}, "Image::edit": {"image_url": f"{ICON_PATH}/edit.svg", "color": cl.hotkey_edit_icon}, "Image::cancel": {"image_url": f"{ICON_PATH}/cancel.svg", "color": cl.hotkey_edit_icon}, "Image::save": {"image_url": f"{ICON_PATH}/save.svg", "color": cl.hotkey_edit_icon}, "Image::remove": {"image_url": f"{ICON_PATH}/remove.svg", "margin": 4}, "Image::remove:hovered": {"image_url": f"{ICON_PATH}/remove-hovered.svg"}, "DropDownArrow.background": {"border_radius": 4, "background_color": cl.actions_background, "margin_height": 1.5}, "DropDownArrow": {"background_color": cl.hotkey_edit_icon, "margin": 4, "border_radius": 4}, "Action.Input": {"color": cl.actions_text, "margin": 4}, "Action.Input::hint": {"color": cl.hotkey_hint}, "TriggerPressOption": { "background_color": 0x0, "margin_width": 2, "padding": 1, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "spacing": 10 }, "TriggerPressOption.Label": { "alignment": ui.Alignment.LEFT, }, "TriggerPressOption.Image": { "image_url": f"{ICON_PATH}/radio_off.svg", }, "TriggerPressOption.Image:checked": { "image_url": f"{ICON_PATH}/radio_on.svg" }, "TriggerPressOption.Background": {"background_color": 0x0}, "TriggerPressOption.Background:hovered": {"background_color": cl.hotkey_background_hovered}, "ResetButton.Invalid": {"background_color": 0xFF505050, "border_radius": 2}, "ResetButton": {"background_color": 0xFFA07D4F, "border_radius": 2}, "SearchBar.Filter": { "image_url": f"{ICON_PATH}/filter.svg", "margin": 4, }, "SearchBar.Options": { "image_url": f"{ICON_PATH}/settings.svg", "color": cl.hotkey_edit_icon, "margin": 5, }, } FILTER_WINDOW_STYLE = { "Window": {"padding": 0, "margin": 0}, "Titlebar.Background": {"background_color": cl.actions_background}, "Titlebar.Title": {"color": cl.actions_text}, "Titlebar.Reset": {"background_color": 0}, "Titlebar.Reset.Label": {"color": 0xFFB0703B}, "CheckBox": {"background_color": cl.actions_text, "color": cl.actions_background}, "FilterFlag.Text": {"color": cl.actions_text}, } WARNING_WINDOW_STYLE = { "Window": {"secondary_background_color": 0x0}, "Titlebar.Background": {"background_color": cl.actions_background}, "Titlebar.Title": {"color": cl.actions_text}, "Titlebar.Image": {"image_url": f"{ICON_PATH}/warning.svg"}, "Warning.Text": {"color": cl.actions_text}, "Warning.Text::highlight": {"color": cl.hotkey_text_active}, "Warning.Button": {"background_color": cl.actions_background}, "Warning.Button.Label": {"color": cl.hotkey_text_active}, } WINDOW_PICK_STYLE = { "TreeView.Item": { "color": cl.actions_text, "margin": 4 }, "TreeView.Item:selected": { "color": cl.actions_background }, } CONTEXT_MENU_STYLE = { "MenuItem": {"color": cl.actions_text}, } HIGHLIGHT_LABEL_STYLE = { "HStack": {"margin": 4}, "Label": {"color": cl.actions_text}, "Label:selected": {"color": cl.actions_background}, } HIGHLIGHT_LABEL_STYLE_USER = { "HStack": {"margin": 4}, "Label": {"color": cl.hotkey_text_user}, "Label:selected": {"color": cl.actions_background}, }
5,170
Python
39.085271
130
0.635783
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/extension.py
# pylint: disable=attribute-defined-outside-init __all__ = ["HotkeysExtension"] from functools import partial import carb.settings import omni.ext import omni.ui as ui import omni.kit.ui from .window.hotkeys_window import HotkeysWindow SETTING_SHOW_STARTUP = "/exts/omni.kit.hotkeys.window/showStartup" class HotkeysExtension(omni.ext.IExt): WINDOW_NAME = "Hotkeys" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): self._window = None ui.Workspace.set_show_window_fn( HotkeysExtension.WINDOW_NAME, partial(self.show_window, HotkeysExtension.MENU_PATH), ) show_startup = carb.settings.get_settings().get(SETTING_SHOW_STARTUP) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(HotkeysExtension.MENU_PATH, self.show_window, toggle=True, value=show_startup) if show_startup: ui.Workspace.show_window(HotkeysExtension.WINDOW_NAME) def on_shutdown(self): ui.Workspace.set_show_window_fn(HotkeysExtension.WINDOW_NAME, None) if self._window: self._window.destroy() self._window = None def show_window(self, menu_path: str, visible: bool): if visible: self._window = HotkeysWindow(HotkeysExtension.WINDOW_NAME) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False def _set_menu(self, checked: bool): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(HotkeysExtension.MENU_PATH, checked) def _visiblity_changed_fn(self, visible): self._set_menu(visible) if self._window and not visible: self._window.stop_key_capture()
1,908
Python
32.491228
124
0.653564
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/view/hotkeys_view.py
# pylint: disable=relative-beyond-top-level __all__ = ["HotkeysView"] import asyncio from omni.kit.actions.window import ActionsView import omni.ui as ui import omni.kit.app from ..model.hotkeys_model import HotkeysModel from .hotkeys_delegate import HotkeysDelegate class HotkeysView(ActionsView): def __init__(self, model: HotkeysModel, delegate: HotkeysDelegate): self.__delegate = delegate super().__init__(model, delegate) self.model.add_item_changed_fn(self.__model_changed) self.set_selection_changed_fn(self.__delegate.on_selection_changed) self.set_hover_changed_fn(self.__delegate.on_hover_changed) def __model_changed(self, model: HotkeysModel, item: ui.AbstractItem): if model.next_select_hotkey: # Select expect item async def __force_select_hotkey_async(select_hotkey): await omni.kit.app.get_app().next_update_async() for ext_item in self.model.get_item_children(None): for hotkey_item in self.model.get_item_children(ext_item): if hotkey_item.hotkey == select_hotkey: self.set_expanded(ext_item, True, True) self.selection = [hotkey_item] # pylint: disable=attribute-defined-outside-init return (saved_select_hotkey, model.next_select_hotkey) = (model.next_select_hotkey, None) asyncio.ensure_future(__force_select_hotkey_async(saved_select_hotkey)) if model.search_done: # Auto expand on searching async def __force_expand_async(): await omni.kit.app.get_app().next_update_async() self.set_expanded(None, True, True) model.search_done = False asyncio.ensure_future(__force_expand_async())
1,870
Python
42.511627
108
0.62246
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/view/hotkeys_delegate.py
# pylint: disable=relative-beyond-top-level __all__ = ["HotkeysDelegate"] from typing import List from omni.kit.actions.window import ActionsDelegate, AbstractColumnDelegate import omni.ui as ui from ..model.hotkey_item import EmptyFilterWindowItem, AddWindowItem, ActionExtItem from ..style import VIEW_ROW_HEIGHT class HotkeysDelegate(ActionsDelegate): def build_branch( self, model: ui.AbstractItemModel, item: ui.AbstractItem, column_id: int = 0, level: int = 0, expanded: bool = False ): if isinstance(item, AddWindowItem): return if isinstance(item, EmptyFilterWindowItem): return if model.can_item_have_children(item): super().build_branch(model, item, column_id, level, expanded) else: if column_id == 0 and isinstance(item, ActionExtItem): # Show background rectangle here when no sub hotkeys found for search/filter # Otherwise here will be blank but name with background next with ui.VStack(height=VIEW_ROW_HEIGHT): ui.Spacer() ui.Rectangle(width=20, height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() else: super().build_branch(model, item, column_id, level, expanded) def on_mouse_double_click(self, button: int, item: ui.AbstractItem, column_delegate: AbstractColumnDelegate): # No execute when double click pass def on_mouse_pressed(self, button: int, item: ui.AbstractItem, column_delegate: AbstractColumnDelegate): # No context menu pass def on_selection_changed(self, selections: List[ui.AbstractItem]): for i in range(self._column_registry.max_column_id + 1): delegate = self._column_registry.get_delegate(i) if delegate and hasattr(delegate, "on_selection_changed"): delegate.on_selection_changed(selections) def on_hover_changed(self, item, hovered) -> None: for i in range(self._column_registry.max_column_id + 1): delegate = self._column_registry.get_delegate(i) if delegate and hasattr(delegate, "on_hover_changed"): delegate.on_hover_changed(item, hovered)
2,333
Python
39.947368
113
0.638234
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/window/warning_window.py
# pylint: disable=relative-beyond-top-level, attribute-defined-outside-init __all__ = ["WarningMessage", "WarningWindow"] from dataclasses import dataclass from typing import List, Tuple, Callable, Union, Optional import omni.ui as ui from ..style import WARNING_WINDOW_STYLE @dataclass class WarningMessage: message: str highlight: bool = False class WarningWindow(ui.Window): r""" Window Show warning message. Args: title (str): Warning title. messages (List[Union[str, WarningMessage]]): Message list. Use a single '\n' for a new line. buttons (List[Tuple[str, Callable[[None], None]]): Button list. Default 'OK' to close. width (ui.Length): Window width. Default 360 pixels. button_width (ui.Length): Width of a single button. Default 60 pixels. visible (bool): Visible after created. Default True. """ PADDING = 4 def __init__( self, title: str, messages: Optional[List[Union[str, WarningMessage]]] = None, buttons: Optional[List[Tuple[str, Callable[[None], None]]]] = None, width: ui.Length = 360, button_width=60, visible=True ): self.__title = title self.__messages = messages if messages else [] self.__buttons = buttons if buttons else [] self.__button_width = button_width self.__width = width flags = ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_MODAL super().__init__(f"###Hotkey_WARNING_{title}", width=width, visible=visible, flags=flags, auto_resize=True, padding_x=0, padding_y=0) self.frame.set_style(WARNING_WINDOW_STYLE) self.frame.set_build_fn(self.__build_ui) def __del__(self): self.destroy() def __build_ui(self): with self.frame: with ui.VStack(width=self.__width, height=0): self._build_titlebar() ui.Spacer(height=15) self._build_message() ui.Spacer(height=15) self._build_buttons() ui.Spacer(height=15) def _build_titlebar(self): with ui.ZStack(height=0): ui.Rectangle(style_tyle_name_override="Titlebar.Background") with ui.VStack(): ui.Spacer(height=self.PADDING) with ui.HStack(): ui.Spacer(width=self.PADDING) ui.Image(width=16, style_type_name_override="Titlebar.Image") ui.Spacer(width=8) ui.Label(self.__title, width=0, style_tyle_name_override="Titlebar.Title") ui.Spacer(width=self.PADDING) ui.Spacer(height=self.PADDING) def _build_message(self): message_lines = [] message_lines.append([]) for message in self.__messages: if isinstance(message, str): if message == "\n": message_lines.append([]) message_lines[len(message_lines) - 1].append(WarningMessage(message)) elif isinstance(message, WarningMessage): message_lines[len(message_lines) - 1].append(message) with ui.VStack(spacing=6, height=0): for messages in message_lines: with ui.HStack(): ui.Spacer(width=self.PADDING) ui.Spacer() for message in messages: ui.Label( message.message, width=0, alignment=ui.Alignment.CENTER, style_type_name_override="Warning.Text", name="highlight" if message.highlight else "" ) ui.Spacer() ui.Spacer(width=self.PADDING) def _build_buttons(self): if self.__buttons: with ui.HStack(): ui.Spacer() for index, button in enumerate(self.__buttons): if index > 0: ui.Spacer(width=20) ui.Button(button[0], width=self.__button_width, clicked_fn=lambda fn=button[1]: self.__on_button_click(fn), style_type_name_override="Warning.Button") ui.Spacer(width=self.PADDING) else: with ui.HStack(): ui.Spacer() ui.Button("OK", width=self.__button_width, clicked_fn=self.__on_button_click, style_type_name_override="Warning.Button") ui.Spacer(width=self.PADDING) def __on_button_click(self, clicked_fn: Callable[[None], bool] = None) -> None: keep_open = False if clicked_fn: keep_open = clicked_fn() if not keep_open: self.visible = False
4,854
Python
37.84
170
0.550474
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/window/hotkeys_window.py
# pylint: disable=unused-private-member, relative-beyond-top-level, attribute-defined-outside-init __all__ = ["HotkeysWindow"] from typing import Optional from omni.kit.actions.window import ColumnRegistry, ACTIONS_WINDOW_STYLE import omni.ui as ui from ..model.hotkeys_model import HotkeysModel from ..column_delegate.hotkey_column_delegate import HotkeyColumnDelegate from ..column_delegate.action_column_delegate import ActionColumnDelegate from ..column_delegate.window_column_delegate import WindowColumnDelegate from ..view.hotkeys_view import HotkeysView from ..view.hotkeys_delegate import HotkeysDelegate from ..style import HOTKEYS_WINDOW_STYLE from .search_bar import SearchBar class HotkeysWindow(ui.Window): def __init__(self, title): super().__init__(title, width=1000, height=600) self._hotkeys_model: Optional[HotkeysModel] = None self.__hotkey_column_delegate: Optional[HotkeyColumnDelegate] = None self._search_bar: Optional[SearchBar] = None self._column_registry: Optional[ColumnRegistry] = None self._hotkeys_view: Optional[HotkeysView] = None self._actions_delegate: Optional[HotkeysDelegate] = None self.__sub_model = None style = ACTIONS_WINDOW_STYLE.copy() style.update(HOTKEYS_WINDOW_STYLE) self.frame.set_style(style) self.frame.set_build_fn(self._build_ui) def destroy(self): self.visible = False self.__sub_model = None if self.__hotkey_column_delegate: self.__hotkey_column_delegate.destroy() if self._hotkeys_model: self._hotkeys_model.destroy() self._hotkeys_model = None super().destroy() def stop_key_capture(self): if self.__hotkey_column_delegate: self.__hotkey_column_delegate.stop_key_capture() def _build_ui(self): self.__hotkey_column_delegate = HotkeyColumnDelegate("Hotkey") self._column_registry = ColumnRegistry() self._column_registry.register_delegate(WindowColumnDelegate("Window", width=200)) self._column_registry.register_delegate(ActionColumnDelegate("Action", width=400)) self._column_registry.register_delegate(self.__hotkey_column_delegate) self._hotkeys_model = HotkeysModel(self._column_registry) self._actions_delegate = HotkeysDelegate(self._hotkeys_model, self._column_registry) self.__sub_model = self._hotkeys_model.subscribe_item_changed_fn(self.__on_model_changed) with self.frame: with ui.VStack(spacing=4): self._search_bar = SearchBar(self._hotkeys_model) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="ActionsView", ): self._hotkeys_view = HotkeysView(self._hotkeys_model, self._actions_delegate) def __on_model_changed(self, model: HotkeysModel, item: ui.AbstractItem) -> None: if self.__hotkey_column_delegate: # Here need to clean key capture since the whole tree view is refreshed self.__hotkey_column_delegate.stop_key_capture()
3,307
Python
43.106666
98
0.677653
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/window/windows_picker.py
# pylint: disable=relative-beyond-top-level __all__ = ["WindowsPicker"] from typing import List, Callable, Optional import omni.ui as ui from omni.kit.actions.window import ACTIONS_WINDOW_STYLE from ..model.windows_model import WindowsModel, WindowItem from ..style import WINDOW_PICK_STYLE class WindowsPicker(ui.Window): def __init__( self, width=0, height=600, on_selected_fn: Callable[[str], None] = None, expand_all: bool = True, focus_search: bool = True, ): super().__init__("###WINDOW_PICKER", width=width, height=height) self.flags = ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_POPUP self.__on_selected_fn = on_selected_fn self.__expand_all = expand_all self.__focus_search = focus_search self._actions_view: Optional[ui.TreeView] = None self._search_field = None self._windows_model: Optional[WindowsModel] = None style = ACTIONS_WINDOW_STYLE.copy() style.update(WINDOW_PICK_STYLE) self.frame.set_style(style) self.frame.set_build_fn(self._build_ui) def _build_ui(self): self._windows_model = WindowsModel("") with self.frame: with ui.VStack(spacing=4): try: from omni.kit.widget.searchfield import SearchField self._search_field = SearchField( on_search_fn=self._on_search, subscribe_edit_changed=True, style=ACTIONS_WINDOW_STYLE, ) except ImportError: self._search_field = None with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="ActionsView", ): self._actions_view = ui.TreeView( self._windows_model, root_visible=False, header_visible=False, ) self._actions_view.set_selection_changed_fn(self._on_selection_changed) if self.__expand_all: self._actions_view.set_expanded(None, True, True) if self.__focus_search and self._search_field: self._search_field._search_field.focus_keyboard() # pylint: disable=protected-access def _on_search(self, search_words: Optional[List[str]]) -> None: self._windows_model.search(search_words) # Auto expand on searching self._actions_view.set_expanded(None, True, True) def _on_selection_changed(self, selections: List[WindowItem]): for item in selections: if isinstance(item, WindowItem) and self.__on_selected_fn: self.__on_selected_fn(item.window_title)
2,943
Python
39.888888
127
0.594631
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/window/options_menu.py
# pylint: disable=relative-beyond-top-level __all__ = ["OptionsMenu"] from typing import Optional, Callable import carb import omni.ui as ui import omni.client from omni.kit.notification_manager import post_notification, NotificationStatus from omni.kit.hotkeys.core import get_hotkey_registry, KeyboardLayoutDelegate from .warning_window import WarningWindow from ..model.hotkeys_model import HotkeysModel class LayoutMenu(ui.MenuItemCollection): def __init__(self): super().__init__("Keyboard Layouts") self.__build_layout_items() def __build_layout_items(self): current_layout = get_hotkey_registry().keyboard_layout with self: for layout in KeyboardLayoutDelegate.get_instances(): name = layout.get_name() checked = current_layout == layout menu_item = ui.MenuItem( name, checkable=True, checked=checked, ) menu_item.set_triggered_fn(lambda m=menu_item, n=name: self.__switch_keyboard_layput(m, n)) def __switch_keyboard_layput(self, menu_item: ui.MenuItem, name: str) -> None: get_hotkey_registry().switch_layout(name) menu_item.checked = True class OptionsMenu: def __init__(self, model: HotkeysModel, widget: ui.Widget): self.__model = model self.__widget = widget self.__context_menu: Optional[ui.Menu] = None self.__last_dir: Optional[str] = None self.__export_dialog = None self.__import_dialog = None def show(self): if self.__context_menu is None: self.__context_menu = ui.Menu(f"Hotkeys window Context Menu##{hash(self)}") with self.__context_menu: ui.MenuItem("Import Preset", triggered_fn=self.__import_preset) ui.MenuItem("Export Preset", triggered_fn=self.__export_preset) ui.MenuItem("Restore Defaults", triggered_fn=self.__restore_defaults) LayoutMenu() # Right-bottom allign to the widget # 120 is the menu width position_x = self.__widget.screen_position_x + self.__widget.computed_width - 120 position_y = self.__widget.screen_position_y + self.__widget.computed_height self.__context_menu.show_at(position_x, position_y) def __import_preset(self): try: import omni.kit.window.filepicker # pylint: disable=redefined-outer-name self.__import_dialog = omni.kit.window.filepicker.FilePickerDialog( "Import", apply_button_label="import", current_directory=self.__last_dir, click_apply_handler=self.__on_import, item_filter_options=["Hotkey preset file (*.json)", "All Files (*)"], # item_filter_fn=self.__on_filter_item, ) except ImportError: carb.log_info("Failed to import omni.kit.window.filepicker") def __export_preset(self): try: import omni.kit.window.filepicker # pylint: disable=redefined-outer-name self.__export_dialog = omni.kit.window.filepicker.FilePickerDialog( "Export As", apply_button_label="Export", current_directory=self.__last_dir, click_apply_handler=self.__on_export, item_filter_options=["Hotkey preset file (*.json)", "All Files (*)"], # item_filter_fn=self.__on_filter_item, ) except ImportError: carb.log_info("Failed to import omni.kit.window.filepicker") def __on_export(self, filename: str, path: str, callback: Callable[[str], None] = None): """Called when the user presses the Save button in the dialog""" if path: self.__last_dir = path if not filename: return # Get the file extension from the filter if not filename.lower().endswith(".json") and self.__export_dialog.current_filter_option < 1: filename += ".json" if path: path = omni.client.combine_urls(path + "/", filename) else: path = filename self.__export_dialog.hide() # check dest file (result, list_entry) = omni.client.stat(path) if result == omni.client.Result.OK and not list_entry.access & omni.client.AccessFlags.WRITE: post_notification( f"Hotkey preset '{path}' is readonly, save to another one!", hide_after_timeout=True, status=NotificationStatus.WARNING, ) return self.__export(path) def __export(self, url: str) -> None: get_hotkey_registry().export_storage(url) def __on_import(self, filename: str, path: str, callback: Callable[[str], None] = None): """Called when the user presses the Save button in the dialog""" self.__last_dir = path if not filename: return # Get the file extension from the filter if not filename.lower().endswith(".json") and self.__import_dialog.current_filter_option < 1: filename += ".json" url = omni.client.combine_urls(path + "/", filename) self.__import_dialog.hide() # check dest file (result, _) = omni.client.stat(url) if result != omni.client.Result.OK: post_notification( f"Hotkey preset '{url}' does not exists!", hide_after_timeout=True, status=NotificationStatus.WARNING, ) return self.__import(url) def __import(self, url: str) -> None: get_hotkey_registry().import_storage(url) self.__model._item_changed(None) # pylint: disable=protected-access def __restore_defaults(self) -> None: def __restore(): get_hotkey_registry().restore_defaults() self.__model._item_changed(None) # pylint: disable=protected-access warn_window = WarningWindow( "Restore Defaults", messages=[ "Are you sure you want to restore all hotkeys to their defaults?", "\n", "This will also remove any user added hotkeys.", ], buttons=[ ("Yes", __restore), ("No", None) ] ) warn_window.position_x = self.__widget.screen_position_x + self.__widget.computed_width - warn_window.width warn_window.position_y = self.__widget.screen_position_y + self.__widget.computed_height
6,657
Python
37.045714
115
0.579991
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/window/search_bar.py
# pylint: disable=relative-beyond-top-level __all__ = ["SearchBar"] from typing import Optional, List import omni.ui as ui from omni.kit.actions.window import ACTIONS_WINDOW_STYLE from omni.kit.widget.filter import FilterButton from ..model.hotkeys_model import HotkeysModel from .options_menu import OptionsMenu class SearchBar: """ Search bar, includes a search field and a filter button. Args: model (HotkeysModel): Hotkeys model. """ def __init__(self, model: HotkeysModel): self.__model = model self.__container: Optional[ui.HStack] = None self.__filter_button: Optional[FilterButton] = None self.__options_menu: Optional[OptionsMenu] = None self.__build_ui() def destroy(self): if self.__filter_button: self.__filter_button.destroy() self.__filter_button = None @property def visible(self) -> bool: return self.__container.visible if self.__container else False @visible.setter def visible(self, value) -> None: if self.__container: self.__container.visible = False def __build_ui(self): try: from omni.kit.widget.searchfield import SearchField self.__container = ui.HStack(height=0) with self.__container: self._search_field = SearchField( on_search_fn=self.__on_search, subscribe_edit_changed=True, style=ACTIONS_WINDOW_STYLE, show_tokens=False, ) self.__filter_button = FilterButton(self.__model.search_filter_flags, width=26, height=26) with ui.VStack(width=26): self.__options_image = ui.ImageWithProvider( width=26, height=26, mouse_pressed_fn=lambda x, y, b, f: self.__show_options(), style_type_name_override="SearchBar.Options", ) ui.Spacer() except ImportError: self._search_field = None def __on_search(self, search_words: Optional[List[str]]) -> None: self.__model.search(search_words) def __show_options(self): if self.__options_menu is None: self.__options_menu = OptionsMenu(self.__model, self.__options_image) self.__options_menu.show()
2,432
Python
32.328767
106
0.571957
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/column_delegate/key_editor.py
# pylint: disable=attribute-defined-outside-init, unused-private-member, relative-beyond-top-level __all__ = ["TriggerPressOption", "TriggerPressWindow", "KeyEditor"] import asyncio from typing import Optional, Union, Callable import carb import carb.input import omni.kit.app import omni.ui as ui from omni.kit.hotkeys.core import Hotkey, HotkeyRegistry, KeyCombination, get_hotkey_registry from ..model.hotkey_item import HotkeyDetailItem, EmptyHotkeyItem from ..model.hotkeys_model import HotkeysModel from ..window.warning_window import WarningWindow, WarningMessage from ..style import HOTKEYS_WINDOW_STYLE _key_capture_instances = 0 class TriggerPressOption: def __init__(self, collection: ui.RadioCollection, text): with ui.ZStack(width=0): ui.Rectangle(style_type_name_override="TriggerPressOption.Background") ui.RadioButton( text=text, radio_collection=collection, width=100, height=24, image_width=14, spacing=4, alignment=ui.Alignment.LEFT, style_type_name_override="TriggerPressOption", ) class TriggerPressWindow(ui.Window): PADDING = 4 def __init__(self, model: ui.SimpleIntModel): self.__model = model flags = ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_POPUP super().__init__("Hotkey Trigger", flags=flags, auto_resize=True) self.frame.set_style(HOTKEYS_WINDOW_STYLE) self.frame.set_build_fn(self.__build_ui) def destroy(self): self.__sub = None def __del__(self): self.destroy() def __build_ui(self): collection = ui.RadioCollection(self.__model) with self.frame: with ui.VStack(style={"padding": self.PADDING}): TriggerPressOption(collection, "On Press") TriggerPressOption(collection, "On Release") self.__sub = collection.model.add_value_changed_fn(self.__on_value_changed) def __on_value_changed(self, model: ui.AbstractValueModel): self.visible = False class KeyEditor: def __init__( self, model: HotkeysModel, item: Union[HotkeyDetailItem, EmptyHotkeyItem], visible: bool = True, on_edit_cancelled_fn: Callable[[str], None] = None ): self.__model = model self.__item = item self.__on_edit_cancelled_fn = on_edit_cancelled_fn self.__key_text_model = ui.SimpleStringModel(item.hotkey.key_text if item.hotkey else "") self.__key_press_model = ui.SimpleIntModel(0 if item.hotkey.key_combination.trigger_press else 1) self.__sub_key_text = self.__key_text_model.add_value_changed_fn(self.__on_key_text_changed) self.__trigger_window: Optional[TriggerPressWindow] = None self.__input_field: Optional[ui.StringField] = None self.__input_hint: Optional[ui.Label] = None self.__remove_container: Optional[ui.HStack] = None self.__input = carb.input.acquire_input_interface() self.__input_sub_id = None self.__build_ui(visible) def __del__(self): self.visible = False def __build_ui(self, visible): # Double click to clean the key input to empty self.__container = ui.HStack(visible=visible) with self.__container: ui.Spacer(width=4) with ui.ZStack(width=ui.Fraction(1)): self.__input_field = ui.StringField(self.__key_text_model, enabled=False) self.__input_hint = ui.Label("Begin Typing to Capture Key Bindings", name="hint", style_type_name_override="Action.Input") self.__remove_container = ui.HStack() with self.__remove_container: ui.Spacer() ui.Image(name="remove", width=20, mouse_released_fn=lambda x, y, b, f: self.__key_text_model.set_value("")) ui.Spacer(width=4) ui.Spacer(width=8) ui.Image(name="cancel", width=20, mouse_released_fn=lambda x, y, b, f: self.__hide()) ui.Spacer(width=4) ui.Image(name="save", width=20, mouse_released_fn=lambda x, y, b, f: self.__save()) ui.Spacer(width=4) with ui.ZStack(width=0): ui.Rectangle(style_type_name_override="DropDownArrow.background") with ui.VStack(width=0): ui.Spacer() self.__arrow = ui.Triangle( width=20, height=16, alignment=ui.Alignment.CENTER_BOTTOM, style_type_name_override="DropDownArrow", mouse_released_fn=lambda x, y, b, f: self.__edit_press() ) ui.Spacer() ui.Spacer(width=1) if visible: carb.log_info(f"[Hotkey Editor] Show editor for {self.__item}") self.__start_key_capture() self.__on_key_text_changed(self.__key_text_model) @property def visible(self) -> bool: return self.__container.visible @visible.setter def visible(self, value: bool) -> None: self.__container.visible = value self.__sub_key_text = False carb.log_info(f"[Hotkey Editor] Visible change to {value} for {self.__item}") if value: # Default to capture keyboard for key input self.__key_text_model.set_value(self.__item.hotkey.key_text if self.__item.hotkey else "") self.__start_key_capture() else: self.__stop_key_capture() def __start_key_capture(self): global _key_capture_instances _key_capture_instances += 1 carb.log_info(f"[Hotkey Editor] [{_key_capture_instances}] Start key capture for {self.__item}") self.__input_sub_id = self.__input.subscribe_to_input_events(self._on_input_event, order=-100000) def __stop_key_capture(self): if self.__input_sub_id is not None: global _key_capture_instances _key_capture_instances -= 1 carb.log_info(f"[Hotkey Editor] [{_key_capture_instances}] Stop key capture for {self.__item}") self.__input.unsubscribe_to_input_events(self.__input_sub_id) self.__input_sub_id = None def _on_input_event(self, event, *_): if event.deviceType == carb.input.DeviceType.KEYBOARD: is_down = event.event.type == carb.input.KeyboardEventType.KEY_PRESS if is_down: key_combination = KeyCombination(event.event.input, modifiers=event.event.modifiers) self.__key_text_model.set_value(key_combination.as_string) # Return False to block key input return False def __hide(self): carb.log_info("[Hotkey Editor] Cancel edit") self.visible = False if isinstance(self.__item, EmptyHotkeyItem): async def __clear_empty_async(): await omni.kit.app.get_app().next_update_async() self.__model.clear_empty_hotkey() asyncio.ensure_future(__clear_empty_async()) if self.__on_edit_cancelled_fn: self.__on_edit_cancelled_fn(self.__item.hotkey.key_text) def __save(self): try: result = self.__model.edit_hotkey_item( self.__item, key_text=self.__key_text_model.as_string, trigger_press=self.__key_press_model.as_int == 0 ) if result == HotkeyRegistry.Result.OK: carb.log_info(f"[Hotkey Editor] Save for {self.__item}") self.visible = False else: if result == HotkeyRegistry.Result.ERROR_NO_ACTION: warn_window = WarningWindow("Action required", ["Please select an action before saving hotkey!"]) elif result == HotkeyRegistry.Result.ERROR_KEY_INVALID: warn_window = WarningWindow("Key required", ["Please input a valid key binding before saving the hotkey!"]) elif result == HotkeyRegistry.Result.ERROR_KEY_DUPLICATED: key_combination = KeyCombination(self.__key_text_model.as_string, trigger_press=self.__item.hotkey.key_combination.trigger_press) duplicated_key = get_hotkey_registry().get_hotkey_for_filter(key_combination, self.__item.hotkey.filter) action_display = duplicated_key.action.display_name if duplicated_key.action else "Unknown Action" warn_window = WarningWindow( "Hotkey Conflict Warning", messages=[ WarningMessage(f"'{key_combination.id}'", highlight=True), WarningMessage(" is already assigned to "), WarningMessage(f"'{action_display}'", highlight=True), '\n', "Do you want to replace this exising hotkey with your new one?" ], buttons=[ ("Replace", lambda k=key_combination, n=self.__item, o=duplicated_key: self.__replace_key(k, n, o)), ("Cancel", None) ] ) elif result == HotkeyRegistry.Result.ERROR_ACTION_DUPLICATED: action_display = self.__item.action_display warn_window = WarningWindow( "Action Conflict Warning", messages=[ WarningMessage(f"'{action_display}'", highlight=True), WarningMessage(" is already defined."), ] ) else: warn_window = WarningWindow("Unkown Error", [f"Error code: {result}"]) warn_window.position_x = self.__container.screen_position_x + 4 warn_window.position_y = self.__container.screen_position_y + self.__container.computed_height + 4 except Exception as e: # pylint: disable=broad-except carb.log_error(f"Exception when save hotkey: {e}") def __edit_press(self): if self.__trigger_window is None: self.__trigger_window = TriggerPressWindow(self.__key_press_model) async def __update_position(): while self.__trigger_window.width < 10 or self.__trigger_window.width == 400: await omni.kit.app.get_app().next_update_async() self.__trigger_window.position_x = self.__arrow.screen_position_x + self.__arrow.computed_width - self.__trigger_window.width self.__trigger_window.position_y = self.__arrow.screen_position_y + self.__arrow.computed_height + 4 self.__trigger_window.visible = True asyncio.ensure_future(__update_position()) def __replace_key(self, key_combination: KeyCombination, item: HotkeyDetailItem, duplicated_key: Hotkey): carb.log_info(f"[Hotkey Editor] Replace hotkey for {self.__item}") self.visible = False self.__model.replace_item_key(key_combination, item, duplicated_key) def __on_key_text_changed(self, model: ui.SimpleStringModel) -> None: if self.__remove_container: self.__remove_container.visible = (model.as_string != "") if self.__input_hint: self.__input_hint.visible = (model.as_string == "")
11,587
Python
44.802371
149
0.579788
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/column_delegate/action_column_delegate.py
# pylint: disable=relative-beyond-top-level __all__ = ["ActionColumnDelegate"] import asyncio from typing import Optional from omni.kit.actions.window import AbstractActionItem, ActionExtItem, StringColumnDelegate, ActionsPicker from omni.kit.widget.highlight_label import HighlightLabel import omni.ui as ui import omni.kit.app from ..model.hotkeys_model import HotkeyDetailItem, HotkeysModel, EmptyHotkeyItem from ..model.hotkey_item import AbstractFilterItem, AddWindowItem, FilterContextItem, FilterWindowItem from ..window.warning_window import WarningWindow from ..style import HIGHLIGHT_LABEL_STYLE, HIGHLIGHT_LABEL_STYLE_USER class ActionColumnDelegate(StringColumnDelegate): """ A simple delegate to display/add action in column. Kwargs: name (str): Column name. width (ui.Length): Column width. Default ui.Fraction(1). """ def __init__(self, name: str, width: ui.Length = None): width = ui.Fraction(1) if width is None else width super().__init__(name, width=width) self.__actions_picker: Optional[ActionsPicker] = None self.__auto_show_picker = False def build_widget(self, model: HotkeysModel, item: AbstractActionItem, level: int, expand: bool): if isinstance(item, AddWindowItem): return None if isinstance(item, HotkeyDetailItem): if item.hotkey.action: label = HighlightLabel(item.hotkey.action.display_name, highlight=item.highlight, style=HIGHLIGHT_LABEL_STYLE_USER if item.user_defined else HIGHLIGHT_LABEL_STYLE) label.widget.set_tooltip(f"{item.hotkey.action_text}\n{item.hotkey.action.description}") return label.widget return ui.Label(item.hotkey.action_text, name="warning", style_type_name_override="ActionsView.Item.Text") if isinstance(item, ActionExtItem): container = ui.ZStack() with container: # Background rectangle with ui.VStack(): ui.Spacer() ui.Rectangle(height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() filter_type = "Global" if isinstance(item, FilterWindowItem): filter_type = "Window" elif isinstance(item, FilterContextItem): filter_type = "Context" button = ui.Button( f"Add New {filter_type} Hotkey", name="add", image_width=20, visible=True, ) button.set_clicked_fn(lambda m=model, i=item, b=button: self.__add_action(m, i, b)) return container if isinstance(item, EmptyHotkeyItem): container = ui.ZStack() with container: ui.Rectangle(style_type_name_override="DropDownArrow.background") with ui.HStack(): action_label = ui.Label("Select An Action", name="hint", style_type_name_override="Action.Input") with ui.VStack(width=0): ui.Spacer() ui.Triangle( width=20, height=16, alignment=ui.Alignment.CENTER_BOTTOM, style_type_name_override="DropDownArrow", ) ui.Spacer() container.set_mouse_released_fn(lambda x, y, b, f, m=model, c=container, l=action_label: self.__show_action_picker(m, c, l)) if self.__auto_show_picker: self.__show_action_picker(model, container, action_label) self.__auto_show_picker = False return container def __add_action(self, model: HotkeysModel, item: AbstractFilterItem, button: ui.Button): if isinstance(item, FilterContextItem): if not item.id: warn_window = WarningWindow("Context required", ["Please select a context first before adding new context hotkey!"]) warn_window.position_x = button.screen_position_x + 4 warn_window.position_y = button.screen_position_y return elif isinstance(item, FilterWindowItem) and not item.id: warn_window = WarningWindow("Window required", ["Please select a window first before adding new window hotkey!"]) warn_window.position_x = button.screen_position_x + 4 warn_window.position_y = button.screen_position_y return async def __add_action_async(): await omni.kit.app.get_app().next_update_async() self.__auto_show_picker = True model.add_empty_hotkey(item) asyncio.ensure_future(__add_action_async()) def __show_action_picker(self, model: HotkeysModel, container: ui.Stack, label: ui.Label) -> None: if self.__actions_picker is not None: if self.__actions_picker.visible: # Just hide actions picker if it already visible self.__actions_picker.visible = False return self.__actions_picker = None # Refresh actions list every time def __on_action_selected(action): item = model.save_empty_action(action) label.text = item.action_display label.name = "" self.__actions_picker.visible = False async def __update_position(): if container.computed_width == 0: await omni.kit.app.get_app().next_update_async() self.__actions_picker = ActionsPicker(width=container.computed_width, height=500, on_selected_fn=__on_action_selected) self.__actions_picker.visible = True self.__actions_picker.position_x = container.screen_position_x self.__actions_picker.position_y = container.screen_position_y + container.computed_height asyncio.ensure_future(__update_position())
6,038
Python
46.179687
179
0.601358
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/column_delegate/reset_button.py
__all__ = ["ResetHelper", "ResetButton"] import abc from typing import Callable, List import carb.settings import omni.ui as ui class ResetHelper: def __init__(self, reset_button=None): self._reset_button = None @abc.abstractmethod def can_reset(self) -> bool: return False @abc.abstractmethod def reset(self) -> bool: return True def set_reset_button(self, button: "ResetButton"): self._reset_button = button self._update_reset_button() def _update_reset_button(self): if self._reset_button is None: return self._reset_button.refresh() class ResetButton: def __init__(self, helpers: List[ResetHelper] = None, on_reset_fn: Callable[[None], None] = None): self._helpers = helpers if helpers else [] self._settings = carb.settings.get_settings() self._on_reset_fn = on_reset_fn self._build_ui() def add_setting_model(self, helper: ResetHelper): if helper not in self._helpers: self._helpers.append(helper) self.refresh() def refresh(self): visible = False for helper in self._helpers: if helper.can_reset(): visible = True break self._reset_button.visible = visible def _build_ui(self): with ui.HStack(width=0): ui.Spacer() with ui.VStack(width=0): ui.Spacer() with ui.ZStack(width=15, height=12): with ui.HStack(style={"margin_width": 0}): ui.Spacer() with ui.VStack(width=0): ui.Spacer() ui.Rectangle(width=5, height=5, style_type_name_override="ResetButton.Invalid") ui.Spacer() ui.Spacer() with ui.HStack(): ui.Spacer() self._reset_button = ui.Rectangle(width=12, height=12, style_type_name_override="ResetButton", tooltip="Click to reset value") ui.Spacer() self._reset_button.set_mouse_pressed_fn(lambda x, y, m, w: self._restore_defaults()) ui.Spacer() ui.Spacer() def _restore_defaults(self): for helper in self._helpers: if helper.can_reset() and not helper.reset(): return self._reset_button.visible = False if self._on_reset_fn: self._on_reset_fn()
2,559
Python
31.405063
150
0.533021
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/column_delegate/window_column_delegate.py
# pylint: disable=relative-beyond-top-level __all__ = ["WindowColumnDelegate"] import asyncio from typing import Optional from omni.kit.actions.window import AbstractActionItem, ActionExtItem, StringColumnDelegate from omni.kit.widget.highlight_label import HighlightLabel import omni.ui as ui import omni.kit.app from ..model.hotkeys_model import HotkeysModel, EmptyFilterWindowItem, AddWindowItem from ..window.windows_picker import WindowsPicker from ..style import VIEW_ROW_HEIGHT, HIGHLIGHT_LABEL_STYLE class WindowColumnDelegate(StringColumnDelegate): """ A simple delegate to display/add action in column. Kwargs: name (str): Column name. width (ui.Length): Column width. Default None means ui.Fraction(1). """ def __init__(self, name: str, width: Optional[ui.Length] = None): width = ui.Fraction(1) if width is None else width super().__init__(name, width=width) self.__windows_picker: Optional[WindowsPicker] = None self.__auto_show_picker = False def build_widget(self, model: HotkeysModel, item: AbstractActionItem, level: int, expand: bool): if isinstance(item, AddWindowItem): container = ui.ZStack(width=self._width) with container: # Background rectangle to keep get hovered when button invisible ui.Rectangle(height=26, style_type_name_override="Button.Background") def __add_window_filter(): self.__auto_show_picker = True model.add_window_filter() ui.Button( "Add Window", name="add", image_width=20, visible=True, clicked_fn=__add_window_filter ) return container if isinstance(item, EmptyFilterWindowItem): container = ui.HStack(width=self._width, height=VIEW_ROW_HEIGHT) with container: ui.Spacer(width=4) with ui.ZStack(): ui.Rectangle(style_type_name_override="DropDownArrow.background") with ui.HStack(): if item.id: action_label = ui.Label(item.id, name="", style_type_name_override="Action.Input") else: action_label = ui.Label("Select A Window", name="hint", style_type_name_override="Action.Input") with ui.VStack(width=0): ui.Spacer() ui.Triangle( width=20, height=16, alignment=ui.Alignment.CENTER_BOTTOM, style_type_name_override="DropDownArrow", ) ui.Spacer() ui.Spacer(width=4) container.set_mouse_released_fn(lambda x, y, b, f, m=model, i=item, c=container, l=action_label: self.__show_window_picker(m, i, c, l)) if self.__auto_show_picker: self.__show_window_picker(model, item, container, action_label) self.__auto_show_picker = False return container if isinstance(item, ActionExtItem): container = ui.ZStack(height=VIEW_ROW_HEIGHT) with container: with ui.VStack(): ui.Spacer() ui.Rectangle(height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() HighlightLabel(item.id, height=VIEW_ROW_HEIGHT, highlight=item.highlight, style=HIGHLIGHT_LABEL_STYLE) return container return None def __show_window_picker(self, model: HotkeysModel, item: EmptyFilterWindowItem, container: ui.Stack, label: ui.Label) -> None: if self.__windows_picker is not None: if self.__windows_picker.visible: # Just hide windows picker if it already visible self.__windows_picker.visible = False return self.__windows_picker = None # Refresh windows list every time def __on_window_selected(item, title): item = model.edit_hotkey_filter_item(item, window_title=title) label.text = title label.name = "" self.__windows_picker.visible = False async def __update_position(): if container.computed_width == 0: await omni.kit.app.get_app().next_update_async() self.__windows_picker = WindowsPicker(width=container.computed_content_width, height=500, on_selected_fn=lambda t, i=item: __on_window_selected(i, t)) self.__windows_picker.visible = True await omni.kit.app.get_app().next_update_async() self.__windows_picker.position_x = container.screen_position_x self.__windows_picker.position_y = container.screen_position_y + container.computed_height asyncio.ensure_future(__update_position())
5,119
Python
45.126126
162
0.572377
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/column_delegate/hotkey_column_delegate.py
# pylint: disable=unused-private-member, relative-beyond-top-level __all__ = ["KeyResetHelper", "HotkeyColumnDelegate"] import asyncio from typing import Dict, List from omni.kit.actions.window import AbstractActionItem, StringColumnDelegate from omni.kit.hotkeys.core import KeyCombination, HOTKEY_CHANGED_EVENT, HotkeyRegistry, get_hotkey_registry from omni.kit.widget.highlight_label import HighlightLabel import omni.ui as ui import omni.kit.app import carb.events from ..model.hotkeys_model import EmptyHotkeyItem, HotkeyDetailItem, HotkeysModel, AddWindowItem from ..model.hotkey_item import USER_HOTKEY_EXT_ID from ..window.warning_window import WarningWindow, WarningMessage from ..style import VIEW_ROW_HEIGHT, HIGHLIGHT_LABEL_STYLE, HIGHLIGHT_LABEL_STYLE_USER from .reset_button import ResetButton, ResetHelper from .key_editor import KeyEditor class KeyResetHelper(ResetHelper): def __init__(self, model: HotkeysModel, item: HotkeyDetailItem, container: ui.Widget): self.__model = model self.__item = item self.__container = container def can_reset(self) -> bool: return self.__item.is_modified() def reset(self) -> bool: result = self.__model.restore_item_key(self.__item) if result != HotkeyRegistry.Result.OK: if result == HotkeyRegistry.Result.ERROR_KEY_DUPLICATED: key_combination = KeyCombination(self.__item.default_key_id) duplicated_key = get_hotkey_registry().get_hotkey_for_filter(key_combination, self.__item.hotkey.filter) action_display = duplicated_key.action.display_name if duplicated_key.action else "Unknown Action" warn_window = WarningWindow( "Hotkey Conflict Warning", messages=[ "The default for this action is ", WarningMessage(f"'{key_combination.id}'", highlight=True), "\n", "It is already assigned to ", WarningMessage(f"'{action_display}'", highlight=True), '\n', "Do you want to replace this exising hotkey with your new one?" ], buttons=[ ("Replace", lambda k=key_combination, n=self.__item, o=duplicated_key: self.__model.replace_item_key(k, n, o)), ("Cancel", None) ], ) else: warn_window = WarningWindow("Unkown Error", [f"Error code: {result}"]) warn_window.position_x = self.__container.screen_position_x + 4 warn_window.position_y = self.__container.screen_position_y + self.__container.computed_height + 4 return False return True def filter_payload(self, payload: Dict) -> bool: hotkey = self.__item.hotkey if ( payload["hotkey_ext_id"] == hotkey.hotkey_ext_id and payload["action_ext_id"] == hotkey.action_ext_id and payload["action_id"] == hotkey.action_id ): self._update_reset_button() return True return False class HotkeyColumnDelegate(StringColumnDelegate): """ A simple delegate to display a editable hotkey in column. Kwargs: name (str): Column name. width (ui.Length): Column width. Default None means ui.Fraction(1). """ def __init__(self, name: str, width: ui.Length = None): width = ui.Fraction(1) if width is None else width super().__init__(name, width=width) self.__reset_helpers: Dict[HotkeyDetailItem, KeyResetHelper] = {} self.__key_editors: Dict[HotkeyDetailItem, KeyEditor] = {} self.__edit_containers: Dict[HotkeyDetailItem, ui.HStack] = {} self.__last_selections: List[AbstractActionItem] = [] event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self.__change_event_sub = event_stream.create_subscription_to_pop_by_type( HOTKEY_CHANGED_EVENT, self.__on_hotkey_changed) def destroy(self): self.__reset_helpers = {} self.stop_key_capture() self.__key_editors = {} self.__change_event_sub = None def stop_key_capture(self): for item in self.__key_editors.values(): item.visible = False def build_widget(self, model: HotkeysModel, item: AbstractActionItem, level: int, expand: bool): if isinstance(item, (HotkeyDetailItem, EmptyHotkeyItem)): is_empty_hotkey = isinstance(item, EmptyHotkeyItem) container = ui.ZStack() with container: tool_container = ui.HStack(visible=not is_empty_hotkey, content_clipping=True) with tool_container: key_label = HighlightLabel(item.hotkey.key_text, highlight=item.highlight, style=HIGHLIGHT_LABEL_STYLE_USER if item.user_defined else HIGHLIGHT_LABEL_STYLE) ui.Spacer() edit_container = ui.HStack(width=0, visible=item in self.__last_selections) with edit_container: if item.hotkey.hotkey_ext_id == USER_HOTKEY_EXT_ID: ui.Image(name="delete", width=20, mouse_pressed_fn=lambda x, y, b, f, m=model, i=item: self.__on_delete(m, i)) ui.Spacer(width=4) edit_image = ui.Image(name="edit", width=20) if isinstance(item, HotkeyDetailItem): ui.Spacer(width=4) self.__reset_helpers[item] = KeyResetHelper(model, item, container) reset_button = ResetButton([self.__reset_helpers[item]]) self.__reset_helpers[item].set_reset_button(reset_button) ui.Spacer(width=1) key_editor = KeyEditor(model, item, visible=is_empty_hotkey, on_edit_cancelled_fn=lambda v, k=key_label, t=tool_container: self.__on_key_cancelled(v, k, t)) self.__key_editors[item] = key_editor self.__edit_containers[item] = edit_container tool_container.set_mouse_double_clicked_fn(lambda x, y, b, f, t=tool_container, k=key_editor: self.__show_key_editor(t, k)) edit_image.set_mouse_pressed_fn(lambda x, y, b, f, t=tool_container, k=key_editor: self.__show_key_editor(t, k)) return container if isinstance(item, AddWindowItem): return None container = ui.VStack(height=VIEW_ROW_HEIGHT) with container: ui.Spacer() ui.Rectangle(height=26, style_type_name_override="ActionsView.Row.Background") ui.Spacer() return container def on_selection_changed(self, selections: List[ui.AbstractItem]): for item in self.__last_selections: if item in self.__edit_containers and not self.__key_editors[item].visible: self.__edit_containers[item].visible = False for item in selections: if item in self.__edit_containers and not self.__key_editors[item].visible: self.__edit_containers[item].visible = True self.__last_selections = selections def on_hover_changed(self, item: ui.AbstractItem, hovered: bool) -> None: if not isinstance(item, HotkeyDetailItem): return if item in self.__edit_containers and not self.__key_editors[item].visible: self.__edit_containers[item].visible = hovered or item in self.__last_selections def __show_key_editor(self, tool_container: ui.HStack, key_editor: KeyEditor) -> None: async def __show_editor(): # Wait a frame to not trigger show editor and drop down arrow at one click await omni.kit.app.get_app().next_update_async() key_editor.visible = True tool_container.visible = False asyncio.ensure_future(__show_editor()) def __on_key_cancelled(self, value: str, key_label: ui.Label, tool_container: ui.HStack): key_label.text = value if value is not None else "" tool_container.visible = True def __on_delete(self, model: HotkeysModel, item: HotkeyDetailItem) -> None: model.delete_hotkey_item(item) def __on_hotkey_changed(self, event: carb.events.IEvent): for helper in self.__reset_helpers.values(): if helper.filter_payload(event.payload): break
8,512
Python
46.825842
176
0.607965
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/tests/test_hotkeys_model.py
# pylint: disable=protected-access from pathlib import Path from typing import Tuple from omni.ui.tests.test_base import OmniUiTest import omni.kit.app import omni.kit.test import omni.ui as ui from omni.kit.actions.core import get_action_registry from omni.kit.hotkeys.core import get_hotkey_registry, KeyCombination, HotkeyRegistry from ..window.hotkeys_window import HotkeysWindow from ..model.hotkey_item import USER_HOTKEY_EXT_ID, HotkeyDetailItem TEST_ACTION_EXT_ID = "test.hotkey.model" TEST_ACTION_ID = "new" TEST_ANOTHER_ACTION_ID = "another" CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") class TestHotkeysModel(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() # Hide original hotkeys window self.__origin_hotkeys_window = ui.Workspace.get_window("Hotkeys") self.__origin_hotkeys_window.visible = False await omni.kit.app.get_app().next_update_async() # Create new hotkeys window self.__window = HotkeysWindow("Model") await self.docked_test_window(window=self.__window, width=1280, height=400, block_devices=False) self.__window._search_bar.visible = False self._model = self.__window._hotkeys_model self.__register_actions() self.__action_executed = 0 self.__model_changed = 0 async def tearDown(self): self._action_registry.deregister_all_actions_for_extension(TEST_ACTION_EXT_ID) self._hotkey_registry.deregister_all_hotkeys_for_extension(USER_HOTKEY_EXT_ID) self._hotkey_registry.clear_storage() self.__window.visible = False self.__window.destroy() self.__window = None self.__origin_hotkeys_window.visible = True await super().tearDown() async def test_1_add_global_empty_hotkey(self): await self.__add_empty_global_hotkey() # Wait for icons loaded for _ in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_add_global_empty.png", threshold=.03) async def test_2_save_global_empty_hotkey(self): (item, _) = await self.__add_save_empty_global_hotkey(KeyCombination("N")) await self.__wait_for_icons() self._model.execute(item) self.assertEqual(self.__action_executed, 1) self.assertEqual(self._model.get_item_by_key(KeyCombination("N"), None).hotkey, item.hotkey) self.assertIsNone(self._model.get_item_by_key(KeyCombination("A"), None)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_save_global_empty.png", threshold=.03) async def test_3_delete_global_hotkey(self): await self.__add_save_empty_global_hotkey(KeyCombination("N")) filter_items = self._model.get_item_children(None) global_filter_item = filter_items[0] hotkey_items = self._model.get_item_children(global_filter_item) self._model.delete_hotkey_item(hotkey_items[0]) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_delete_global_empty.png", threshold=.03) async def test_4_edit_global_hotkey(self): await self.__add_save_edit_empty_global_hotkey(KeyCombination("N")) # Wait for icons loaded for _ in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_edit_global_empty.png", threshold=.03) async def test_5_retore_global_hotkey(self): await self.__add_save_edit_empty_global_hotkey(KeyCombination("N")) model = self.__window._hotkeys_model filter_items = model.get_item_children(None) global_filter_item = filter_items[0] hotkey_items = model.get_item_children(global_filter_item) model.restore_item_key(hotkey_items[0]) await self.__wait_for_icons() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_restore_global_hotkey.png", threshold=.03) async def test_6_add_window_filter(self): await self.__add_window_filter() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_add_window_filter.png", threshold=.03) async def test_7_edit_window_filter(self): result = await self.__add_save_window_filter(KeyCombination("T")) self.assertEqual(result, HotkeyRegistry.Result.OK) await self.__wait_for_icons() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_edit_window_filter.png", threshold=.03) async def test_8_save_global_duplicated(self): key_combination = KeyCombination("T") (_, result) = await self.__add_save_empty_global_hotkey(key_combination) self.assertEqual(result, HotkeyRegistry.Result.OK) (item, result) = await self.__add_save_empty_global_hotkey(key_combination, action=self._another_action) self.assertEqual(result, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED) model = self.__window._hotkeys_model duplicated_key = self._hotkey_registry.get_hotkey_for_filter(key_combination, item.hotkey.filter) model.replace_item_key(key_combination, item, duplicated_key) await self.__wait_for_icons() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="hotkeys_model_save_global_duplicated.png", threshold=.03) async def test_clear_empty_hotkey(self): def __on_model_changed(m, i): self.__model_changed += 1 sub = self._model.subscribe_item_changed_fn(__on_model_changed) # noqa: PLW0612 # No empty hotkey, nothing happens self._model.clear_empty_hotkey() self.assertEqual(self.__model_changed, 0) # Add a empty hotkey then clear filter_items = self._model.get_item_children(None) window_filter_item = filter_items[1] added_item = self._model.add_empty_hotkey(window_filter_item) self.assertIsNotNone(added_item) self.assertEqual(self.__model_changed, 1) await omni.kit.app.get_app().next_update_async() self._model.clear_empty_hotkey() await omni.kit.app.get_app().next_update_async() self.assertEqual(self.__model_changed, 2) sub = None # noqa: F841 async def __add_window_filter(self): model = self.__window._hotkeys_model model.add_window_filter() await omni.kit.app.get_app().next_update_async() async def __add_save_window_filter(self, key_combination) -> HotkeyRegistry.Result: await self.__add_window_filter() model = self.__window._hotkeys_model filter_items = model.get_item_children(None) window_filter_item = filter_items[1] model.edit_hotkey_filter_item(window_filter_item, window_title="Hotkeys") model.add_empty_hotkey(window_filter_item) model.save_empty_action(self._new_action) result = model.save_empty_hotkey(key_combination) await omni.kit.app.get_app().next_update_async() return result async def __add_empty_global_hotkey(self) -> HotkeyDetailItem: model = self.__window._hotkeys_model filter_items = model.get_item_children(None) global_filter_item = filter_items[0] item = model.add_empty_hotkey(global_filter_item) await omni.kit.app.get_app().next_update_async() return item async def __add_save_empty_global_hotkey(self, key_combination, action=None) -> Tuple[HotkeyDetailItem, HotkeyRegistry.Result]: item = await self.__add_empty_global_hotkey() model = self.__window._hotkeys_model if action is None: action = self._new_action model.save_empty_action(action) result = model.save_empty_hotkey(key_combination) await omni.kit.app.get_app().next_update_async() return (item, result) async def __add_save_edit_empty_global_hotkey(self, key_combination) -> Tuple[HotkeyDetailItem, HotkeyRegistry.Result]: (item, result) = await self.__add_save_empty_global_hotkey(key_combination) model = self.__window._hotkeys_model filter_items = model.get_item_children(None) global_filter_item = filter_items[0] hotkey_items = model.get_item_children(global_filter_item) result = model.edit_hotkey_item(hotkey_items[0], key_text="P") await omni.kit.app.get_app().next_update_async() return (item, result) def __register_actions(self): self._action_registry = get_action_registry() self._new_action = self._action_registry.register_action( TEST_ACTION_EXT_ID, TEST_ACTION_ID, self._test_action, display_name="Model test", description="MODEL TEST", tag="Actions", ) self._another_action = self._action_registry.register_action( TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, lambda: None, display_name="Another model test", description="ANOTHER MODEL TEST", tag="Actions", ) self._hotkey_registry = get_hotkey_registry() async def __wait_for_icons(self): for _ in range(10): await omni.kit.app.get_app().next_update_async() def _test_action(self): self.__action_executed += 1
9,783
Python
42.292035
144
0.660125
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/tests/test_windows_picker.py
import omni.kit.app from omni.kit.test import AsyncTestCase from ..window.windows_picker import WindowsPicker class TestWindowsPicker(AsyncTestCase): async def setUp(self): self._selected_title = "" async def test_general(self): def on_selected(window_title: str): self._selected_title = window_title window = WindowsPicker(width=800, height=600, on_selected_fn=on_selected) for _ in range(4): await omni.kit.app.get_app().next_update_async() window._search_field.search_words = ["hot"] # noqa: PLW0212 await omni.kit.app.get_app().next_update_async() items = window._windows_model.get_item_children() # noqa: PLW0212 window._actions_view.selection = [item for item in items if item.window_title == "Hotkeys"] # noqa: PLW0212 await omni.kit.app.get_app().next_update_async() self.assertEqual(self._selected_title, "Hotkeys")
953
Python
35.692306
118
0.655824
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/tests/__init__.py
from .test_hotkeys_window import * from .test_hotkeys_model import * from .test_options_menu import * from .test_warning_window import * from .test_windows_model import * from .test_windows_picker import *
206
Python
28.571424
34
0.76699
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/tests/test_windows_model.py
from omni.kit.test import AsyncTestCase from ..model.windows_model import WindowsModel class TestWindowsModel(AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_model(self): model = WindowsModel("Hotkeys") self.assertEqual(model.get_item_value_model_count(), 1) items = model.get_item_children() self.assertEqual(model.get_item_value_model(None), "") self.assertEqual(model.get_item_value_model(items[1]).as_string, items[1].window_title) self.assertEqual(model.get_item_children(items[0]), []) self.assertTrue("Hotkeys" in [item.window_title for item in items]) self.assertEqual(model.selected_windows, ["Hotkeys"]) # Note, there will always be "" as first item # Search a window model.search(["hot"]) items = model.get_item_children() print([w.window_title for w in items]) self.assertEqual(len(items), 2) # Search a un-exist window model.search(["un-exist"]) items = model.get_item_children() self.assertEqual(len(items), 1)
1,146
Python
32.735293
95
0.638743
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/tests/test_options_menu.py
from unittest.mock import patch import omni.kit.app import omni.ui as ui from omni.kit.ui_test.query import MenuRef, WindowRef import omni.kit.ui_test as ui_test from omni.ui.tests.test_base import OmniUiTest class TestOptionsMenu(OmniUiTest): async def setUp(self): await super().setUp() window = ui.Workspace.get_window("Hotkeys") window.visible = True # just in case another test has turned it off await self.docked_test_window(window=window, width=1280, height=800, block_devices=False) window._search_bar._SearchBar__show_options() # noqa: PLW0212 self._menu = window._search_bar._SearchBar__options_menu # noqa: PLW0212 await omni.kit.app.get_app().next_update_async() menu_ref = MenuRef(self._menu._OptionsMenu__context_menu, "") # noqa: PLW0212 self._menu_items = menu_ref.find_all("**/") async def test_import(self): """Test import hotkey preset""" self.assertEqual(self._menu_items[0].widget.text, "Import Preset") await self._menu_items[0].click() for _ in range(4): await omni.kit.app.get_app().next_update_async() dialog = self._menu._OptionsMenu__import_dialog # noqa: PLW0212 self.assertIsNotNone(dialog) dialog.set_current_directory("test") dialog.set_filename("test_import.json") import_window = ui.Workspace.get_window("Import") window_ref = WindowRef(import_window, "") import_btn_ref = window_ref.find_all("**/Button[*].text=='import'")[0] with ( patch("omni.client.stat", side_effect=self._mock_stat_file_impl), patch("omni.kit.hotkeys.core.HotkeyRegistry.import_storage") as mock_import ): await import_btn_ref.click() mock_import.assert_called_once() async def test_export(self): """Test export hotkey presets""" self.assertEqual(self._menu_items[1].widget.text, "Export Preset") await self._menu_items[1].click() for _ in range(4): await omni.kit.app.get_app().next_update_async() dialog = self._menu._OptionsMenu__export_dialog # noqa: PLW0212 self.assertIsNotNone(dialog) dialog.set_current_directory("test") dialog.set_filename("test_import.json") export_window = ui.Workspace.get_window("Export As") window_ref = WindowRef(export_window, "") export_btn_ref = window_ref.find_all("**/Button[*].text=='Export'")[0] with ( patch("omni.client.stat", side_effect=self._mock_stat_file_not_found_impl), patch("omni.kit.hotkeys.core.HotkeyRegistry.export_storage") as mock_export ): await export_btn_ref.click() mock_export.assert_called_once() async def test_restore(self): """Test restore hotkeys defaults""" self.assertEqual(self._menu_items[2].widget.text, "Restore Defaults") await self._menu_items[2].click() for _ in range(4): await omni.kit.app.get_app().next_update_async() warning_window = ui.Workspace.get_window("###Hotkey_WARNING_Restore Defaults") window_ref = WindowRef(warning_window, "") for _ in range(10): await omni.kit.app.get_app().next_update_async() btn_ref = window_ref.find_all("**/Button[*].text=='Yes'")[0] with patch("omni.kit.hotkeys.core.HotkeyRegistry.restore_defaults") as mock_restore: await btn_ref.click() mock_restore.assert_called_once() async def test_layout(self): """Test switching keyboard layout""" self.assertEqual(self._menu_items[3].widget.text, "Keyboard Layouts") await ui_test.emulate_mouse_move(self._menu_items[3].center) layout_menu_items = self._menu_items[3].find_all("**/") with patch("omni.kit.hotkeys.core.HotkeyRegistry.switch_layout") as mock_switch_layout: await layout_menu_items[0].click() mock_switch_layout.assert_called_once() def _mock_stat_file_impl(self, url: str): return (omni.client.Result.OK, None) def _mock_stat_file_not_found_impl(self, url: str): return (omni.client.Result.ERROR_NOT_FOUND, None)
4,268
Python
36.778761
97
0.627226
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/tests/test_hotkeys_window.py
from pathlib import Path from omni.kit.actions.core import get_action_registry import omni.kit.app import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.kit.hotkeys.core import get_hotkey_registry, HotkeyFilter import omni.ui as ui import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") ACTION_SHOW_WINDOW = "Show" ACTION_HIDE_WINDOW = "Hide" class TestHotkeysWindow(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._action_registry = None self._ext_id = "hotkeys" self.__register_test_hotkeys() window = ui.Workspace.get_window("Hotkeys") window.visible = True # just in case another test has turned it off await self.docked_test_window(window=window, width=1280, height=400, block_devices=False) async def tearDown(self): # Deregister all the test hotkeys self._hotkey_registry.deregister_hotkey(self._ext_id, "CTL+S") self._hotkey_registry.deregister_hotkey(self._ext_id, "ALT+H") # Deregister all the test actions. self._action_registry.deregister_action(self._ext_id, ACTION_SHOW_WINDOW) self._action_registry.deregister_action(self._ext_id, ACTION_HIDE_WINDOW) self._action_registry = None async def test_1_general_window(self): # When startup, no actions loaded # Expand await ui_test.emulate_mouse_move_and_click(Vec2(13, 67)) for _ in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_hotkey_window_general_with_search.png") async def test_2_search(self): # Actions reloaded, we can see register actions now # Focus on search bar await ui_test.emulate_mouse_move_and_click(Vec2(50, 17)) # Search "Show" await ui_test.emulate_char_press("Show\n") await ui_test.emulate_mouse_move_and_click(Vec2(0, 0)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_hotkey_window_search.png") async def test_3_search_clean(self): # Focus on search bar await ui_test.emulate_mouse_move_and_click(Vec2(50, 17)) # Clean search await ui_test.emulate_mouse_move_and_click(Vec2(1214, 17)) await ui_test.emulate_mouse_move_and_click(Vec2(0, 0)) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_hotkey_window_search_clean.png") def __register_test_hotkeys(self): self._action_registry = get_action_registry() self._action_registry.register_action( self._ext_id, ACTION_SHOW_WINDOW, lambda: None, display_name=ACTION_SHOW_WINDOW, description=ACTION_SHOW_WINDOW, tag="Actions", ) self._action_registry.register_action( self._ext_id, ACTION_HIDE_WINDOW, lambda: None, display_name=ACTION_HIDE_WINDOW, description=ACTION_HIDE_WINDOW, tag="Actions", ) self._context_filter = HotkeyFilter(context="Test Context") self._window_filter = HotkeyFilter(windows=["Viewport"]) self._hotkey_registry = get_hotkey_registry() self._hotkey_registry.register_hotkey(self._ext_id, "CTL+S", self._ext_id, ACTION_SHOW_WINDOW) self._hotkey_registry.register_hotkey(self._ext_id, "ALT+H", self._ext_id, ACTION_HIDE_WINDOW) self._hotkey_registry.register_hotkey(self._ext_id, "H", self._ext_id, ACTION_HIDE_WINDOW, filter=self._context_filter) self._hotkey_registry.register_hotkey(self._ext_id, "S", self._ext_id, ACTION_SHOW_WINDOW, filter=self._context_filter) self._hotkey_registry.register_hotkey(self._ext_id, "H", self._ext_id, ACTION_HIDE_WINDOW, filter=self._window_filter) self._hotkey_registry.register_hotkey(self._ext_id, "S", self._ext_id, ACTION_SHOW_WINDOW, filter=self._window_filter)
4,275
Python
41.76
131
0.660819
omniverse-code/kit/exts/omni.kit.hotkeys.window/omni/kit/hotkeys/window/tests/test_warning_window.py
from pathlib import Path from omni.ui.tests.test_base import OmniUiTest import omni.kit.app import omni.kit.test import omni.ui as ui from ..window.warning_window import WarningWindow, WarningMessage CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") class TestWarningWindow(OmniUiTest): async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self.__window = None # Hide hotkeys window window = ui.Workspace.get_window("Hotkeys") window.visible = False await omni.kit.app.get_app().next_update_async() async def tearDown(self): self.__window.visible = False self.__window = None await super().tearDown() async def test_simple(self): self.__window = WarningWindow("Test", messages=["This is a simple test menssage."]) await omni.kit.app.get_app().next_update_async() await self.docked_test_window(window=self.__window, width=self.__window.width + 10, height=100, block_devices=False) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="warning_simple.png") async def test_advanced(self): self.__window = WarningWindow( "Test", messages=[ WarningMessage("'CTRL + O (On Press_'", highlight=True), WarningMessage(" is already assigned to "), WarningMessage("'Open'", highlight=True), "\n", "Do you want to replace this existing hotkey with your new one?" ], buttons=[ ("Replace", lambda: print("Replace")), ("Cancel", lambda: print("Cancel")) ] ) await omni.kit.app.get_app().next_update_async() await self.docked_test_window(window=self.__window, width=self.__window.width + 10, height=160, block_devices=False) # Because it takes time to load the icon in the warning window for _ in range(5): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="warning_advanced.png")
2,307
Python
38.118643
124
0.623754
omniverse-code/kit/exts/omni.kit.hotkeys.window/docs/index.rst
omni.kit.hotkeys.window ####################### Window to show hotkeys. .. toctree:: :maxdepth: 1 CHANGELOG EditHotkey
132
reStructuredText
10.083332
23
0.560606
omniverse-code/kit/exts/omni.kit.stage.copypaste/PACKAGE-LICENSES/omni.kit.stage.copypaste-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.stage.copypaste/config/extension.toml
[package] version = "1.0.4" authors = ["NVIDIA"] title = "USD Prim Copy Paste" description="The ability to copy and paste USD Prims" readme = "docs/README.md" repository = "" category = "USD" feature = true keywords = ["usd", "copy", "paste", "clipboard", "stage"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.appwindow" = {} "omni.kit.clipboard" = {} "omni.kit.commands" = {} "omni.kit.context_menu" = {} "omni.kit.pip_archive" = {} "omni.usd" = {} [[python.module]] name = "omni.kit.stage.copypaste" [[test]] args = [] dependencies = [] stdoutFailPatterns.include = [] stdoutFailPatterns.exclude = []
671
TOML
20.677419
57
0.66766
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/prim_serializer.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["update_property_paths", "get_prim_as_text", "text_to_stage"] import sys from typing import Callable from typing import List from typing import Optional from typing import Tuple from omni.kit.commands import execute from pxr import Sdf from pxr import Tf from pxr import Usd import omni.usd POS_ATTR_NAME = 'ui:nodegraph:node:pos' SMALL_OFFSET = 40 def _to_layer(text: str, keep_inputs=True, position=None) -> Optional[Sdf.Layer]: """Create an sdf layer from the given text""" if not text.startswith("#usda 1.0\n"): text = "#usda 1.0\n" + text anonymous_layer = Sdf.Layer.CreateAnonymous("clipboard.usda") try: if not anonymous_layer.ImportFromString(text): return None except Tf.ErrorException: return None if not keep_inputs or position is not None: graph_node_processing(anonymous_layer, keep_inputs=keep_inputs, position=position) return anonymous_layer def graph_node_processing(layer: Sdf.Layer, keep_inputs=True, position=None): all_prims = [] min_x, min_y = sys.maxsize, sys.maxsize offset = None root_prims = layer.rootPrims for prim_spec in root_prims: root_spec = prim_spec.nameChildren[0] all_prims.append(root_spec.path) if position is not None and POS_ATTR_NAME in root_spec.attributes: # Keep top left of bounding box of nodes pos = root_spec.attributes[POS_ATTR_NAME].default if pos[0] < min_x: min_x = pos[0] if pos[1] < min_y: min_y = pos[1] if position is not None: offset = (position[0] - min_x, position[1] - min_y) for prim_path in all_prims: prim_spec = layer.GetPrimAtPath(prim_path) attrs = prim_spec.attributes if POS_ATTR_NAME in attrs: offset_node_position(attrs[POS_ATTR_NAME], offset=offset) if not keep_inputs: for attr in attrs: connections = attr.connectionPathList.explicitItems if connections: attr.connectionPathList.explicitItems = [ path for path in attr.connectionPathList.explicitItems if connections[0].GetPrimPath() in all_prims ] def offset_node_position(pos_attr: Sdf.AttributeSpec, offset: Optional[Tuple[float, float]] = None): """Shift the nodes to be pasted, by the offset parameter, or if no offset is passed in, by a small offset, so pasted nodes are not exactly on top of the originals. Args: pos_attr (Sdf.AttributeSpec): AttributeSpec to get the existing position from. offset (Tuple[float, float], optional): Offset to place at mouse position. Defaults to None. """ cur_position = pos_attr.default if offset is not None: pos_attr.default = (cur_position[0] + offset[0], cur_position[1] + offset[1]) else: pos_attr.default = (cur_position[0] + SMALL_OFFSET, cur_position[1] + SMALL_OFFSET) def update_property_paths(prim_spec, old_path, new_path): if not prim_spec: return for rel in prim_spec.relationships: rel.targetPathList.explicitItems = [ path.ReplacePrefix(old_path, new_path) for path in rel.targetPathList.explicitItems ] for attr in prim_spec.attributes: attr.connectionPathList.explicitItems = [ path.ReplacePrefix(old_path, new_path) for path in attr.connectionPathList.explicitItems ] for child in prim_spec.nameChildren: update_property_paths(child, old_path, new_path) def get_prim_as_text(stage: Usd.Stage, prim_paths: List[Sdf.Path]) -> Optional[str]: """Generate a text representation from the stage and prim path""" if not prim_paths: return None prim_paths = [Sdf.Path(path) for path in prim_paths] prim_paths = Sdf.Path.RemoveDescendentPaths(prim_paths) # flatten_layer = stage.Flatten() # Stitches prims instead of flattening to avoid flattening references and payloads. flatten_layer = Sdf.Layer.CreateAnonymous() for prim_path in prim_paths: omni.usd.stitch_prim_specs(stage, prim_path, flatten_layer) paths_map = {} anonymous_layer = Sdf.Layer.CreateAnonymous(prim_paths[0].name + ".usda") for i, prim_path in enumerate(prim_paths): item_name = str.format("Item_{:02d}", i) Sdf.PrimSpec(anonymous_layer, item_name, Sdf.SpecifierDef) anonymous_path = Sdf.Path.absoluteRootPath.AppendChild(item_name).AppendChild(prim_path.name) # Copy Sdf.CopySpec(flatten_layer, prim_path, anonymous_layer, anonymous_path) paths_map[prim_path] = anonymous_path for prim in anonymous_layer.rootPrims: for source_path, target_path in paths_map.items(): update_property_paths(prim, source_path, target_path) return anonymous_layer.ExportToString() def text_to_stage(stage: Usd.Stage, text: str, root: Sdf.Path = Sdf.Path.absoluteRootPath, keep_inputs=True, position=None, filter_fn: Optional[Callable] = None) -> bool: """ Convert the given text to prims and place them on the stage under the given root. """ source_layer = _to_layer(text, keep_inputs=keep_inputs, position=position) if not source_layer: return False execute("ImportLayer", layer=source_layer, stage=stage, root=root, filter_fn=filter_fn) return True
5,899
Python
34.329341
101
0.666045
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/usdstage_helper.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["UsdStageHelper"] from typing import Optional from pxr import Usd from pxr import UsdUtils class UsdStageHelper: """Keeps the stage ID or returns the stage from the current context""" def __init__(self, stage: Usd.Stage): if stage: # Keep ID so the command doesn't prevent the stage from closing. self.__stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt() else: self.__stage_id = None def _get_stage(self) -> Optional[Usd.Stage]: if self.__stage_id: # Get the stage from ID cache = UsdUtils.StageCache.Get() stage = cache.Find(Usd.StageCache.Id.FromLongInt(self.__stage_id)) return stage # Get the stage from the context import omni.usd return omni.usd.get_context().get_stage()
1,285
Python
32.842104
80
0.676265
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/stage_copypaste_extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["StageCopypasteExtension"] from typing import Optional # from carb.input import KEYBOARD_MODIFIER_FLAG_CONTROL as CTRL # from carb.input import KeyboardInput as Key from pxr import Sdf import carb import omni.ext import omni.kit.context_menu import omni.usd from omni.kit.actions.core import get_action_registry # from .hotkey import Hotkey from .prim_serializer import get_prim_as_text, text_to_stage _HOTKEYS_EXT = "omni.kit.hotkeys.core" _DEFAULT_HOTKEY_MAP = { "stage_copy": "CTRL+C", "stage_paste": "CTRL+V", } class StageCopypasteExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_name = None self._stage_menu = None self._stage_context_menu_copy = None self._stage_context_menu_paste = None self._hotkey_extension_enabled_hook = None self._hotkey_extension_disabled_hook = None def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) # Hooks to hotkey extension enable/disable app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() hooks: omni.ext.IExtensionManagerHooks = ext_manager.get_hooks() self._hotkey_extension_enabled_hook = hooks.create_extension_state_change_hook( self._on_hotkey_ext_changed, omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE, ext_name="omni.kit.hotkeys.core", ) self._hotkey_extension_disabled_hook = hooks.create_extension_state_change_hook( self._on_hotkey_ext_changed, omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE, ext_name="omni.kit.hotkeys.core", ) self.register_actions(self._ext_name) self.register_hotkeys(self._ext_name) self._stage_menu = ext_manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self._register_stage_menu(), on_disable_fn=lambda _: self._unregister_stage_menu(), ext_name="omni.kit.widget.stage", hook_name="omni.kit.stage.copypaste", ) def on_shutdown(self): self._stage_menu = None self._stage_context_menu_copy = None self._stage_context_menu_paste = None self._hotkey_extension_enabled_hook = None self._hotkey_extension_disabled_hook = None self.deregister_hotkeys(self._ext_name) self.deregister_actions(self._ext_name) def register_actions(self, extension_id: str): action_registry = get_action_registry() actions_tag = "Stage Copy/Paste Actions" action_registry.register_action( extension_id, "stage_copy", self._on_copy, display_name="Copy", description="Copy objects in the stage", tag=actions_tag, ) action_registry.register_action( extension_id, "stage_paste", self._on_paste, display_name="Paste", description="Paste objects in the stage", tag=actions_tag, ) def deregister_actions(self, extension_id): action_registry = get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id) def register_hotkeys(self, extension_id: str, window_name: Optional[str] = None): ext_manager = omni.kit.app.get_app_interface().get_extension_manager() if not ext_manager.is_extension_enabled(_HOTKEYS_EXT): carb.log_info(f"{_HOTKEYS_EXT} is not enabled. Cannot register hotkeys.") return import omni.kit.hotkeys.core as hotkeys hotkey_registry = hotkeys.get_hotkey_registry() action_registry = get_action_registry() ext_actions = action_registry.get_all_actions_for_extension(extension_id) hotkey_filter = hotkeys.HotkeyFilter(windows=[window_name]) if window_name else None for action in ext_actions: key = _DEFAULT_HOTKEY_MAP.get(action.id, None) # Not all Actions will have default hotkeys if not key: continue hotkey_registry.register_hotkey( hotkey_ext_id=extension_id, key=key, action_ext_id=action.extension_id, action_id=action.id, filter=hotkey_filter, ) def deregister_hotkeys(self, extension_id: str): ext_manager = omni.kit.app.get_app_interface().get_extension_manager() if not ext_manager.is_extension_enabled(_HOTKEYS_EXT): carb.log_info(f"{_HOTKEYS_EXT} is not enabled. No hotkeys to deregister.") return import omni.kit.hotkeys.core as hotkeys hotkey_registry = hotkeys.get_hotkey_registry() hotkey_registry.deregister_all_hotkeys_for_extension(extension_id) def _on_hotkey_ext_changed(self, ext_id: str, ext_change_type: omni.ext.ExtensionStateChangeType): if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE: self.register_hotkeys(self._ext_name) if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE: self.deregister_hotkeys(self._ext_name) def _on_copy(self): """Called when the user pressed Ctrl-C""" # Get the selected paths usd_context = omni.usd.get_context() stage = usd_context.get_stage() selection = usd_context.get_selection() paths = [Sdf.Path(name) for name in selection.get_selected_prim_paths()] prim_as_text = get_prim_as_text(stage, paths) if prim_as_text: omni.kit.clipboard.copy(prim_as_text) def _on_paste(self, keep_inputs=True, root=None, position=None, filter_fn=None): """Called when the user pressed Ctrl-V""" def get_root_prims(stage): """Get the root layer prims visible in the stage window""" all_roots = stage.GetPseudoRoot().GetChildren() return [p for p in all_roots if p.GetMetadata("hide_in_stage_window") is not True] text = omni.kit.clipboard.paste() if not text: # Silent return return usd_context = omni.usd.get_context() stage = usd_context.get_stage() if not root: # Pick the root. If we have the only root prim and it's the default # one, we need to paste in this prim. For example "/World". root = Sdf.Path.absoluteRootPath if len(get_root_prims(stage)) == 1: default_prim = stage.GetDefaultPrim() if default_prim: root = default_prim.GetPath() if not text_to_stage(stage, text, root, keep_inputs=keep_inputs, position=position, filter_fn=filter_fn): carb.log_warn("The clipboard doesn't have usda") def _register_stage_menu(self): """Called when "omni.kit.widget.stage" is loaded""" def on_copy(objects: dict): """Called from the context menu""" prims = objects.get("prim_list", None) stage = objects.get("stage", None) if not prims or not stage: return paths = [p.GetPath() for p in prims] prim_as_text = get_prim_as_text(stage, paths) if prim_as_text: omni.kit.clipboard.copy(prim_as_text) def on_paste(objects: dict): """Called from the context menu""" text = omni.kit.clipboard.paste() if not text: # Silent return return stage = objects.get("stage", None) if not stage: return prims = objects.get("prim_list", None) if not prims: root = Sdf.Path.absoluteRootPath elif len(prims) == 1: root = prims[0].GetPath() else: carb.log_warn("Can't paste to multiple locations") return if not text_to_stage(stage, text, root): carb.log_warn("The clipboard doesn't have usda") # Add context menu to omni.kit.widget.stage context_menu = omni.kit.context_menu.get_instance() if context_menu: menu = { "name": "Copy Prim", "glyph": "menu_link.svg", "show_fn": [context_menu.is_prim_selected], "onclick_fn": on_copy, "appear_after": "Copy Prim Path", } self._stage_context_menu_copy = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage") menu = {"name": "Paste Prim", "glyph": "menu_link.svg", "onclick_fn": on_paste, "appear_after": "Copy Prim"} self._stage_context_menu_paste = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage") def _unregister_stage_menu(self): """Called when "omni.kit.widget.stage" is unloaded""" self._stage_context_menu_copy = None self._stage_context_menu_paste = None
9,582
Python
36.580392
120
0.605823
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .prim_serializer import * from .stage_copypaste_commands import * from .stage_copypaste_extension import *
540
Python
44.08333
76
0.805556
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/hotkey.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["Hotkey"] from functools import partial import carb.input import omni.appwindow class Hotkey: """ Bind a hotkey to the given callback. The hotkey is active while the object is alive. """ def __init__(self, action_name, hotkey, modifier, on_action_fn): self._input = carb.input.acquire_input_interface() settings = carb.settings.get_settings() # TODO: bind to all app windows appwindow = omni.appwindow.get_default_app_window() action_mapping_set_path = appwindow.get_action_mapping_set_path() action_mapping_set = self._input.get_action_mapping_set_by_path(action_mapping_set_path) input_string = carb.input.get_string_from_action_mapping_desc(hotkey, modifier) input_path = action_mapping_set_path + "/" + action_name + "/0" settings.set_default_string(input_path, input_string) def action_trigger(on_action_fn, evt, *_): if not evt.flags & carb.input.BUTTON_FLAG_PRESSED: return on_action_fn() self._sub = self._input.subscribe_to_action_events( action_mapping_set, action_name, partial(action_trigger, on_action_fn) ) def __del__(self): self._input.unsubscribe_to_action_events(self._sub)
1,721
Python
35.638297
96
0.680999
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/stage_copypaste_commands.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ImportLayerCommand"] import re from typing import Callable from typing import List from typing import Optional import carb from omni.usd.commands import DeletePrimsCommand from pxr import Sdf from pxr import Usd import omni.kit.commands import omni.usd from .usdstage_helper import UsdStageHelper from .prim_serializer import update_property_paths class ImportLayerCommand(omni.kit.commands.Command, UsdStageHelper): """ Import given layer to the given stage under the specific root. ### Arguments: `layer : Sdf.Layer` All the prims from this layer will be imported to the stage. `root : Sdf.Path` The new prims will be placed under this path. `stage : Optional[int]` The stage it's necessary to add the new prims. If None, it takes the stage from the USD Context. """ def __init__( self, layer: Sdf.Layer, root: Sdf.Path = Sdf.Path.absoluteRootPath, stage: Optional[Usd.Stage] = None, filter_fn: Optional[Callable] = None, ): UsdStageHelper.__init__(self, stage) self._layer = layer self._root = root self._created_paths: List[str] = [] self._selection: List[str] = [] self._filter_fn: Optional[Callable] = filter_fn def do(self): # Save selection self._selection = omni.usd.get_context().get_selection().get_selected_prim_paths() stage = self._get_stage() target_layer = stage.GetEditTarget().GetLayer() paths_map = {} with Sdf.ChangeBlock(): for prim_spec in self._layer.rootPrims: root_spec = prim_spec.nameChildren[0] if self._filter_fn and not self._filter_fn(root_spec): carb.log_warn(f"{root_spec.name} is not a valid prim type to paste here, ignoring.") continue prim_path = root_spec.path prim_name = root_spec.name target_path = get_layer_next_free_path( stage, self._root.AppendChild(prim_name).pathString, False ) # Copy to stage Sdf.CopySpec(self._layer, prim_path, target_layer, target_path) paths_map[prim_path] = target_path self._created_paths.append(target_path) for path in self._created_paths: for source_path, target_path in paths_map.items(): update_property_paths(target_layer.GetPrimAtPath(path), source_path, target_path) omni.usd.get_context().get_selection().set_selected_prim_paths(self._created_paths, True) self._layer = None def undo(self): # Delete created DeletePrimsCommand(self._created_paths).do() # Restore selection omni.usd.get_context().get_selection().set_selected_prim_paths(self._selection, False) def get_layer_next_free_path(stage, path, prepend_default_prim, is_batch_editing=True): """This checks both in the stage and in the current edit target layer, since during batch editing, the changes won't have made it to the usd stage yet.""" if prepend_default_prim and stage.HasDefaultPrim(): default_prim = stage.GetDefaultPrim() if default_prim: path = default_prim.GetPath().pathString + path def increment_path(path): match = re.search(r"_(\d+)$", path) if match: new_num = int(match.group(1)) + 1 ret = re.sub(r"_(\d+)$", str.format("_{:02d}", new_num), path) else: ret = path + "_01" return ret while stage.GetPrimAtPath(path): path = increment_path(path) if is_batch_editing: layer = stage.GetEditTarget().GetLayer() while layer.GetPrimAtPath(path): path = increment_path(path) return path
4,341
Python
33.188976
104
0.62451
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .test_copypaste import TestStageCopyPaste from .test_hot_key import * from .test_context_menu import *
536
Python
43.749996
76
0.80597
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/tests/test_copypaste.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pxr import Sdf from pxr import Usd from pxr import UsdGeom import omni.kit.test import omni.usd import omni.kit.undo from ..prim_serializer import get_prim_as_text, _to_layer, text_to_stage sdf_prim_to_text = """#usda 1.0 def "Item_00" { def Sphere "Sphere01" { } } """ sdf_duplicate_name = """#usda 1.0 def "Item_00" { def Sphere "Sphere01" { } } def "Item_01" { def Sphere "Sphere01" { } } """ sdf_preserve_relationships = """#usda 1.0 def "Item_00" { def Sphere "Sphere01" { custom rel test = </Item_01/Sphere02> } } def "Item_01" { def Sphere "Sphere02" { } } """ # This usda has 2 incoming connections on the first node, and an internal # connection between the 2 nodes on the 2nd node. delete_external_connections = """#usda 1.0 def "Item_00" { def OmniGraphNode "add_01" ( apiSchemas = ["NodeGraphNodeAPI"] ) { custom token inputs:a token inputs:a.connect = </World/ActionGraph/add.outputs:sum> custom token inputs:b token inputs:b.connect = </World/ActionGraph/read_time.outputs:frame> token node:type = "omni.graph.nodes.Add" int node:typeVersion = 1 custom token outputs:sum uniform float2 ui:nodegraph:node:pos = (617.9488, -19.670042) } } def "Item_01" { def OmniGraphNode "scale_to_size_01" ( apiSchemas = ["NodeGraphNodeAPI"] ) { custom double inputs:speed = 1 double inputs:speed.connect = </Item_00/add_01.outputs:sum> token node:type = "omni.graph.nodes.ScaleToSize" uniform float2 ui:nodegraph:node:pos = (882.75476, 398.3356) } } """ class TestStageCopyPaste(omni.kit.test.AsyncTestCase): async def test_prim_to_text(self): """Testing how only one prim can be converted to text""" stage = Usd.Stage.CreateInMemory() path = Sdf.Path("/Sphere01") UsdGeom.Sphere.Define(stage, path) UsdGeom.Sphere.Define(stage, "/Sphere02") # Extract only one prim result = get_prim_as_text(stage, [path]) # Linux line endings result = "\n".join(result.splitlines()) self.assertEqual(result, sdf_prim_to_text) async def test_text_to_stage(self): """Testing converting text to layer and import to stage""" await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() path = Sdf.Path("/Sphere01") UsdGeom.Sphere.Define(stage, path) UsdGeom.Xform.Define(stage, "/root_for_import") import_root_prim = stage.GetPrimAtPath("/root_for_import") # test that invalid text returns False self.assertFalse(text_to_stage(stage, "asdf", root=import_root_prim.GetPath())) self.assertFalse(import_root_prim.GetChildren()) # test import to specific root text_to_stage(stage, sdf_prim_to_text, root=import_root_prim.GetPath()) self.assertEqual(len(import_root_prim.GetChildren()), 1) child = import_root_prim.GetChildren()[0] self.assertEqual(child.GetName(), "Sphere01") omni.kit.undo.undo() # test import to default root text_to_stage(stage, sdf_prim_to_text) self.assertFalse(import_root_prim.GetChildren()) imported = stage.GetPrimAtPath("/Item_00") self.assertIsNotNone(imported) omni.kit.undo.undo() async def test_duplicate_name(self): """Testing the ability to copy two prims with the same name and different paths""" stage = Usd.Stage.CreateInMemory() path1 = Sdf.Path("/Sphere01") UsdGeom.Sphere.Define(stage, path1) path2 = Sdf.Path("/Parent/Sphere01") UsdGeom.Sphere.Define(stage, path2) # Serialize prims result = get_prim_as_text(stage, [path1, path2]) # Linux line endings result = "\n".join(result.splitlines()) self.assertEqual(result, sdf_duplicate_name) async def test_preserve_relationships(self): """Testing relationship target updates when copying multiple prims""" stage = Usd.Stage.CreateInMemory() path1 = Sdf.Path("/Sphere01") sphere1 = UsdGeom.Sphere.Define(stage, path1) path2 = Sdf.Path("/Sphere02") UsdGeom.Sphere.Define(stage, path2) rel = sphere1.GetPrim().CreateRelationship("test") rel.SetTargets([path2]) # Serialize prims result = get_prim_as_text(stage, [path1, path2]) # Linux line endings result = "\n".join(result.splitlines()) self.assertEqual(result, sdf_preserve_relationships) async def test_delete_external_connections(self): """Testing that external connections are removed, but internal connections remain""" layer = _to_layer(delete_external_connections, keep_inputs=False) root_prims = layer.rootPrims self.assertIsNotNone(root_prims) # Check to make sure the incoming connections are gone prim_spec = root_prims[0].nameChildren[0] num_connections = 0 for attr in prim_spec.attributes: connections = attr.connectionPathList.explicitItems if connections: num_connections += len(connections) self.assertEqual(num_connections, 0) # Check to make sure the internal connection is there still prim_spec = root_prims[1].nameChildren[0] num_connections = 0 for attr in prim_spec.attributes: connections = attr.connectionPathList.explicitItems if connections: num_connections += len(connections) self.assertEqual(num_connections, 1)
6,126
Python
28.887805
92
0.64365
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/tests/test_context_menu.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 pxr import UsdGeom import omni.kit.test from omni.kit.test_suite.helpers import arrange_windows import omni.kit.ui_test as ui_test class TestContextMenu(omni.kit.test.AsyncTestCase): async def setUp(self): await arrange_windows("Stage", 800, 600) await omni.usd.get_context().new_stage_async() self.stage = omni.usd.get_context().get_stage() async def tearDown(self): await omni.usd.get_context().close_stage_async() def _find_prim_item(self, text): # TODO: not sure why there's two items with the same realpath in the stage window, for now pick the first one item = ui_test.find_all(f"Stage//Frame/**/Label[*].text=='{text}'")[0] self.assertTrue(item) return item async def test_copy_prim(self): """Test that copy prim context menu copies selected prims.""" from .test_copypaste import sdf_prim_to_text UsdGeom.Sphere.Define(self.stage, "/Sphere01") await ui_test.human_delay(20) sphere = self._find_prim_item("Sphere01") await sphere.right_click() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertTrue("Copy Prim" in context_options) await ui_test.select_context_menu("Copy Prim") text = omni.kit.clipboard.paste() # Linux line endings result = "\n".join(text.splitlines()) self.assertEqual(result, sdf_prim_to_text) async def test_paste_prim(self): """Test that paste prim context menu pastes copied prims.""" from .test_copypaste import sdf_prim_to_text UsdGeom.Xform.Define(self.stage, "/root") await ui_test.human_delay(20) # prepare the clipboard with invalid content omni.kit.clipboard.copy("dummy") root = self._find_prim_item("root") await root.right_click() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertTrue("Paste Prim" in context_options) # test that pasting invalid content doesn't error await ui_test.select_context_menu("Paste Prim") self.assertFalse(self.stage.GetPrimAtPath("/root").GetChildren()) # prepare valid clipboard content omni.kit.clipboard.copy(sdf_prim_to_text) # test that pasting valid content works as expected await root.right_click() await ui_test.select_context_menu("Paste Prim") self.assertEqual(len(self.stage.GetPrimAtPath("/root").GetChildren()), 1) self.assertIsNotNone(self.stage.GetPrimAtPath("/root/Sphere01"))
3,062
Python
39.839999
117
0.674069
omniverse-code/kit/exts/omni.kit.stage.copypaste/omni/kit/stage/copypaste/tests/test_hot_key.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 pxr import UsdGeom import omni.kit.test import omni.usd import omni.kit.clipboard import omni.kit.ui_test as ui_test class TestHotKey(omni.kit.test.AsyncTestCase): async def setUp(self): await omni.usd.get_context().new_stage_async() self.stage = omni.usd.get_context().get_stage() async def tearDown(self): await omni.usd.get_context().close_stage_async() async def _test_copy(self, prim_paths, text_to_compare): """Utility for testing copy.""" usd_context = omni.usd.get_context() selection = usd_context.get_selection() selection.set_selected_prim_paths(prim_paths, True) await ui_test.emulate_key_combo("CTRL+C") await ui_test.human_delay() text = omni.kit.clipboard.paste() # Linux line endings result = "\n".join(text.splitlines()) self.assertEqual(result, text_to_compare) async def test_copy(self): """Testing CTRL+C for copy""" from .test_copypaste import sdf_prim_to_text UsdGeom.Sphere.Define(self.stage, "/Sphere01") UsdGeom.Sphere.Define(self.stage, "/Sphere02") await self._test_copy(["/Sphere01"], sdf_prim_to_text) async def test_paste(self): """Testing CTRL+V for paste""" UsdGeom.Sphere.Define(self.stage, "/Sphere01") omni.kit.clipboard.copy("dummy") # test that when invalid string is in the clipboard, paste doesn't do anything await ui_test.emulate_key_combo("CTRL+V") await ui_test.human_delay() self.assertEqual(len(self.stage.GetPseudoRoot().GetChildren()), 1) # select prim and copy usd_context = omni.usd.get_context() selection = usd_context.get_selection() selection.set_selected_prim_paths(["/Sphere01"], True) await ui_test.emulate_key_combo("CTRL+C") await ui_test.human_delay() # test that prim is pasted await ui_test.emulate_key_combo("CTRL+V") await ui_test.human_delay() self.assertEqual(len(self.stage.GetPseudoRoot().GetChildren()), 2) # when pasted with a duplicated name, it will be suffixed with a number self.assertIsNotNone(self.stage.GetPrimAtPath("/Sphere01_01"))
2,675
Python
35.657534
86
0.670654
omniverse-code/kit/exts/omni.kit.stage.copypaste/docs/CHANGELOG.md
# CHANGELOG The ability to copy and paste USD Prims. ## [1.0.4] - 2022-11-17 ### Changed - Switched out pyperclip for more linux-friendly copy & paste ## [1.0.3] - 2021-06-17 ### Changed - Properly linted ## [1.0.2] - 2021-06-04 ### Changed - Handle copying duplicate prim names - Preserve relationships and connections between copied prims - Made paste operation happen in a single change block ## [1.0.1] - 2021-04-09 ### Added - Context menu "Copy Prim" and "Paste Prim" in Stage windows ## [1.0.0] - 2021-04-08 ### Added - Ctrl-C to copy selection, Ctrl-V to paste it
578
Markdown
21.26923
61
0.686851
omniverse-code/kit/exts/omni.kit.stage.copypaste/docs/README.md
# Copy and paste USD Prims. This extension activates Ctrl-C to copy the selected prim to the clipboard and Ctrl-V to paste copied prim to the current stage.
159
Markdown
25.666662
74
0.779874
omniverse-code/kit/exts/omni.kit.window.images/PACKAGE-LICENSES/omni.kit.window.images-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.images/config/extension.toml
[package] version = "0.2.0" title = "Kit Images testing Widget" category = "Internal" [dependencies] "omni.ui" = {} "omni.kit.pip_archive" = {} [[python.module]] name = "omni.kit.window.images" [python.pipapi] requirements = ["numpy"] [[native.plugin]] search_path = "bin/*.plugin" [[test]] unreliable = true waiver = "Simple example extension" # OM-48130
362
TOML
14.782608
46
0.671271
omniverse-code/kit/exts/omni.kit.window.images/omni/kit/window/images/__init__.py
from .scripts.extension import *
33
Python
15.999992
32
0.787879
omniverse-code/kit/exts/omni.kit.window.images/omni/kit/window/images/scripts/extension.py
import os import carb import carb.profiler import omni.ext import omni.ui WINDOW_NAME = "Images testing" class ImagesWindow: def _update_byte_image(self): import math size_increase = max(16.0 * math.sin(self._time), 0.0) size_x = (int)(32 + size_increase) size_y = (int)(32 + size_increase) byte_data = [] byte_data_float = [] for x in range(size_x): for y in range(size_y): color = int(255 * (math.sin(self._time + 0.01 * (x * x + y * y)) * 0.4 + 0.6)) color_float = math.sin(self._time + 0.01 * (x * x + y * y)) * 0.4 + 0.6 byte_data.extend([0, color, 0, color]) byte_data_float.extend([color_float, color_float, 0, color_float]) self._time += 100.0 # This will call version that uses byte array, and has a default format omni.ui.TextureFormat.RGBA8_UNORM self._byte_provider.set_bytes_data(byte_data, [size_x, size_y]) # This will call version that uses array of floating point numbers, and has a default format omni.ui.TextureFormat.RGBA32_SFLOAT self._byte_provider_float.set_bytes_data(byte_data_float, [size_x, size_y]) def _update_dynamic_frame(self): self._raster_provider_dynamic = omni.ui.RasterImageProvider() self._raster_provider_dynamic.source_url = r"${exe-path}/resources/icons/material.png" with self._dynamic_frame: self._img2_dynamic = omni.ui.ImageWithProvider(self._raster_provider_dynamic) def startup(self): carb.profiler.begin(1, "Creating explicit image providers") self._window = omni.ui.Window(WINDOW_NAME, width=600, height=340) self._time = 0.0 self._byte_provider = omni.ui.ByteImageProvider() self._byte_provider_float = omni.ui.ByteImageProvider() self._update_byte_image() self._raster_provider = omni.ui.RasterImageProvider() self._raster_provider.source_url = r"${exe-path}/resources/icons/material.png" self._vector_provider = omni.ui.VectorImageProvider() self._vector_provider.source_url = r"${exe-path}/resources/glyphs/toolbar_select_prim.svg" carb.log_warn("image: %dx%d" % (self._vector_provider.width, self._vector_provider.height)) carb.profiler.end(1) styles = [ { "": {"image_url": "resources/icons/Nav_Walkmode.png"}, ":hovered": {"image_url": "resources/icons/Nav_Flymode.png"}, }, { "": {"image_url": "resources/icons/Move_local_64.png"}, ":hovered": {"image_url": "resources/icons/Move_64.png"}, }, { "": {"image_url": "resources/icons/Rotate_local_64.png"}, ":hovered": {"image_url": "resources/icons/Rotate_global.png"}, }, ] carb.profiler.begin(1, "Building UI") def set_image(model, image): value = model.get_item_value_model().get_value_as_int() image.set_style(styles[value]) with self._window.frame: with omni.ui.VStack(): with omni.ui.HStack(): with omni.ui.HStack(): self._img1 = omni.ui.ImageWithProvider(self._byte_provider) self._img1_float = omni.ui.ImageWithProvider(self._byte_provider_float) self._btn1update = omni.ui.Button(text="Update") self._btn1update.set_clicked_fn(self._update_byte_image) with omni.ui.HStack(): self._img2 = omni.ui.ImageWithProvider(self._raster_provider) self._dynamic_frame = omni.ui.Frame(width=100, height=100) self._btn2refresh = omni.ui.Button(text="Refresh") self._btn2refresh.set_clicked_fn(self._update_dynamic_frame) self._img3 = omni.ui.ImageWithProvider(self._vector_provider) self._img4 = omni.ui.ImageWithProvider(r"${exe-path}/resources/glyphs/timeline_loop.svg") self._img6 = omni.ui.ImageWithProvider(width=64, height=64, style=styles[0]) with omni.ui.HStack(width=omni.ui.Percent(50)): omni.ui.Label("Select a texture to display", name="text") model = omni.ui.ComboBox(0, "Navigation", "Move", "Rotate").model model.add_item_changed_fn(lambda m, i, im=self._img6: set_image(m, im)) carb.profiler.end(1) def shutdown(self): self._img1 = None self._img1_float = None self._img2 = None self._img3 = None self._img4 = None self._img6 = None self._byte_provider = None self._raster_provider = None self._vector_provider = None self._window = None class Extension(omni.ext.IExt): def __init__(self): super().__init__() pass def on_startup(self): self._ext_window = ImagesWindow() self._ext_window.startup() def on_shutdown(self): self._ext_window.shutdown() self._ext_window = None
5,170
Python
38.776923
136
0.573501
omniverse-code/kit/exts/omni.kit.widget.filter/omni/kit/widget/filter/style.py
from pathlib import Path from omni import ui from omni.ui import color as cl CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"data/icons") UI_STYLE = { "FilterButton": {"background_color": 0, "margin_width": 0, "padding": 2, "border_radius": 2}, "FilterButton:selected": {"background_color": cl.shade(cl('#23211F'))}, "FilterButton.Image": { "background_color": 0x0, "color": cl.shade(cl('#A8A8A8')), "image_url": f"{ICON_PATH}/filter_tint.svg", "alignment": ui.Alignment.CENTER, }, "FilterButton.Image:selected": { "color": cl.shade(cl('#34C7FF')), }, "FilterButton:hovered": {"background_color": 0xFF6E6E6E}, "FilterButton.Carot": {"background_color": cl.shade(cl('#A8A8A8'))}, "FilterButton.Carot:selected": {"background_color": cl.shade(cl('#34C7FF'))}, }
902
Python
35.119999
97
0.638581
omniverse-code/kit/exts/omni.kit.widget.filter/omni/kit/widget/filter/__init__.py
from .filter import FilterButton, FilterModel
46
Python
22.499989
45
0.847826
omniverse-code/kit/exts/omni.kit.widget.filter/omni/kit/widget/filter/filter.py
import asyncio from typing import Optional, Dict, List import carb.events import omni.kit.app from omni.kit.widget.options_menu import OptionsMenu, OptionsModel, OptionItem import omni.ui as ui from .style import UI_STYLE TIME_HOLD_SHOW_MENU = 0.08 class FilterModel(OptionsModel): """ Filter model. """ def __init__(self, option_items: List[OptionItem]): super().__init__("Filter", option_items) class FilterButton: """ A Filter button includes a popup menu for filter options. Kwargs: option_items (List[OptionItem]): Option items. width (ui.Length): Button width. Default ui.Pixel(24). height (ui.Length): Button height. Default ui.Pixel(24). hide_on_click (bool): Hide popup menu if menu item clicked. Default False. menu_width (ui.Length): Width of popup menu item. Default ui.Fraction(1). style (dict): External widget style. Default empty. """ def __init__( self, option_items: List[OptionItem], width: ui.Length = ui.Pixel(24), height: ui.Length = ui.Pixel(24), hide_on_click: bool = False, menu_width: ui.Length = ui.Fraction(1), carot_size: ui.Length = ui.Pixel(3), style: Dict = {}, ): self._options_model = FilterModel(option_items) self._width = width self._height = height self._hide_on_click = hide_on_click self._menu_width = menu_width self._carot_size = carot_size self._style = UI_STYLE.copy() self._style.update(style) self._options_menu: Optional[OptionsMenu] = None self._ignore_next_mouse_release = False self._show_menu_task = None self._saved_options: Dict[OptionItem, bool] = {} self._build_ui() def destroy(self) -> None: self.__sub = None self._options_model.destroy() self._options_model = None if self._options_menu: self._options_menu.destroy() self._options_menu = None @property def model(self) -> FilterModel: """Filter options model""" return self._options_model @property def button(self) -> ui.Button: """FIlter button widget""" return self._button def _build_ui(self) -> None: self._container = ui.ZStack(width=0, height=0, style=self._style) with self._container: self._button = ui.Button( width=self._width, height=self._height, checked=self._options_model.dirty, style_type_name_override="FilterButton", # clicked_fn=lambda: self._show_options_menu(), mouse_pressed_fn=lambda x, y, b, a: self._on_mouse_pressed(b), mouse_released_fn=lambda x, y, b, a: self._on_mouse_released(b), mouse_double_clicked_fn=lambda x, y, b, a: self._on_mouse_double_clicked(b), ) with ui.VStack(): with ui.HStack(): ui.Spacer() with ui.VStack(width=self._carot_size): ui.Spacer() ui.Triangle( width=self._carot_size, height=self._carot_size, alignment=ui.Alignment.RIGHT_TOP, style_type_name_override="FilterButton.Carot", ) ui.Spacer(width=2) ui.Spacer(height=2) self.__sub = self._options_model.subscribe_item_changed_fn(self._on_item_changed) def _on_mouse_pressed(self, btn) -> None: # If options menu already show, just hide self._ignore_next_mouse_release = False if self._options_menu and self._options_menu.shown: self._ignore_next_mouse_release = True else: self._ignore_next_mouse_release = False return def _on_mouse_released(self, btn) -> None: if self._ignore_next_mouse_release: return if btn == 1 or btn == 0: # Schedule a task so double click will interrupt self._show_menu_task = asyncio.ensure_future(self._schedule_show_menu()) elif btn == 2: # Middle button self._toggle_filter() return def _on_mouse_double_clicked(self, btn) -> None: self._ignore_next_mouse_release = True if self._show_menu_task: self._show_menu_task.cancel() self._toggle_filter() def _show_options_menu(self): if self._options_menu is None: self._options_menu = OptionsMenu(self._options_model, hide_on_click=self._hide_on_click, width=self._menu_width) self._options_menu.show_by_widget(self._button) async def _schedule_show_menu(self, ): await asyncio.sleep(TIME_HOLD_SHOW_MENU) self._show_options_menu() self._show_menu_task = None self._ignore_next_mouse_release = True def _toggle_filter(self): if self._container.selected: for item in self._options_model.get_item_children(): self._saved_options[item] = item.value self._options_model.reset() else: for item, value in self._saved_options.items(): item.value = value def _on_item_changed(self, model: OptionsModel, item: OptionItem) -> None: self._container.selected = model.dirty
5,522
Python
33.955696
124
0.566099
omniverse-code/kit/exts/omni.kit.widget.filter/omni/kit/widget/filter/tests/__init__.py
from .test_filter import *
27
Python
12.999994
26
0.740741
omniverse-code/kit/exts/omni.kit.widget.filter/omni/kit/widget/filter/tests/test_filter.py
import asyncio from pathlib import Path from carb.input import MouseEventType import omni.kit.ui_test as ui_test from omni.kit.ui_test.input import emulate_mouse, emulate_mouse_click from omni.ui.tests.test_base import OmniUiTest from omni.kit.widget.options_menu import OptionItem from ..filter import FilterButton, FilterModel CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestFilter(OmniUiTest): # Before running each test async def setUp(self): self._items = [ OptionItem("audio", text="Audio"), OptionItem("materials", text="Materials"), OptionItem("scripts", text="Scripts"), OptionItem("textures", text="Textures"), OptionItem("usd", text="USD"), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden") await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def finalize_test(self, golden_img_name: str): await self.wait_n_updates() await super().finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=golden_img_name) await self.wait_n_updates() async def test_ui(self): """Test initial UI""" window = await self.create_test_window(block_devices=False) with window.frame: FilterButton(self._items) await ui_test.human_delay() await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(20, 20), right_click=False) await asyncio.sleep(0.5) await ui_test.human_delay() await self.finalize_test("filter_initial_ui.png") async def test_dirty_toggle(self): """Test filter settings are dirty""" window = await self.create_test_window(block_devices=False) with window.frame: self._button = FilterButton(self._items) try: # click on first item await ui_test.human_delay() await self.__show_menu(right_click=True) await ui_test.human_delay() await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(60, 72)) await ui_test.human_delay() await self.finalize_test("filter_dirty_ui.png") # hide menu await self.__hide_menu() # Double click to toggle await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(20, 20), double=True) await ui_test.human_delay() items = self._button.model.get_item_children() for item in items: self.assertFalse(item.value) # Middle click to toggle again await ui_test.emulate_mouse_move(ui_test.Vec2(20, 20)) await emulate_mouse(MouseEventType.MIDDLE_BUTTON_DOWN) await ui_test.human_delay() await emulate_mouse(MouseEventType.MIDDLE_BUTTON_UP) await ui_test.human_delay() items = self._button.model.get_item_children() for index, item in enumerate(items): if index == 0: self.assertTrue(item.value) else: self.assertFalse(item.value) finally: await self.__hide_menu() self._button.model.reset() async def __show_menu(self, right_click: bool=False): await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(20, 20), right_click=right_click) await asyncio.sleep(0.1) async def __hide_menu(self): await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(0, 0)) await ui_test.human_delay() await asyncio.sleep(1)
3,721
Python
35.490196
105
0.613545
omniverse-code/kit/exts/omni.kit.widget.filter/docs/index.rst
omni.kit.widget.filter ########################### .. toctree:: :maxdepth: 1 CHANGELOG
97
reStructuredText
8.799999
27
0.453608
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/PACKAGE-LICENSES/omni.kit.viewport_widgets_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.viewport_widgets_manager/config/extension.toml
[package] title = "Viewport Widgets Manager" description = "The viewport widgets manager provides simple API to manage viewport widgets." version = "1.0.6" changelog = "docs/CHANGELOG.md" readme = "docs/README.md" category = "Collaboration" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.kit.viewport.utility" = {} "omni.timeline" = {} [[python.module]] name = "omni.kit.viewport_widgets_manager" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/persistent/app/viewport/displayOptions=0", "--/app/viewport/showSettingMenu=false", "--/app/viewport/showCameraMenu=false", "--/app/viewport/showRendererMenu=false", "--/app/viewport/showHideMenu=false", "--/app/viewport/showLayerMenu=false", "--/app/viewport/hideBuiltinTimeline=true", "--/app/docks/disabled=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/window/width=320", "--/app/window/height=240", "--no-window" ] dependencies = [ "omni.kit.commands", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.test_helpers_gfx", "omni.hydra.pxr", "omni.kit.window.viewport", ]
1,886
TOML
29.934426
118
0.685578
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/omni/kit/viewport_widgets_manager/widget_provider.py
class WidgetProvider: def build_widget(self, window): raise NotImplementedError("This function needs to be implemented.")
134
Python
32.749992
75
0.738806
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/omni/kit/viewport_widgets_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 carb import omni.ext from typing import Union from pxr import Sdf from .manager import ViewportWidgetsManager, WidgetAlignment from .widget_provider import WidgetProvider _global_instance = None class ViewportWidgetsManagerExtension(omni.ext.IExt): def on_startup(self): global _global_instance _global_instance = self self._widgets_manager = ViewportWidgetsManager() self._widgets_manager.start() def on_shutdown(self): global _global_instance _global_instance = None self._widgets_manager.stop() @staticmethod def _get_instance(): global _global_instance return _global_instance def add_widget(self, prim_path: Sdf.Path, widget: WidgetProvider, alignment=WidgetAlignment.CENTER): return self._widgets_manager.add_widget(prim_path, widget, alignment) def remove_widget(self, widget_id): self._widgets_manager.remove_widget(widget_id) def add_widget(prim_path: Union[str, Sdf.Path], widget: WidgetProvider, alignment=WidgetAlignment.CENTER): """Add widget to viewport, which is positioned to the screen pos of prim on the viewport. REMINDER: Currently, it's possible that a prim may includes multiple widgets, and they will be overlapped to each other. Args: prim_path (Union[str, Sdf.Path]): The prim you want to add the widget to. widget (WidgetProvider): The widget provider that you can override to customize the UI layout. alignment: The anchor point of the widget. By default, it will be the calculated by the position of prim. Returns: widget id, which you can use it for widget remove. Or None if prim cannot be found. """ instance = ViewportWidgetsManagerExtension._get_instance() if not instance: carb.log_warn("Extension omni.kit.viewport_widgets_manager is not enabled.") return None return ViewportWidgetsManagerExtension._get_instance().add_widget(Sdf.Path(prim_path), widget, alignment) def remove_widget(widget_id): """ Remove widget with id. Args: widget_id: The widget id returned with add_widget. """ instance = ViewportWidgetsManagerExtension._get_instance() if not instance: carb.log_warn("Extension omni.kit.viewport_widgets_manager is not enabled.") return None return ViewportWidgetsManagerExtension._get_instance().remove_widget(widget_id)
2,954
Python
32.965517
109
0.702776
omniverse-code/kit/exts/omni.kit.viewport_widgets_manager/omni/kit/viewport_widgets_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 ViewportWidgetsManagerExtension, WidgetAlignment, add_widget, remove_widget from .widget_provider import WidgetProvider
577
Python
47.166663
98
0.82149