file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/create_prims.py | import os
import random
import carb
import omni.usd
import omni.kit.commands
from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux
def create_test_stage():
stage = omni.usd.get_context().get_stage()
rootname = stage.GetDefaultPrim().GetPath().pathString
prim_list1 = []
prim_list2 = []
# create Looks folder
omni.kit.commands.execute(
"CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False
)
# create material 1
mtl_created_list = []
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name="OmniPBR.mdl",
mtl_name="OmniPBR",
mtl_created_list=mtl_created_list,
)
mtl_path1 = mtl_created_list[0]
# create material 2
mtl_created_list = []
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name="OmniGlass.mdl",
mtl_name="OmniGlass",
mtl_created_list=mtl_created_list,
)
mtl_path2 = mtl_created_list[0]
# create prims & bind material
random_list = {}
samples = 100
for index in random.sample(range(samples), int(samples / 2)):
random_list[index] = 0
strengths = [UsdShade.Tokens.strongerThanDescendants, UsdShade.Tokens.weakerThanDescendants]
for index in range(samples):
prim_path = omni.usd.get_stage_next_free_path(stage, "{}/TestCube_{}".format(rootname, index), False)
omni.kit.commands.execute("CreatePrim", prim_path=prim_path, prim_type="Cube")
if index in random_list:
omni.kit.commands.execute(
"BindMaterial", prim_path=prim_path, material_path=mtl_path1, strength=strengths[index & 1]
)
prim_list1.append(prim_path)
elif (index & 3) != 0:
omni.kit.commands.execute(
"BindMaterial", prim_path=prim_path, material_path=mtl_path2, strength=strengths[index & 1]
)
prim_list2.append(prim_path)
return [(mtl_path1, prim_list1), (mtl_path2, prim_list2)]
def create_and_select_cube():
stage = omni.usd.get_context().get_stage()
rootname = stage.GetDefaultPrim().GetPath().pathString
prim_path = "{}/Cube".format(rootname)
# create Looks folder
omni.kit.commands.execute(
"CreatePrim", prim_path=prim_path,
prim_type="Cube", select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100}
)
return prim_path
| 2,464 | Python | 31.012987 | 109 | 0.635958 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/context_tests.py | import asyncio
import carb
import omni.usd
import omni.kit.test
import omni.kit.viewport_legacy
import omni.timeline
from pxr import Usd, UsdGeom, Gf, Sdf
from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class ViewportContextTest(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def _create_test_stage(self):
# Create the objects
test_list = omni.kit.viewport_legacy.tests.create_test_stage()
# Wait so that the test does not exit before MDL loaded and crash on exit.
while True:
try:
event, payload = await asyncio.wait_for(self._usd_context.next_stage_event_async(), timeout=60.0)
if event == int(omni.usd.StageEventType.ASSETS_LOADED):
break
except asyncio.TimeoutError:
_, files_loaded, total_files = self._usd_context.get_stage_loading_status()
if files_loaded == total_files:
carb.log_warn("Timed out waiting for ASSETS_LOADED event. Is MDL already loaded?")
break
return test_list
# Simulate a mouse-click-selection at pos (x,y) in viewport
async def _simulate_mouse_selection(self, viewport, pos):
app = omni.kit.app.get_app()
mouse = omni.appwindow.get_default_app_window().get_mouse()
input_provider = carb.input.acquire_input_provider()
async def simulate_mouse_click():
input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.MOVE, pos, 0, pos)
input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.LEFT_BUTTON_DOWN, pos, 0, pos)
await app.next_update_async()
input_provider.buffer_mouse_event(mouse, carb.input.MouseEventType.LEFT_BUTTON_UP, pos, 0, pos)
await app.next_update_async()
# You're guess as good as mine.
# Need to start and end with one wait, then need 12 more waits for mouse click
loop_counts = (1, 5)
for i in range(loop_counts[0]):
await app.next_update_async()
# Is this really to sync up carb and imgui state ?
for i in range(loop_counts[1]):
await simulate_mouse_click()
# Enable picking and do the selection
viewport.request_picking()
await simulate_mouse_click()
# Almost done!
for i in range(loop_counts[0]):
await app.next_update_async()
# Actual test, notice it is "async" function, so "await" can be used if needed
#
# But why does this test exist in Viewport??
async def test_bound_objects(self):
return
# Create the objects
usd_context, test_list = self._usd_context, await self._create_test_stage()
self.assertIsNotNone(usd_context)
self.assertIsNotNone(test_list)
objects = {}
stage = omni.usd.get_context().get_stage()
objects["stage"] = stage
for mtl, mtl_prims in test_list:
# Select material prim
objects["prim_list"] = [stage.GetPrimAtPath(Sdf.Path(mtl))]
# Run select_prims_using_material
omni.kit.context_menu.get_instance().select_prims_using_material(objects)
# Verify selected prims
prims = omni.usd.get_context().get_selection().get_selected_prim_paths()
self.assertTrue(prims == mtl_prims)
async def test_create_and_select(self):
viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface()
viewport = viewport_interface.get_viewport_window()
viewport.set_enabled_picking(True)
viewport.set_window_pos(0, 0)
viewport.set_window_size(400, 400)
# Create the objects
usd_context, cube_path = self._usd_context, omni.kit.viewport_legacy.tests.create_and_select_cube()
self.assertIsNotNone(usd_context)
self.assertIsNotNone(cube_path)
self.assertEqual([], self._usd_context.get_selection().get_selected_prim_paths())
await self._simulate_mouse_selection(viewport, (200, 230))
self.assertEqual([cube_path], self._usd_context.get_selection().get_selected_prim_paths())
| 4,610 | Python | 38.75 | 142 | 0.642082 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/mouse_raycast_tests.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import carb.input
import omni.appwindow
import omni.kit.commands
import omni.kit.test
import omni.kit.viewport_legacy
import omni.usd
from carb.input import KeyboardInput as Key
from omni.kit.test_suite.helpers import arrange_windows
class TestViewportMouseRayCast(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows(hide_viewport=True)
self._input_provider = carb.input.acquire_input_provider()
app_window = omni.appwindow.get_default_app_window()
self._mouse = app_window.get_mouse()
self._keyboard = app_window.get_keyboard()
self._app = omni.kit.app.get_app()
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface()
self._viewport = viewport_interface.get_viewport_window()
self._viewport.set_enabled_picking(True)
self._viewport.set_window_pos(0, 0)
self._viewport.set_window_size(400, 400)
self._viewport.show_hide_window(True)
await self._app.next_update_async()
# After running each test
async def tearDown(self):
pass
async def test_viewport_mouse_raycast(self):
stage_update = omni.stageupdate.get_stage_update_interface()
stage_subscription = stage_update.create_stage_update_node(
"viewport_mouse_raycast_test", on_raycast_fn=self._on_ray_cast
)
test_data = [
(
"/OmniverseKit_Persp",
(499.058, 499.735, 499.475),
(-0.848083, -0.23903, -0.472884),
),
(
"/OmniverseKit_Front",
(-127.551, 165.44, 30000),
(0, 0, -1),
),
(
"/OmniverseKit_Top",
(127.551, 30000, 165.44),
(0, -1, 0),
),
(
"/OmniverseKit_Right",
(-30000, 165.44, -127.551),
(1, 0, 0),
),
]
for data in test_data:
self._raycast_data = None
self._viewport.set_active_camera(data[0])
await self._app.next_update_async()
self._input_provider.buffer_mouse_event(
self._mouse, carb.input.MouseEventType.MOVE, (100, 100), 0, (100, 100)
)
await self._app.next_update_async()
# Hold SHIFT down to start raycast
self._input_provider.buffer_keyboard_key_event(
self._keyboard, carb.input.KeyboardEventType.KEY_PRESS, Key.LEFT_SHIFT, 0
)
await self._app.next_update_async()
self._input_provider.buffer_keyboard_key_event(
self._keyboard, carb.input.KeyboardEventType.KEY_RELEASE, Key.LEFT_SHIFT, 0
)
await self._app.next_update_async()
self._input_provider.buffer_mouse_event(self._mouse, carb.input.MouseEventType.MOVE, (0, 0), 0, (0, 0))
await self._app.next_update_async()
self.assertIsNotNone(self._raycast_data)
self.assertAlmostEqual(self._raycast_data[0][0], data[1][0], 3)
self.assertAlmostEqual(self._raycast_data[0][1], data[1][1], 3)
self.assertAlmostEqual(self._raycast_data[0][2], data[1][2], 3)
self.assertAlmostEqual(self._raycast_data[1][0], data[2][0], 3)
self.assertAlmostEqual(self._raycast_data[1][1], data[2][1], 3)
self.assertAlmostEqual(self._raycast_data[1][2], data[2][2], 3)
stage_subscription = None
def _on_ray_cast(self, orig, dir, input):
self._raycast_data = (orig, dir)
print(self._raycast_data)
| 4,239 | Python | 35.551724 | 115 | 0.598726 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/drag_drop_multi_material_viewport.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
import omni.kit.test
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class ZZViewportDragDropMaterialMulti(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
def _verify_material(self, stage, mtl_name, to_select):
# verify material created
prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()]
self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths)
self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths)
# verify bound material
if to_select:
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertEqual(bound_material.GetPrim().IsValid(), True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, f"/World/Looks/{mtl_name}")
def choose_material(self, mdl_list, excluded_list):
# need to skip any multi-subid materials
exclude_multi = {}
for _, mdl_path, _ in mdl_list:
mdl_name = os.path.splitext(os.path.basename(mdl_path))[0]
if not mdl_name in exclude_multi:
exclude_multi[mdl_name] = 1
else:
exclude_multi[mdl_name] += 1
for _, mdl_path, _ in mdl_list:
mdl_name = os.path.splitext(os.path.basename(mdl_path))[0]
if mdl_name not in excluded_list and exclude_multi[mdl_name] < 2:
return mdl_path, mdl_name
return None, None
async def test_l1_drag_drop_single_material_viewport(self):
from carb.input import KeyboardInput
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"]
await wait_stage_loading()
# verify bound materials before DnD
for prim_path, material_path in [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", "/World/Looks/OmniPBR"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")]:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertEqual(bound_material.GetPrim().IsValid(), True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path)
# drag to center of viewport window
# NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used viewport_window = ui_test.find("Viewport")
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
drag_target = viewport_window.center
# select prim
await select_prims(to_select)
# wait for UI to update
await ui_test.human_delay()
# get paths
mdl_list = await omni.kit.material.library.get_mdl_list_async()
mdl_path1, mdl_name = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"])
# drag and drop items from the tree view of content browser
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.drag_and_drop_tree_view(mdl_path1, drag_target=drag_target)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify bound materials after DnD - Should be unchanged
for prim_path, material_path in [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", f"/World/Looks/{mdl_name}"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")]:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertEqual(bound_material.GetPrim().IsValid(), True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path)
async def test_l1_drag_drop_multi_material_viewport(self):
from carb.input import KeyboardInput
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"]
expected_list = [("/World/Cube", "/World/Looks/OmniGlass"), ("/World/Cone", "/World/Looks/OmniPBR"), ("/World/Sphere", "/World/Looks/OmniGlass"), ("/World/Cylinder", "/World/Looks/OmniPBR")]
await wait_stage_loading()
# verify bound materials before DnD
for prim_path, material_path in expected_list:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertEqual(bound_material.GetPrim().IsValid(), True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path)
# drag to center of viewport window
# NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
drag_target = viewport_window.center
# select prim
await select_prims(to_select)
# wait for UI to update
await ui_test.human_delay()
# get paths
mdl_list = await omni.kit.material.library.get_mdl_list_async()
mdl_path1, mdl_name1 = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"])
mdl_path2, mdl_name2 = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR", mdl_name1])
# drag and drop items from the tree view of content browser
async with ContentBrowserTestHelper() as content_browser_helper:
dir_url = os.path.dirname(os.path.commonprefix([mdl_path1, mdl_path2]))
filenames = [os.path.basename(url) for url in [mdl_path1, mdl_path2]]
await content_browser_helper.drag_and_drop_tree_view(dir_url, names=filenames, drag_target=drag_target)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify bound materials after DnD - Should be unchanged
for prim_path, material_path in expected_list:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertEqual(bound_material.GetPrim().IsValid(), True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, material_path)
| 7,880 | Python | 46.475903 | 219 | 0.65698 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/window_tests.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.test
from omni.kit.viewport.utility import get_active_viewport_window
class TestViewportWindowShowHide(omni.kit.test.AsyncTestCase):
async def test_window_show_hide(self):
# Test that multiple show-hide invocations of a window doesn't crash
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
# Show hide 10 times, and wait 60 frames between a show hide
# This does make the test take 10 seconds, but might be a bit
# more representative of real-world usage when it.
nwaits = 60
nitrations = 10
viewport, viewport_window = get_active_viewport_window()
for x in range(nitrations):
viewport_window.visible = True
for x in range(nwaits):
await omni.kit.app.get_app().next_update_async()
viewport_window.visible = False
for x in range(nwaits):
await omni.kit.app.get_app().next_update_async()
for x in range(nitrations):
viewport_window.visible = False
for x in range(nwaits):
await omni.kit.app.get_app().next_update_async()
viewport_window.visible = True
for x in range(nwaits):
await omni.kit.app.get_app().next_update_async()
| 1,774 | Python | 40.279069 | 76 | 0.666291 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/__init__.py | from .draw_tests import *
from .context_tests import *
from .create_prims import *
from .camera_tests import *
from .mouse_raycast_tests import *
# these tests must be last or test_viewport_mouse_raycast fails.
from .multi_descendents_dialog import *
from .drag_drop_multi_material_viewport import *
from .drag_drop_looks_material_viewport import *
| 349 | Python | 33.999997 | 64 | 0.776504 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/draw_tests.py | import carb.dictionary
import omni.usd
import omni.kit.test
import omni.kit.viewport_legacy
import omni.timeline
from pxr import Usd, UsdGeom, Gf, Sdf
from omni.kit.test_suite.helpers import arrange_windows
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class ViewportDrawTest(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_ui_draw_event_payload(self):
dictionary_interface = carb.dictionary.get_dictionary()
viewport_interface = omni.kit.viewport_legacy.acquire_viewport_interface()
viewport = viewport_interface.get_viewport_window()
draw_event_stream = viewport.get_ui_draw_event_stream()
CAM_PATH = "/OmniverseKit_Persp"
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
cam_prim = stage.GetPrimAtPath(CAM_PATH)
camera = UsdGeom.Camera(cam_prim)
timeline_interface = omni.timeline.get_timeline_interface()
timecode = timeline_interface.get_current_time() * stage.GetTimeCodesPerSecond()
gf_camera = camera.GetCamera(timecode)
expected_transform = gf_camera.transform
expected_viewport_rect = viewport.get_viewport_rect()
def uiDrawCallback(event):
events_data = dictionary_interface.get_dict_copy(event.payload)
vm = events_data["viewMatrix"]
viewMatrix = Gf.Matrix4d(
vm[0],
vm[1],
vm[2],
vm[3],
vm[4],
vm[5],
vm[6],
vm[7],
vm[8],
vm[9],
vm[10],
vm[11],
vm[12],
vm[13],
vm[14],
vm[15],
).GetInverse()
self.assertTrue(Gf.IsClose(expected_transform, viewMatrix, 0.00001))
vr = events_data["viewportRect"]
self.assertAlmostEqual(expected_viewport_rect[0], vr[0])
self.assertAlmostEqual(expected_viewport_rect[1], vr[1])
self.assertAlmostEqual(expected_viewport_rect[2], vr[2])
self.assertAlmostEqual(expected_viewport_rect[3], vr[3])
subscription = draw_event_stream.create_subscription_to_pop(uiDrawCallback)
await omni.kit.app.get_app().next_update_async()
| 2,646 | Python | 36.28169 | 142 | 0.608466 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/drag_drop_looks_material_viewport.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
import omni.kit.test
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class ZZViewportDragDropMaterialLooks(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await omni.usd.get_context().new_stage_async()
# After running each test
async def tearDown(self):
await wait_stage_loading()
def choose_material(self, mdl_list, excluded_list):
for _, mdl_path, _ in mdl_list:
mdl_name = os.path.splitext(os.path.basename(mdl_path))[0]
if mdl_name not in excluded_list:
return mdl_path, mdl_name
return None, None
async def test_l1_drag_drop_single_material_viewport_looks(self):
from carb.input import KeyboardInput
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create default prim
omni.kit.commands.execute("CreatePrim", prim_path="/World", prim_type="Xform", select_new_prim=False)
stage.SetDefaultPrim(stage.GetPrimAtPath("/World"))
# drag to center of viewport window
# NOTE: Material binding is only done if dropped over prim. This just creates materials as center coordinates are used
viewport_window = ui_test.find("Viewport")
await viewport_window.focus()
drag_target = viewport_window.center
# get paths
mdl_list = await omni.kit.material.library.get_mdl_list_async()
mdl_path1, mdl_name = self.choose_material(mdl_list, excluded_list=["OmniGlass", "OmniPBR"])
# drag and drop items from the tree view of content browser
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.drag_and_drop_tree_view(mdl_path1, drag_target=drag_target)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify /World/Looks type after drag/drop
prim = stage.GetPrimAtPath("/World/Looks")
self.assertEqual(prim.GetTypeName(), "Scope")
| 2,792 | Python | 38.899999 | 126 | 0.698782 |
omniverse-code/kit/exts/omni.kit.window.viewport/omni/kit/viewport_legacy/tests/multi_descendents_dialog.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.test
import omni.usd
import omni.ui as ui
from omni.kit.test.async_unittest import AsyncTestCase
from pxr import Sdf, UsdShade
from omni.kit import ui_test
from omni.kit.viewport.utility import get_ui_position_for_prim
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from omni.kit.test_suite.helpers import (
arrange_windows,
open_stage,
get_test_data_path,
wait_stage_loading,
handle_multiple_descendents_dialog,
Vec2
)
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
# has to be last or test_viewport_mouse_raycast fails.
class ZZMultipleDescendentsDragDropTest(AsyncTestCase):
# Before running each test
async def setUp(self):
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.ui_test", True)
manager.set_extension_enabled_immediate("omni.kit.window.status_bar", True)
manager.set_extension_enabled_immediate("omni.kit.window.content_browser", True)
# load stage
await open_stage(get_test_data_path(__name__, "empty_stage.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_material_viewport(self):
viewport_window = await arrange_windows(topleft_width=0)
ui_test_window = ui_test.find("Viewport")
await ui_test_window.focus()
# get single and multi-subid materials
single_material = None
multi_material = None
mdl_list = await omni.kit.material.library.get_mdl_list_async()
for mtl_name, mdl_path, submenu in mdl_list:
if "Presets" in mdl_path or "Base" in mdl_path:
continue
if not single_material and not submenu:
single_material = (mtl_name, mdl_path)
if not multi_material and submenu:
multi_material = (mtl_name, mdl_path)
# verify both tests have run
self.assertTrue(single_material != None)
self.assertTrue(multi_material != None)
async def verify_prims(stage, mtl_name, verify_prim_list):
# verify material
prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()]
self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths)
self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths)
# verify bound material
if verify_prim_list:
for prim_path in verify_prim_list:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}")
# undo
omni.kit.undo.undo()
# verify material was removed
prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()]
self.assertFalse(f"/World/Looks/{mtl_name}" in prim_paths)
async def test_mtl(stage, material, verify_prim_list, drag_target):
mtl_name, mdl_path = material
# drag and drop items from the tree view of content browser
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# handle create material dialog
async with MaterialLibraryTestHelper() as material_library_helper:
await material_library_helper.handle_create_material_dialog(mdl_path, mtl_name)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify created/bound prims
await verify_prims(stage, mtl_name, verify_prim_list)
async def test_multiple_descendents_mtl(stage, material, multiple_descendents_prim, target_prim, drag_target):
mtl_name, mdl_path = material
# drag and drop items from the tree view of content browser
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# use multiple descendents dialog
await handle_multiple_descendents_dialog(stage, multiple_descendents_prim, target_prim)
# handle create material dialog
async with MaterialLibraryTestHelper() as material_library_helper:
await material_library_helper.handle_create_material_dialog(mdl_path, mtl_name)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify created/bound prims
await verify_prims(stage, mtl_name, [target_prim])
# test DnD single & multi subid material from Content window to centre of viewport - Create material
stage = omni.usd.get_context().get_stage()
drag_target = ui_test_window.center
await test_mtl(stage, single_material, [], drag_target)
await test_mtl(stage, multi_material, [], drag_target)
# load stage with multi-descendent prim
await open_stage(get_test_data_path(__name__, "multi-material-object-cube-component.usda"))
await wait_stage_loading()
# test DnD single & multi subid material from Content window to /World/Sphere - Create material & Binding
stage = omni.usd.get_context().get_stage()
verify_prim_list = ["/World/Sphere"]
drag_target, valid = get_ui_position_for_prim(viewport_window, verify_prim_list[0])
drag_target = Vec2(drag_target[0], drag_target[1])
await test_mtl(stage, single_material, verify_prim_list, drag_target)
await test_mtl(stage, multi_material, verify_prim_list, drag_target)
# test DnD single & multi subid material from Content window to /World/pCube1 targeting each descendent - Create material & Binding
stage = omni.usd.get_context().get_stage()
multiple_descendents_prim = "/World/pCube1"
descendents = ["/World/pCube1", "/World/pCube1/front1", "/World/pCube1/side1", "/World/pCube1/back", "/World/pCube1/side2", "/World/pCube1/top1", "/World/pCube1/bottom"]
drag_target, valid = get_ui_position_for_prim(viewport_window, multiple_descendents_prim)
drag_target = Vec2(drag_target[0], drag_target[1])
for target_prim in descendents:
await test_multiple_descendents_mtl(stage, single_material, multiple_descendents_prim, target_prim, drag_target)
await test_multiple_descendents_mtl(stage, multi_material, multiple_descendents_prim, target_prim, drag_target)
| 7,382 | Python | 46.025477 | 177 | 0.670144 |
omniverse-code/kit/exts/omni.inspect/omni/inspect/__init__.py | """
Contains interfaces for inspecting values used within other interfaces
"""
# Required to be able to instantiate the object types
import omni.core
# Interface from the ABI bindings
from ._omni_inspect import IInspectJsonSerializer
from ._omni_inspect import IInspectMemoryUse
from ._omni_inspect import IInspectSerializer
from ._omni_inspect import IInspector
| 364 | Python | 29.416664 | 70 | 0.815934 |
omniverse-code/kit/exts/omni.inspect/omni/inspect/tests/test_bindings.py | """Suite of tests to exercise the bindings exposed by omni.inspect"""
import omni.kit.test
import omni.inspect as oi
from pathlib import Path
import tempfile
# ==============================================================================================================
class TestOmniInspectBindings(omni.kit.test.AsyncTestCase):
"""Wrapper for tests to verify functionality in the omni.inspect bindings module"""
# ----------------------------------------------------------------------
def __test_inspector_api(self, inspector: oi.IInspector):
"""Run tests on flags common to all inspector types
API surface being tested:
omni.inspect.IInspector
@help, help_flag, help_information, is_flag_set, set_flag
"""
HELP_FLAG = "help"
HELP_INFO = "This is some help"
self.assertEqual(inspector.help_flag(), HELP_FLAG)
self.assertFalse(inspector.is_flag_set(HELP_FLAG))
inspector.help = HELP_INFO
self.assertEqual(inspector.help_information(), HELP_INFO)
inspector.set_flag("help", True)
self.assertTrue(inspector.is_flag_set(HELP_FLAG))
inspector.set_flag("help", False)
inspector.set_flag("Canadian", True)
self.assertFalse(inspector.is_flag_set(HELP_FLAG))
self.assertTrue(inspector.is_flag_set("Canadian"))
# ----------------------------------------------------------------------
async def test_memory_inspector(self):
"""Test features only available to the memory usage inspector
API surface being tested:
omni.inspect.IInspectMemoryUse
[omni.inspect.IInspector]
reset, total_used, use_memory
"""
inspector = oi.IInspectMemoryUse()
self.__test_inspector_api(inspector)
self.assertEqual(inspector.total_used(), 0)
self.assertTrue(inspector.use_memory(inspector, 111))
self.assertTrue(inspector.use_memory(inspector, 222))
self.assertTrue(inspector.use_memory(inspector, 333))
self.assertEqual(inspector.total_used(), 666)
inspector.reset()
self.assertEqual(inspector.total_used(), 0)
# ----------------------------------------------------------------------
async def test_serializer(self):
"""Test features only available to the shared serializer types
API surface being tested:
omni.inspect.IInspectSerializer
[omni.inspect.IInspector]
as_string, clear, output_location, output_to_file_path, set_output_to_string, write_string
"""
inspector = oi.IInspectSerializer()
self.__test_inspector_api(inspector)
self.assertEqual(inspector.as_string(), "")
TEST_STRINGS = [
"This is line 1",
"This is line 2",
]
# Test string output
inspector.write_string(TEST_STRINGS[0])
self.assertEqual(inspector.as_string(), TEST_STRINGS[0])
inspector.write_string(TEST_STRINGS[1])
self.assertEqual(inspector.as_string(), "".join(TEST_STRINGS))
inspector.clear()
self.assertEqual(inspector.as_string(), "")
# Test file output
with tempfile.TemporaryDirectory() as tmp:
test_output_file = Path(tmp) / "test_serializer.txt"
# Get the temp file path and test writing a line to it
inspector.output_to_file_path = str(test_output_file)
inspector.write_string(TEST_STRINGS[0])
self.assertEqual(inspector.as_string(), TEST_STRINGS[0])
# Set output back to string and check the temp file contents manually
inspector.set_output_to_string()
file_contents = open(test_output_file, "r").readlines()
self.assertEqual(file_contents, [TEST_STRINGS[0]])
# ----------------------------------------------------------------------
async def test_json_serializer(self):
"""Test features only available to the JSON serializer type
API surface being tested:
omni.inspect.IInspectJsonSerializer
[omni.inspect.IInspector]
as_string, clear, close_array, close_object, finish, open_array, open_object, output_location,
output_to_file_path, set_output_to_string, write_base64_encoded, write_bool,
write_double, write_float, write_int, write_int64, write_key, write_key_with_length, write_null,
write_string, write_string_with_length, write_u_int, write_u_int64
"""
inspector = oi.IInspectJsonSerializer()
self.__test_inspector_api(inspector)
self.assertEqual(inspector.as_string(), "")
self.assertTrue(inspector.open_array())
self.assertTrue(inspector.close_array())
self.assertEqual(inspector.as_string(), "[\n]")
inspector.clear()
self.assertEqual(inspector.as_string(), "")
# Note: There's what looks like a bug in the StructuredLog JSON output that omits the space before
# a base64_encoded value. If that's ever fixed the first entry in the dictionary will have to change.
every_type = """
{
"base64_key":"MTI=",
"bool_key": true,
"double_key": 123.456,
"float_key": 125.25,
"int_key": -123,
"int64_key": -123456789,
"null_key": null,
"string_key": "Hello",
"string_with_length_key": "Hell",
"u_int_key": 123,
"u_int64_key": 123456789,
"array": [
1,
2,
3
]
}
"""
def __inspect_every_type():
"""Helper to write one of every type to the inspector"""
self.assertTrue(inspector.open_object())
self.assertTrue(inspector.write_key("base64_key"))
self.assertTrue(inspector.write_base64_encoded(b'1234', 2))
self.assertTrue(inspector.write_key("bool_key"))
self.assertTrue(inspector.write_bool(True))
self.assertTrue(inspector.write_key("double_key"))
self.assertTrue(inspector.write_double(123.456))
self.assertTrue(inspector.write_key("float_key"))
self.assertTrue(inspector.write_float(125.25))
self.assertTrue(inspector.write_key_with_length("int_key_is_truncated", 7))
self.assertTrue(inspector.write_int(-123))
self.assertTrue(inspector.write_key("int64_key"))
self.assertTrue(inspector.write_int64(-123456789))
self.assertTrue(inspector.write_key("null_key"))
self.assertTrue(inspector.write_null())
self.assertTrue(inspector.write_key("string_key"))
self.assertTrue(inspector.write_string("Hello"))
self.assertTrue(inspector.write_key("string_with_length_key"))
self.assertTrue(inspector.write_string_with_length("Hello World", 4))
self.assertTrue(inspector.write_key("u_int_key"))
self.assertTrue(inspector.write_u_int(123))
self.assertTrue(inspector.write_key("u_int64_key"))
self.assertTrue(inspector.write_u_int64(123456789))
self.assertTrue(inspector.write_key("array"))
self.assertTrue(inspector.open_array())
self.assertTrue(inspector.write_int(1))
self.assertTrue(inspector.write_int(2))
self.assertTrue(inspector.write_int(3))
self.assertTrue(inspector.close_array())
self.assertTrue(inspector.close_object())
self.assertTrue(inspector.finish())
__inspect_every_type()
self.assertEqual(inspector.as_string(), every_type)
# Test file output
with tempfile.TemporaryDirectory() as tmp:
test_output_file = Path(tmp) / "test_serializer.txt"
# Get the temp file path and test writing a line to it
inspector.output_to_file_path = str(test_output_file)
__inspect_every_type()
self.assertEqual(inspector.as_string(), every_type)
# Set output back to string and check the temp file contents manually
inspector.set_output_to_string()
file_contents = [line.rstrip() for line in open(test_output_file, "r").readlines()]
self.assertCountEqual(file_contents, every_type.split("\n")[:-1])
| 8,329 | Python | 39.833333 | 115 | 0.593829 |
omniverse-code/kit/exts/omni.inspect/omni/inspect/tests/__init__.py | """
Scan the test directory for unit tests
"""
scan_for_test_modules = True
| 76 | Python | 14.399997 | 38 | 0.710526 |
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/__init__.py | from .imageview import ImageView
| 33 | Python | 15.999992 | 32 | 0.848485 |
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/imageview.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
class ImageView:
"""The widget that shows the image with the ability to navigate"""
def __init__(self, filename, **kwargs):
with ui.CanvasFrame(style_type_name_override="ImageView", **kwargs):
self.__image = ui.Image(filename)
def set_progress_changed_fn(self, fn):
"""Callback that is called when control state is changed"""
self.__image.set_progress_changed_fn(fn)
def destroy(self):
if self.__image:
self.__image.destroy()
self.__image = None
| 985 | Python | 35.518517 | 76 | 0.701523 |
omniverse-code/kit/exts/omni.kit.widget.imageview/omni/kit/widget/imageview/tests/imageview_test.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from ..imageview import ImageView
from omni.ui.tests.test_base import OmniUiTest
from functools import partial
from pathlib import Path
import omni.kit.app
import asyncio
class TestImageview(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute()
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def test_general(self):
window = await self.create_test_window()
f = asyncio.Future()
def on_image_progress(future: asyncio.Future, progress):
if progress >= 1:
if not future.done():
future.set_result(None)
with window.frame:
image_view = ImageView(f"{self._golden_img_dir.joinpath('lenna.png')}")
image_view.set_progress_changed_fn(partial(on_image_progress, f))
# Wait the image to be loaded
await f
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 1,697 | Python | 35.127659 | 110 | 0.683559 |
omniverse-code/kit/exts/omni.kit.widget.text_editor/omni/kit/widget/text_editor/tests/test_text_editor.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["TestTextEditor"]
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
from .._text_editor import TextEditor
EXTENSION_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
GOLDEN_PATH = EXTENSION_PATH.joinpath("data/golden")
STYLE = {"Field": {"background_color": 0xFF24211F, "border_radius": 2}}
class TestTextEditor(OmniUiTest):
async def test_general(self):
"""Testing general look of TextEditor"""
window = await self.create_test_window()
lines = ["The quick brown fox jumps over the lazy dog."] * 20
with window.frame:
TextEditor(text_lines=lines)
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=GOLDEN_PATH, golden_img_name=f"test_general.png")
async def test_syntax(self):
"""Testing languages of TextEditor"""
import inspect
window = await self.create_test_window()
with window.frame:
TextEditor(text_lines=inspect.getsource(self.test_syntax).splitlines(), syntax=TextEditor.Syntax.PYTHON)
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=GOLDEN_PATH, golden_img_name=f"test_syntax.png")
async def test_text_changed_flag(self):
"""Testing TextEditor text edited callback"""
from omni.kit import ui_test
window = await self.create_test_window(block_devices=False)
window.focus()
text = "Lorem ipsum"
text_new = "dolor sit amet"
with window.frame:
text_editor = TextEditor(text=text)
await ui_test.wait_n_updates(2)
self.text_changed = False
def on_text_changed(text_changed):
self.text_changed = text_changed
text_editor.set_edited_fn(on_text_changed)
self.assertFalse(self.text_changed)
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(100, 100))
await ui_test.wait_n_updates(2)
await ui_test.emulate_char_press("A")
await ui_test.wait_n_updates(2)
self.assertTrue(self.text_changed)
await ui_test.emulate_key_combo("BACKSPACE")
await ui_test.wait_n_updates(2)
self.assertFalse(self.text_changed)
text_editor.text = text_new
await ui_test.wait_n_updates(2)
# Only user input will trigger the callback
self.assertFalse(self.text_changed)
await ui_test.emulate_char_press("A")
await ui_test.wait_n_updates(2)
self.assertTrue(self.text_changed)
text_editor.set_edited_fn(None)
| 3,199 | Python | 31.98969 | 116 | 0.666458 |
omniverse-code/kit/exts/omni.timeline/omni/timeline/__init__.py | from ._timeline import *
def get_timeline_interface(timeline_name: str='') -> Timeline:
"""Returns the timeline with the given name via cached :class:`omni.timeline.ITimeline` interface"""
if not hasattr(get_timeline_interface, "timeline"):
get_timeline_interface.timeline = acquire_timeline_interface()
return get_timeline_interface.timeline.get_timeline(timeline_name)
def destroy_timeline(timeline_name: str):
"""Destroys a timeline object with the given name, if it is not the default timeline and it is not in use."""
if not hasattr(get_timeline_interface, "timeline"):
get_timeline_interface.timeline = acquire_timeline_interface()
return get_timeline_interface.timeline.destroy_timeline(timeline_name)
| 754 | Python | 43.411762 | 113 | 0.740053 |
omniverse-code/kit/exts/omni.timeline/omni/timeline/tests/tests.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.events
import omni.kit.app
import omni.kit.test
import omni.timeline
import carb.settings
import queue
import asyncio
from time import sleep
USE_FIXED_TIMESTEP_PATH = "/app/player/useFixedTimeStepping"
RUNLOOP_RATE_LIMIT_PATH = "/app/runLoops/main/rateLimitFrequency"
COMPENSATE_PLAY_DELAY_PATH = "/app/player/CompensatePlayDelayInSecs"
class TestTimeline(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._app = omni.kit.app.get_app()
self._timeline = omni.timeline.get_timeline_interface()
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self._buffered_evts = queue.Queue()
self._settings = carb.settings.acquire_settings_interface()
async def tearDown(self):
self._timeline = None
self._timeline_sub = None
async def test_timeline_api(self):
## Check initial states
self.assertFalse(self._timeline.is_playing())
self.assertTrue(self._timeline.is_stopped())
self.assertEqual(0.0, self._timeline.get_start_time())
self.assertEqual(0.0, self._timeline.get_end_time())
self.assertEqual(0.0, self._timeline.get_current_time())
self.assertEqual(0.0, self._timeline.get_time_codes_per_seconds())
self.assertTrue(self._timeline.is_looping())
self.assertTrue(self._timeline.is_auto_updating())
self.assertFalse(self._timeline.is_prerolling())
self.assertFalse(self._timeline.is_zoomed())
## Change start time
start_time = -1.0
self._timeline.set_start_time(start_time)
self._assert_no_change_then_commit(self._timeline.get_start_time(), 0)
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED, "startTime", start_time)
self.assertTrue(self._buffered_evts.empty())
self.assertEqual(start_time, self._timeline.get_start_time())
self.assertEqual(0.0, self._timeline.get_current_time())
## Change end time
end_time = 2.0
self._timeline.set_end_time(end_time)
self._assert_no_change_then_commit(self._timeline.get_end_time(), 0)
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED, "endTime", end_time)
self.assertTrue(self._buffered_evts.empty())
self.assertEqual(end_time, self._timeline.get_end_time())
self.assertEqual(0.0, self._timeline.get_current_time())
## Change start time to current_time < start_time < end_time
# OM-75796: changing start time does not move current time when the timeline is not playing
old_start_time = start_time
start_time = 1.0
self._timeline.set_start_time(start_time)
self._assert_no_change_then_commit(self._timeline.get_start_time(), old_start_time)
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED, "startTime", start_time)
self.assertTrue(self._buffered_evts.empty())
self.assertEqual(start_time, self._timeline.get_start_time())
self.assertEqual(0.0, self._timeline.get_current_time())
## Change timecode per second
time_code_per_sec = 24.0
self._timeline.set_time_codes_per_second(time_code_per_sec)
self._assert_no_change_then_commit(self._timeline.get_time_codes_per_seconds(), 0)
self._verify_evt(
omni.timeline.TimelineEventType.TIME_CODE_PER_SECOND_CHANGED, "timeCodesPerSecond", time_code_per_sec
)
self.assertEqual(time_code_per_sec, self._timeline.get_time_codes_per_seconds())
## Do not allow endtime <= starttime
frame_time = 1.0 / time_code_per_sec
new_start_time = end_time
self._timeline.set_start_time(new_start_time)
self._assert_no_change_then_commit(self._timeline.get_start_time(), start_time)
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED, "startTime", new_start_time)
self._verify_evt(
omni.timeline.TimelineEventType.END_TIME_CHANGED,
"endTime",
new_start_time + frame_time,
exact=False
)
self.assertTrue(self._buffered_evts.empty())
new_start_time = new_start_time + 10.0 * frame_time
self._timeline.set_start_time(new_start_time)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED, "startTime", new_start_time)
self._verify_evt(
omni.timeline.TimelineEventType.END_TIME_CHANGED,
"endTime",
new_start_time + frame_time,
exact=False
)
self.assertTrue(self._buffered_evts.empty())
new_end_time = self._timeline.get_start_time()
self._timeline.set_end_time(new_end_time)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED, "endTime", new_end_time)
self._verify_evt(
omni.timeline.TimelineEventType.START_TIME_CHANGED,
"startTime",
new_end_time - frame_time,
exact=False
)
self.assertTrue(self._buffered_evts.empty())
new_end_time = new_end_time - 10.0 * frame_time
self._timeline.set_end_time(new_end_time)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED, "endTime", new_end_time)
self._verify_evt(
omni.timeline.TimelineEventType.START_TIME_CHANGED,
"startTime",
new_end_time - frame_time,
exact=False
)
self.assertTrue(self._buffered_evts.empty())
# Revert
start_time = 1.0
self._timeline.set_start_time(start_time)
self._timeline.set_end_time(end_time)
self._timeline.set_current_time(start_time)
self._timeline.commit()
self._clear_evt_queue() # Don't care
## Time conversion
self.assertAlmostEqual(self._timeline.time_to_time_code(-1), -24, places=5)
self.assertAlmostEqual(self._timeline.time_to_time_code(0), 0, places=5)
self.assertAlmostEqual(self._timeline.time_to_time_code(0.5), 12, places=5)
self.assertAlmostEqual(self._timeline.time_to_time_code(2), 48, places=5)
self.assertAlmostEqual(self._timeline.time_code_to_time(-24), -1, places=5)
self.assertAlmostEqual(self._timeline.time_code_to_time(0), 0, places=5)
self.assertAlmostEqual(self._timeline.time_code_to_time(12), 0.5, places=5)
self.assertAlmostEqual(self._timeline.time_code_to_time(48), 2, places=5)
self.assertTrue(self._buffered_evts.empty())
## Set current time
old_current_time = self._timeline.get_current_time()
new_current_time = start_time
self._timeline.set_current_time(new_current_time)
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "currentTime", new_current_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "currentTime", new_current_time)
self.assertEqual(new_current_time, self._timeline.get_current_time())
# dt is smaller than 1 frame
old_current_time = self._timeline.get_current_time()
expected_dt = 0.5 * frame_time
new_current_time = start_time + expected_dt
self._timeline.set_current_time(new_current_time)
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "dt", expected_dt, False)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "dt", expected_dt, False)
self.assertEqual(new_current_time, self._timeline.get_current_time())
# Edge case: dt is exactly one frame
old_current_time = self._timeline.get_current_time()
expected_dt = 1.0 * frame_time
new_current_time = new_current_time + expected_dt
self._timeline.set_current_time(new_current_time)
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "dt", expected_dt, False)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "dt", expected_dt, False)
self.assertEqual(new_current_time, self._timeline.get_current_time())
# If dt would be too large to simulate, it is set to zero
old_current_time = self._timeline.get_current_time()
expected_dt = 0
new_current_time = new_current_time + 1.5 * frame_time
self._timeline.set_current_time(new_current_time)
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "dt", expected_dt, False)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "dt", expected_dt, False)
self.assertEqual(new_current_time, self._timeline.get_current_time())
# If dt would be negative, it is set to zero
old_current_time = self._timeline.get_current_time()
expected_dt = 0
new_current_time = start_time
self._timeline.set_current_time(new_current_time)
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "dt", expected_dt, False)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "dt", expected_dt, False)
self.assertEqual(new_current_time, self._timeline.get_current_time())
## Forward one frame
old_current_time = self._timeline.get_current_time()
self._timeline.forward_one_frame()
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
# Forward one frame triggers a play and pause if the timeline was not playing
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
"currentTime", start_time + 1.0 / time_code_per_sec
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT,
"currentTime", start_time + 1.0 / time_code_per_sec
)
self._verify_evt(omni.timeline.TimelineEventType.PAUSE)
self.assertAlmostEqual(start_time + 1.0 / time_code_per_sec, self._timeline.get_current_time(), places=5)
## Rewind one frame
old_current_time = self._timeline.get_current_time()
self._timeline.rewind_one_frame()
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "currentTime", start_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "currentTime", start_time)
self.assertAlmostEqual(start_time, self._timeline.get_current_time(), places=5)
new_current_time = self._timeline.get_current_time()
## Set target framerate.
DEFAULT_TARGET_FRAMERATE = 60
self.assertEqual(self._timeline.get_target_framerate(), DEFAULT_TARGET_FRAMERATE)
target_vs_set_fps = [
[2 * time_code_per_sec - 1, 2 * time_code_per_sec],
[3 * time_code_per_sec + 15, 4 * time_code_per_sec],
[5 * time_code_per_sec - 7, 5 * time_code_per_sec],
[time_code_per_sec, time_code_per_sec] # this comes last to avoid frame skipping in Play tests
]
self._timeline.play()
self._timeline.commit()
self._clear_evt_queue() # don't care
for fps in target_vs_set_fps:
target_fps = fps[0]
desired_runloop_fps = fps[1]
old_fps = self._timeline.get_target_framerate()
self._timeline.set_target_framerate(target_fps)
self._assert_no_change_then_commit(self._timeline.get_target_framerate(), old_fps)
self._verify_evt(
omni.timeline.TimelineEventType.TARGET_FRAMERATE_CHANGED, "targetFrameRate", target_fps
)
self.assertEqual(target_fps, self._timeline.get_target_framerate())
self.assertEqual(self._settings.get(RUNLOOP_RATE_LIMIT_PATH), desired_runloop_fps)
self._timeline.stop()
self._timeline.commit()
self._clear_evt_queue() # don't care
## Play
self._timeline.play()
self._assert_no_change_then_commit(self._timeline.is_playing(), False)
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
self.assertTrue(self._settings.get(USE_FIXED_TIMESTEP_PATH))
self.assertTrue(self._timeline.is_playing())
self.assertFalse(self._timeline.is_stopped())
await self._app.next_update_async()
dt = 1.0 / time_code_per_sec # timeline uses fixed dt by default
self.assertAlmostEqual(new_current_time + dt, self._timeline.get_current_time(), places=5)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "currentTime", new_current_time + dt, exact=False
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "dt", dt, exact=False
)
# varying dt
self._timeline.stop()
self._settings.set(USE_FIXED_TIMESTEP_PATH, False)
self._timeline.play()
self._timeline.commit()
self._clear_evt_queue()
new_current_time = self._timeline.get_current_time()
dt = await self._app.next_update_async()
self.assertAlmostEqual(new_current_time + dt, self._timeline.get_current_time(), places=5)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "currentTime", new_current_time + dt, exact=False
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "dt", dt, exact=False
)
self._settings.set(USE_FIXED_TIMESTEP_PATH, True)
## Pause
self._timeline.pause()
self._assert_no_change_then_commit(self._timeline.is_playing(), True)
self._verify_evt(omni.timeline.TimelineEventType.PAUSE)
self.assertFalse(self._timeline.is_playing())
self.assertFalse(self._timeline.is_stopped())
# current time should not change
await self._app.next_update_async()
self.assertAlmostEqual(new_current_time + dt, self._timeline.get_current_time(), places=5)
# permanent update event is still ticking
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
## Stop
self._timeline.stop()
self._assert_no_change_then_commit(self._timeline.is_stopped(), False)
self._verify_evt(omni.timeline.TimelineEventType.STOP)
self.assertFalse(self._timeline.is_playing())
self.assertTrue(self._timeline.is_stopped())
self.assertEqual(start_time, self._timeline.get_current_time())
## Loop
# self._timeline.set_looping(True) # it was already set
self._timeline.play()
self._timeline.commit()
dt = 1.0 / time_code_per_sec # timeline uses fixed dt by default
elapsed_time = 0.0
while elapsed_time < end_time * 1.5:
await self._app.next_update_async()
elapsed_time += dt
self._timeline.pause()
self._timeline.commit()
self._clear_evt_queue() # don't care
# time is looped
loopped_time = elapsed_time % (end_time - start_time) + start_time
self.assertAlmostEqual(loopped_time, self._timeline.get_current_time(), places=5)
## Non-loop
self._timeline.set_looping(False)
self._assert_no_change_then_commit(self._timeline.is_looping(), True)
self._verify_evt(omni.timeline.TimelineEventType.LOOP_MODE_CHANGED, "looping", False)
self._timeline.stop()
self._timeline.play()
self._timeline.commit()
elapsed_time = 0.0
while elapsed_time < end_time * 1.5:
dt = await self._app.next_update_async()
elapsed_time += dt
# timeline paused when reached the end
self.assertFalse(self._timeline.is_playing())
self.assertFalse(self._timeline.is_stopped())
self.assertAlmostEqual(end_time, self._timeline.get_current_time(), places=5)
## Change end time that should change current time because current time was > end time
self._clear_evt_queue()
end_time = 1.5
current_time = self._timeline.get_current_time()
self._timeline.set_end_time(end_time)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED, "endTime", end_time)
# OM-75796: changing the end time does not move current time when timeline is not playing
self.assertTrue(self._buffered_evts.empty())
self.assertEqual(end_time, self._timeline.get_end_time())
self.assertEqual(current_time, self._timeline.get_current_time())
self._timeline.stop()
# OM-75796: changing the end time moves current time to start when timeline is playing
self._timeline.play()
self._timeline.set_current_time(end_time) # someting after the new end time
self._timeline.commit()
self._clear_evt_queue() # don't care
end_time = 1.25
self._timeline.set_end_time(end_time)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED, "endTime", end_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "currentTime", start_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "currentTime", start_time)
self.assertTrue(self._buffered_evts.empty())
self.assertEqual(end_time, self._timeline.get_end_time())
self.assertEqual(start_time, self._timeline.get_current_time())
# OM-75796: changing the start time moves current time to start when timeline is playing
end_time = 100
self._timeline.set_end_time(end_time)
self._timeline.commit()
self._clear_evt_queue() # don't care
start_time = 2.0
self._timeline.set_start_time(start_time)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED, "startTime", start_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "currentTime", start_time)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "currentTime", start_time)
self.assertTrue(self._buffered_evts.empty())
self.assertEqual(start_time, self._timeline.get_start_time())
self.assertEqual(start_time, self._timeline.get_current_time())
self._timeline.stop()
self._timeline.commit()
## Auto update
self._clear_evt_queue()
self._timeline.set_auto_update(False)
self._assert_no_change_then_commit(self._timeline.is_auto_updating(), True)
self._verify_evt(omni.timeline.TimelineEventType.AUTO_UPDATE_CHANGED, "autoUpdate", False)
self.assertFalse(self._timeline.is_auto_updating())
self._timeline.set_looping(True)
self._timeline.play()
for i in range(5):
await self._app.next_update_async()
self.assertEqual(start_time, self._timeline.get_current_time())
## Prerolling
self._clear_evt_queue()
self._timeline.set_prerolling(True)
self._assert_no_change_then_commit(self._timeline.is_prerolling(), False)
self.assertTrue(self._timeline.is_prerolling())
self._verify_evt(omni.timeline.TimelineEventType.PREROLLING_CHANGED, "prerolling", True)
## Change TimeCodesPerSeconds and verify if CurrentTime is properly refitted.
time_codes_per_second = 24
timecode = 50
self._timeline.set_time_codes_per_second(time_codes_per_second)
self._timeline.set_start_time(0)
self._timeline.set_end_time(100)
self._timeline.set_current_time(timecode)
self._timeline.set_time_codes_per_second(100)
self._timeline.commit()
# we stay the same timecode after change TimeCodesPerSeconds
self.assertEqual(timecode, self._timeline.get_current_time())
## Play in range
self._timeline.stop()
self._timeline.set_auto_update(True)
start_time_seconds = 0
range_start_timecode = 20
range_end_timecode = 30
end_time_seconds = 40
self._timeline.set_start_time(start_time_seconds)
self._timeline.set_end_time(end_time_seconds)
self._timeline.commit()
self._clear_evt_queue()
self._timeline.play(range_start_timecode, range_end_timecode, False)
self._assert_no_change_then_commit(True, True)
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
self.assertTrue(self._timeline.is_playing())
self.assertFalse(self._timeline.is_stopped())
await asyncio.sleep(5)
self.assertEqual(start_time_seconds, self._timeline.get_start_time())
self.assertEqual(end_time_seconds, self._timeline.get_end_time())
self.assertEqual(range_end_timecode, self._timeline.get_current_time() * self._timeline.get_time_codes_per_seconds())
## tentative time
current_time = 2.0
tentative_time = 2.5
self._timeline.set_current_time(current_time)
self._timeline.commit()
self._clear_evt_queue()
self._timeline.set_tentative_time(tentative_time)
self._assert_no_change_then_commit(self._timeline.get_tentative_time(), current_time)
self._verify_evt(omni.timeline.TimelineEventType.TENTATIVE_TIME_CHANGED)
self.assertEqual(tentative_time, self._timeline.get_tentative_time())
self.assertEqual(current_time, self._timeline.get_current_time())
self._timeline.clear_tentative_time()
self._assert_no_change_then_commit(self._timeline.get_tentative_time(), tentative_time)
self.assertEqual(self._timeline.get_tentative_time(), self._timeline.get_current_time())
## tentative time and events
tentative_time = 3.5
self._timeline.set_tentative_time(tentative_time)
self._timeline.commit()
self._clear_evt_queue()
self._timeline.forward_one_frame()
self._assert_no_change_then_commit(True, True)
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
self._verify_evt(omni.timeline.TimelineEventType.PAUSE)
self.assertTrue(self._buffered_evts.empty()) # tentative time was used, no other event
self._timeline.set_tentative_time(tentative_time)
self._timeline.commit()
self._clear_evt_queue()
self._timeline.rewind_one_frame()
self._assert_no_change_then_commit(True, True)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
self.assertTrue(self._buffered_evts.empty()) # tentative time was used, no other event
## Forward one frame while the timeline is playing: only time is ticked, no play/pause
self._timeline.play()
self._timeline.commit()
self._clear_evt_queue() # don't care
old_current_time = self._timeline.get_current_time()
tcps_current = self._timeline.get_time_codes_per_seconds()
self._timeline.forward_one_frame()
self._assert_no_change_then_commit(self._timeline.get_current_time(), old_current_time)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
"currentTime", old_current_time + 1.0 / tcps_current
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT,
"currentTime", old_current_time + 1.0 / tcps_current
)
self.assertTrue(self._buffered_evts.empty())
self.assertAlmostEqual(old_current_time + 1.0 / tcps_current, self._timeline.get_current_time(), places=5)
self._timeline.stop()
self._timeline.commit()
self._clear_evt_queue() # don't care
## substepping
subsample_rate = 3
old_subsample_rate = self._timeline.get_ticks_per_frame()
self._timeline.set_ticks_per_frame(subsample_rate)
self._assert_no_change_then_commit(self._timeline.get_ticks_per_frame(), old_subsample_rate)
self._verify_evt(
omni.timeline.TimelineEventType.TICKS_PER_FRAME_CHANGED, "ticksPerFrame", subsample_rate, exact=True
)
self.assertEqual(self._timeline.get_ticks_per_frame(), subsample_rate)
self.assertEqual(self._timeline.get_ticks_per_second(), subsample_rate * self._timeline.get_time_codes_per_seconds())
self._timeline.play()
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
await self._app.next_update_async()
for i in range(subsample_rate):
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "tick", i, exact=True
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "tick", i, exact=True
)
tick_dt = 1.0 / (self._timeline.get_time_codes_per_seconds() * subsample_rate)
await self._app.next_update_async()
for i in range(subsample_rate):
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, "dt", tick_dt, exact=False
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, "dt", tick_dt, exact=False
)
start_time = self._timeline.get_current_time()
await self._app.next_update_async()
for i in range(subsample_rate):
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
"currentTime",
start_time + (i + 1) * tick_dt,
exact=False
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT,
"currentTime",
start_time + (i + 1) * tick_dt,
exact=False
)
self._timeline.stop()
self._timeline.commit()
## substepping with event handling and event firing in the kit runloop
self._tick = True
def pause(e: carb.events.IEvent):
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
if self._tick:
self._timeline.pause()
else:
self._timeline.play()
self._tick = not self._tick
pause_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(pause, order=1)
start_time = self._timeline.get_current_time()
self._timeline.play()
self._timeline.commit()
self._clear_evt_queue()
# callbacks call stop and pause but we still finish the frame
await self._app.post_update_async()
for i in range(subsample_rate):
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
"currentTime",
start_time + (i + 1) * tick_dt,
exact=False
)
self._verify_evt(
omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT,
"currentTime",
start_time + (i + 1) * tick_dt,
exact=False
)
# No events until the next frame
self.assertTrue(self._buffered_evts.empty())
# wait a until the next update, events are then re-played
await self._app.next_update_async()
self._tick = True
for i in range(subsample_rate):
if self._tick:
self._verify_evt(omni.timeline.TimelineEventType.PAUSE)
else:
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
self._tick = not self._tick
self.assertEqual(self._timeline.is_playing(), self._tick)
pause_sub = None
# stop for the next test
self._timeline.stop()
self._timeline.commit()
self._clear_evt_queue()
## frame skipping
self.assertFalse(self._timeline.get_play_every_frame()) # off by default
self.assertAlmostEqual(self._settings.get(COMPENSATE_PLAY_DELAY_PATH), 0.0) # No compensation by default
self._timeline.set_time_codes_per_second(time_codes_per_second)
self._timeline.set_ticks_per_frame(1)
self._timeline.set_target_framerate(3.0 * time_code_per_sec)
self._timeline.play()
self._timeline.commit()
self._clear_evt_queue()
await self._app.next_update_async()
# events are fired on the first call
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
# 2 frames are skipped
await self._app.next_update_async()
self.assertTrue(self._buffered_evts.empty())
await self._app.next_update_async()
self.assertTrue(self._buffered_evts.empty())
# firing events again
await self._app.next_update_async()
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
self._timeline.stop()
self._timeline.commit()
self._clear_evt_queue() # don't care
# fast mode, target frame rate is still 3 * time_code_per_sec, but frames should not be skipped
self._timeline.set_play_every_frame(True)
self._assert_no_change_then_commit(self._timeline.get_play_every_frame(), False)
self._verify_evt(
omni.timeline.TimelineEventType.PLAY_EVERY_FRAME_CHANGED, "playEveryFrame", True, exact=True
)
self._timeline.play()
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
await self._app.next_update_async()
for i in range(5):
await self._app.next_update_async()
# events are fired for every call
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
self._timeline.set_play_every_frame(False)
self._timeline.commit()
self._clear_evt_queue() # don't care
## test multiple pipelines
self._timeline.stop()
self._timeline.commit()
default_timeline_current_time = self._timeline.get_current_time()
new_timeline_name = "new_timeline"
self._new_timeline = omni.timeline.get_timeline_interface(new_timeline_name)
self._new_timeline.set_current_time(default_timeline_current_time + 1.0)
self._new_timeline.set_end_time(default_timeline_current_time + 10.0)
self._new_timeline.commit()
new_timeline_current_time = self._new_timeline.get_current_time()
self.assertNotEqual(new_timeline_current_time, self._timeline.get_current_time())
self._new_timeline.play()
self._new_timeline.commit()
self.assertFalse(self._timeline.is_playing())
self.assertTrue(self._new_timeline.is_playing())
for i in range(10):
await self._app.next_update_async()
self.assertNotEqual(new_timeline_current_time, self._new_timeline.get_current_time())
self.assertEqual(default_timeline_current_time, self._timeline.get_current_time())
# OM-76359: test that cleaning works
self._new_timeline = None
self._dummy_timeline = omni.timeline.get_timeline_interface('dummy')
self._new_timeline = omni.timeline.get_timeline_interface(new_timeline_name)
self.assertAlmostEqual(0.0, self._new_timeline.get_current_time(), places=5)
omni.timeline.destroy_timeline(new_timeline_name)
omni.timeline.destroy_timeline('dummy')
## commit and its silent version
self._clear_evt_queue()
self._timeline.set_target_framerate(17)
self._timeline.set_time_codes_per_second(1)
self._timeline.set_ticks_per_frame(19)
self._timeline.play()
self._timeline.stop()
self._timeline.set_current_time(15)
self._timeline.rewind_one_frame()
self._timeline.commit_silently()
self.assertTrue(self._buffered_evts.empty())
self.assertAlmostEqual(self._timeline.get_target_framerate(), 17)
self.assertAlmostEqual(self._timeline.get_time_codes_per_seconds(), 1)
self.assertAlmostEqual(self._timeline.get_ticks_per_frame(), 19)
self.assertFalse(self._timeline.is_playing())
self.assertAlmostEqual(self._timeline.get_current_time(), 14)
# Revert
self._timeline.set_ticks_per_frame(1)
await self._app.next_update_async()
self._clear_evt_queue()
self._timeline.set_start_time(1)
self._timeline.set_end_time(10)
self._timeline.set_current_time(5)
self._timeline.play()
self._timeline.forward_one_frame()
self._timeline.rewind_one_frame()
self.assertAlmostEqual(self._timeline.get_current_time(), 14)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED, 'startTime', 1)
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED, 'endTime', 10)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, 'currentTime', 5)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, 'currentTime', 5)
self._verify_evt(omni.timeline.TimelineEventType.PLAY)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, 'currentTime', 6)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, 'currentTime', 6)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED, 'currentTime', 5)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT, 'currentTime', 5)
self.assertTrue(self._buffered_evts.empty())
self.assertAlmostEqual(self._timeline.get_current_time(), 5)
self.assertTrue(self._timeline.is_playing())
self._timeline.stop()
self._timeline.commit()
self._clear_evt_queue()
# calling manually to make sure they come after the API test
# independently of the test env
await self._test_runloop_integration()
await self._test_director()
async def _test_runloop_integration(self):
""" Test how the run loop behaves when it is controlled by the timeline
and test proper behavior when runloop slows down
"""
# make sure other tests do not interfere
TIMELINE_FPS = 25.0
RUNLOOP_FPS = TIMELINE_FPS * 4.0 # 100, 1/4 frame skipping
self._timeline.stop()
self._timeline.set_current_time(0.0)
self._timeline.set_start_time(0.0)
self._timeline.set_end_time(1000.0)
self._timeline.set_target_framerate(RUNLOOP_FPS)
self._timeline.set_time_codes_per_second(TIMELINE_FPS)
self._timeline.set_play_every_frame(False)
self._timeline.set_ticks_per_frame(1)
self._timeline.play()
self._timeline.commit()
# Run loop is expected to run with 100 FPS, nothing should slow it down.
# Timeline relies on this so we test this here.
self.assertEqual(self._settings.get(RUNLOOP_RATE_LIMIT_PATH), RUNLOOP_FPS)
FPS_TOLERANCE_PERCENT = 5
runloop_dt_min = (1.0 / RUNLOOP_FPS) * (1 - FPS_TOLERANCE_PERCENT * 0.01)
runloop_dt_max = (1.0 / RUNLOOP_FPS) * (1 + FPS_TOLERANCE_PERCENT * 0.01)
update_sub = self._app.get_update_event_stream().create_subscription_to_pop(
self._save_runloop_dt,
name="[TimelineTest save dt]"
)
for i in range(3):
await self._app.next_update_async() # warm up, "consume" old FPS
for i in range(5):
await self._app.next_update_async()
self.assertTrue(self._runloop_dt >= runloop_dt_min,
"Run loop dt is too far from expected: {} vs {}"
.format(self._runloop_dt, (1.0 / RUNLOOP_FPS)))
self.assertTrue(self._runloop_dt <= runloop_dt_max,
"Run loop dt is too far from expected: {} vs {}"
.format(self._runloop_dt, (1.0 / RUNLOOP_FPS)))
# Timeline wants to keep up with real time if run loop gets too slow (no frame skipping)
self._settings.set(COMPENSATE_PLAY_DELAY_PATH, 1000.0) # set something high, e.g. 1000s
pre_update_sub = self._app.get_pre_update_event_stream().create_subscription_to_pop(
self._sleep,
name="[TimelineTest sleep]"
)
self._timeline.stop()
self._timeline.play()
self._timeline.commit()
self._clear_evt_queue()
await self._app.next_update_async()
for i in range(5):
await self._app.next_update_async()
self.assertTrue(self._runloop_dt > 0.99) # sleep
# run loop is slow, no frame skipping even though fast mode is off
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED)
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
self._timeline.stop()
self._timeline.commit()
self._clear_evt_queue()
async def _test_director(self):
self._timeline.stop()
self._timeline.set_current_time(0)
self._timeline.set_end_time(10)
self._timeline.set_start_time(0)
self._timeline.set_time_codes_per_second(24)
self._timeline.set_looping(False)
self._timeline.set_prerolling(True)
self._timeline.set_auto_update(False)
self._timeline.set_play_every_frame(True)
self._timeline.set_ticks_per_frame(2)
self._timeline.set_target_framerate(24)
self._timeline.commit()
self._clear_evt_queue()
self.assertIsNone(self._timeline.get_director())
self._director_timeline = omni.timeline.get_timeline_interface('director')
# Make sure they have the same parameters
self._director_timeline.stop()
self._director_timeline.set_current_time(self._timeline.get_current_time())
self._director_timeline.set_end_time(self._timeline.get_end_time())
self._director_timeline.set_start_time(self._timeline.get_start_time())
self._director_timeline.set_time_codes_per_second(self._timeline.get_time_codes_per_seconds())
self._director_timeline.set_looping(self._timeline.is_looping())
self._director_timeline.set_prerolling(self._timeline.is_prerolling())
self._director_timeline.set_auto_update(self._timeline.is_auto_updating())
self._director_timeline.set_play_every_frame(self._timeline.get_play_every_frame())
self._director_timeline.set_ticks_per_frame(self._timeline.get_ticks_per_frame())
self._director_timeline.set_target_framerate(self._timeline.get_target_framerate())
self._director_timeline.commit()
self._timeline.set_director(self._director_timeline)
self._timeline.commit()
self._verify_evt(omni.timeline.TimelineEventType.DIRECTOR_CHANGED, 'directorName', 'director')
self._director_timeline.play()
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertTrue(self._timeline.is_playing())
self._director_timeline.pause()
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertFalse(self._timeline.is_playing())
self._director_timeline.stop()
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertTrue(self._timeline.is_stopped())
self._director_timeline.set_current_time(2)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertAlmostEqual(self._timeline.get_current_time(), 2, places=4)
self._director_timeline.set_end_time(5)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertAlmostEqual(self._timeline.get_end_time(), 5, places=4)
self._director_timeline.set_start_time(1)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertAlmostEqual(self._timeline.get_start_time(), 1, places=4)
self._director_timeline.set_time_codes_per_second(30)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertAlmostEqual(self._timeline.get_time_codes_per_seconds(), 30, places=4)
self._director_timeline.set_looping(True)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertTrue(self._timeline.is_looping())
self._director_timeline.set_prerolling(False)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertFalse(self._timeline.is_prerolling())
self._director_timeline.set_auto_update(True)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertTrue(self._timeline.is_auto_updating())
self._director_timeline.set_play_every_frame(False)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertFalse(self._timeline.get_play_every_frame())
self._director_timeline.set_ticks_per_frame(1)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertEqual(self._timeline.get_ticks_per_frame(), 1)
self._director_timeline.set_target_framerate(30)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertAlmostEqual(self._timeline.get_target_framerate(), 30, places=4)
self.assertFalse(self._timeline.is_zoomed())
zoom_start = self._timeline.get_start_time() + 1
zoom_end = self._timeline.get_end_time() - 1
self._director_timeline.set_zoom_range(zoom_start, zoom_end)
self._director_timeline.commit()
self._timeline.commit()
await self._app.next_update_async()
self.assertAlmostEqual(self._timeline.get_zoom_start_time(), zoom_start)
self.assertAlmostEqual(self._timeline.get_zoom_end_time(), zoom_end)
self.assertTrue(self._timeline.is_zoomed())
self._clear_evt_queue() # don't care
# Make sure we still get the permanent tick from the timeline
# It might be delayed by one frame
await self._app.next_update_async()
await self._app.next_update_async()
self._verify_evt(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)
self._clear_evt_queue() # don't care
self._timeline.set_director(None)
self._timeline.commit()
await self._app.next_update_async()
self._verify_evt_exists(omni.timeline.TimelineEventType.DIRECTOR_CHANGED, 'hasDirector', False)
omni.timeline.destroy_timeline('director')
async def test_zoom(self):
timeline_name = 'zoom_test'
# create a new timeline so we don't interfere with other tests.
timeline = omni.timeline.get_timeline_interface(timeline_name)
timeline.set_time_codes_per_second(30)
start_time = 0
end_time = 10
timeline.set_start_time(start_time)
timeline.set_end_time(end_time)
# initial state: no zoom
self.assertAlmostEqual(timeline.get_start_time(), timeline.get_zoom_start_time())
self.assertAlmostEqual(timeline.get_end_time(), timeline.get_zoom_end_time())
self.assertFalse(timeline.is_zoomed())
# setting start and end time keeps the non-zoomed state
start_time = 1 # smaller interval than the current
end_time = 9
timeline.set_start_time(start_time)
self.assertAlmostEqual(timeline.get_start_time(), timeline.get_zoom_start_time())
self.assertFalse(timeline.is_zoomed())
timeline.commit()
timeline.set_end_time(end_time)
timeline.commit()
self.assertAlmostEqual(timeline.get_end_time(), timeline.get_zoom_end_time())
self.assertFalse(timeline.is_zoomed())
start_time = 0 # larger interval
end_time = 10
timeline.set_start_time(start_time)
self.assertAlmostEqual(timeline.get_start_time(), timeline.get_zoom_start_time())
self.assertFalse(timeline.is_zoomed())
timeline.commit()
timeline.set_end_time(end_time)
timeline.commit()
self.assertAlmostEqual(timeline.get_end_time(), timeline.get_zoom_end_time())
self.assertFalse(timeline.is_zoomed())
# changes are not immediate
timeline.set_zoom_range(start_time + 1, end_time - 1)
self.assertAlmostEqual(timeline.get_zoom_start_time(), start_time)
self.assertAlmostEqual(timeline.get_zoom_end_time(), end_time)
self.assertFalse(timeline.is_zoomed())
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), start_time + 1)
self.assertAlmostEqual(timeline.get_zoom_end_time(), end_time - 1)
self.assertTrue(timeline.is_zoomed())
# clear
timeline.clear_zoom()
self.assertAlmostEqual(timeline.get_zoom_start_time(), start_time + 1)
self.assertAlmostEqual(timeline.get_zoom_end_time(), end_time - 1)
self.assertTrue(timeline.is_zoomed())
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), start_time)
self.assertAlmostEqual(timeline.get_zoom_end_time(), end_time)
self.assertFalse(timeline.is_zoomed())
# set zoom ranges inside the timeline's range
timeline_sub = timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self._test_zoom_change(timeline, start_time + 1, end_time - 1, True, start_time + 1, end_time - 1,
"startTime", start_time + 1, False)
self._test_zoom_change(timeline, start_time + 1, end_time - 2, True, start_time + 1, end_time - 2,
"endTime", end_time - 2, False)
self._test_zoom_change(timeline, start_time + 2, end_time - 1, True, start_time + 2, end_time - 1,
"cleared", False)
# invalid input
zoom_start, zoom_end = timeline.get_zoom_start_time(), timeline.get_zoom_end_time()
timeline.set_zoom_range(start_time + 3, start_time + 1) # end < start
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), zoom_start)
self.assertAlmostEqual(timeline.get_zoom_end_time(), zoom_end)
# setting the same values should fire no events
timeline.set_zoom_range(timeline.get_zoom_start_time(), timeline.get_zoom_end_time())
timeline.commit()
self.assertTrue(self._buffered_evts.empty())
# set zoom ranges fully or partially outside the timeline's range, should be clipped
self._test_zoom_change(timeline, start_time + 1, end_time + 1, True, start_time + 1, end_time,
"endTime", end_time, False)
self._test_zoom_change(timeline, start_time - 1, end_time - 1, True, start_time, end_time - 1,
"startTime", start_time, False)
self._test_zoom_change(timeline, start_time - 1, end_time + 1, False, start_time, end_time,
"cleared", True)
# passing an empty interval should set a 1 frame long zoom range
self.assertGreater(timeline.get_time_codes_per_seconds(), 0)
dt = 1.0 / timeline.get_time_codes_per_seconds()
self._test_zoom_change(timeline, end_time, end_time, True, end_time - dt, end_time,
"startTime", end_time - dt)
self._test_zoom_change(timeline, start_time + 1, start_time + 1, True, start_time + 1, start_time + 1 + dt,
"endTime", start_time + 1 + dt)
# changing start/end time should not affect the zoom when setting a larger range
old_zoom_start = timeline.get_zoom_start_time()
old_zoom_end = timeline.get_zoom_end_time()
start_time = -1
timeline.set_start_time(start_time)
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), old_zoom_start)
self.assertAlmostEqual(timeline.get_zoom_end_time(), old_zoom_end)
self.assertTrue(timeline.is_zoomed())
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED)
self.assertTrue(self._buffered_evts.empty())
end_time = 9
timeline.set_end_time(end_time)
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), old_zoom_start)
self.assertAlmostEqual(timeline.get_zoom_end_time(), old_zoom_end)
self.assertTrue(timeline.is_zoomed())
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED)
self.assertTrue(self._buffered_evts.empty())
# zoom range should shrink with start and end time
timeline.set_zoom_range(start_time + 1, end_time - 1) # preparations for this test
timeline.commit()
old_zoom_start = timeline.get_zoom_start_time()
old_zoom_end = timeline.get_zoom_end_time()
self.assertTrue(timeline.is_zoomed())
self._clear_evt_queue() # don't care
start_time = timeline.get_zoom_start_time() + 1
timeline.set_start_time(start_time)
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), start_time)
self.assertAlmostEqual(timeline.get_zoom_end_time(), old_zoom_end)
self._verify_evt(omni.timeline.TimelineEventType.START_TIME_CHANGED)
self._verify_evt(omni.timeline.TimelineEventType.ZOOM_CHANGED, "startTime", start_time, False)
end_time = timeline.get_zoom_end_time() - 1
timeline.set_end_time(end_time)
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), start_time)
self.assertAlmostEqual(timeline.get_zoom_end_time(), end_time)
self._verify_evt(omni.timeline.TimelineEventType.END_TIME_CHANGED)
self._verify_evt(omni.timeline.TimelineEventType.ZOOM_CHANGED, "endTime", end_time, False)
# playback is affected by zoom
timeline_sub = None # don't care anymore
zoom_start = start_time + 1
zoom_end = end_time - 1
timeline.set_zoom_range(zoom_start, zoom_end)
timeline.commit()
self.assertTrue(timeline.is_zoomed())
timeline.play()
timeline.commit()
self.assertAlmostEqual(timeline.get_current_time(), zoom_start)
timeline.rewind_one_frame()
timeline.commit()
self.assertAlmostEqual(timeline.get_current_time(), zoom_end)
timeline.forward_one_frame()
timeline.commit()
self.assertAlmostEqual(timeline.get_current_time(), zoom_start)
timeline.set_current_time(zoom_start + 1)
timeline.stop()
timeline.commit()
self.assertAlmostEqual(timeline.get_current_time(), zoom_start)
omni.timeline.destroy_timeline(timeline_name)
def _on_timeline_event(self, e: carb.events.IEvent):
self._buffered_evts.put(e)
def _verify_evt(
self, type: omni.timeline.TimelineEventType, payload_key: str = None, payload_val=None, exact=False
):
try:
evt = self._buffered_evts.get_nowait()
if evt:
self.assertEqual(evt.type, int(type))
if payload_key and payload_val:
if exact:
self.assertEqual(evt.payload[payload_key], payload_val)
else:
self.assertAlmostEqual(evt.payload[payload_key], payload_val, places=4)
except queue.Empty:
self.assertTrue(False, "Expect event in queue but queue is empty")
# verifies that the an event of the given type exists in the queue, and its payload matches
def _verify_evt_exists(
self, type: omni.timeline.TimelineEventType, payload_key: str = None, payload_val=None, exact=False
):
found = False
while not self._buffered_evts.empty():
evt = self._buffered_evts.get_nowait()
if evt and evt.type == int(type):
found = True
if payload_key and payload_val:
if exact:
self.assertEqual(evt.payload[payload_key], payload_val)
else:
self.assertAlmostEqual(evt.payload[payload_key], payload_val, places=4)
self.assertTrue(found, f"Event {type} was not found in the queue.")
def _clear_evt_queue(self):
while not self._buffered_evts.empty():
# clear the buffer
self._buffered_evts.get_nowait()
def _sleep(self, _):
sleep(1.0)
def _save_runloop_dt(self, e: carb.events.IEvent):
self._runloop_dt = e.payload['dt']
def _assert_no_change_then_commit(self, old_value, new_value):
self.assertEqual(old_value, new_value)
self.assertTrue(self._buffered_evts.empty())
self._timeline.commit()
def _test_zoom_change(
self,
timeline,
start_time,
end_time,
expected_is_zoomed,
expected_start_time,
expected_end_time,
payload_key,
payload_value,
exact=True
):
timeline.set_zoom_range(start_time, end_time)
timeline.commit()
self.assertAlmostEqual(timeline.get_zoom_start_time(), expected_start_time)
self.assertAlmostEqual(timeline.get_zoom_end_time(), expected_end_time)
self.assertEqual(expected_is_zoomed, timeline.is_zoomed())
self._verify_evt(omni.timeline.TimelineEventType.ZOOM_CHANGED, payload_key, payload_value, exact)
self.assertTrue(self._buffered_evts.empty())
| 56,075 | Python | 46.643161 | 125 | 0.640892 |
omniverse-code/kit/exts/omni.timeline/omni/timeline/tests/test_thread_safety.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.events
import omni.kit.app
import omni.kit.test
import omni.timeline
import carb.settings
import random
from threading import get_ident, Lock, Thread
from time import sleep
from typing import List
class TestTimelineThreadSafety(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._app = omni.kit.app.get_app()
self._timeline = omni.timeline.get_timeline_interface()
self._timeline.stop() # make sure other tests do not interfere
await self._app.next_update_async()
self._timeline.set_end_time(100)
self._timeline.set_start_time(0)
self._timeline.set_current_time(0)
self._timeline.set_time_codes_per_second(30)
self._timeline.clear_zoom()
await self._app.next_update_async()
self._buffered_evts = []
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self._setter_to_event_map = {
'set_auto_update': omni.timeline.TimelineEventType.AUTO_UPDATE_CHANGED,
'set_prerolling': omni.timeline.TimelineEventType.PREROLLING_CHANGED,
'set_looping': omni.timeline.TimelineEventType.LOOP_MODE_CHANGED,
'set_fast_mode': omni.timeline.TimelineEventType.FAST_MODE_CHANGED,
'set_target_framerate': omni.timeline.TimelineEventType.TARGET_FRAMERATE_CHANGED,
'set_current_time': omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
'set_start_time': omni.timeline.TimelineEventType.START_TIME_CHANGED,
'set_end_time': omni.timeline.TimelineEventType.END_TIME_CHANGED,
'set_time_codes_per_second': omni.timeline.TimelineEventType.TIME_CODE_PER_SECOND_CHANGED,
'set_ticks_per_frame': omni.timeline.TimelineEventType.TICKS_PER_FRAME_CHANGED,
'set_tentative_time': omni.timeline.TimelineEventType.TENTATIVE_TIME_CHANGED,
'play': omni.timeline.TimelineEventType.PLAY,
'pause': omni.timeline.TimelineEventType.PAUSE,
'stop': omni.timeline.TimelineEventType.STOP,
'rewind_one_frame': omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
'forward_one_frame': omni.timeline.TimelineEventType.CURRENT_TIME_TICKED,
}
async def tearDown(self):
self._timeline = None
self._timeline_sub = None
async def test_setters(self):
self._main_thread_id = get_ident()
all_setters = ['set_auto_update', 'set_prerolling', 'set_looping', 'set_fast_mode', 'set_target_framerate',
'set_current_time', 'set_start_time', 'set_end_time', 'set_time_codes_per_second', 'set_ticks_per_frame',
'set_tentative_time']
all_getters = ['is_auto_updating', 'is_prerolling', 'is_looping', 'get_fast_mode', 'get_target_framerate',
'get_current_time', 'get_start_time', 'get_end_time', 'get_time_codes_per_seconds', 'get_ticks_per_frame',
'get_tentative_time']
all_values_to_set = [[True, False], [True, False], [True, False], [True, False], [24, 30, 60, 100],
[0, 10, 12, 20], [0, 10], [20, 100], [24, 30, 60], [1, 2, 4],
[0, 10, 12, 20]]
self.assertEqual(len(all_getters), len(all_setters))
self.assertEqual(len(all_getters), len(all_values_to_set))
# Run for every attribute individually
for i in range(len(all_setters)):
print(f'Thread safety test for timeline method {all_setters[i]}')
# Trying all values
await self.do_multithreaded_test([[all_setters[i]]], [[all_getters[i]]], [[all_values_to_set[i]]], 200, 100)
# Setting a single value, no other values should appear. Making sure the initial value is what we'll set.
getattr(self._timeline, all_setters[i])(all_values_to_set[i][0])
await self._app.next_update_async()
await self.do_multithreaded_test([[all_setters[i]]], [[all_getters[i]]], [[[all_values_to_set[i][0]]]], 50, 50)
# Run for all attributes
print('Thread safety test for all timeline methods')
await self.do_multithreaded_test([all_setters], [all_getters], [all_values_to_set], 100, 100)
async def test_time_control(self):
self._main_thread_id = get_ident()
all_methods = ['play', 'pause', 'stop', 'rewind_one_frame', 'forward_one_frame']
await self.do_multithreaded_test([all_methods], [None], [None], 50, 50)
async def do_multithreaded_test(
self,
setters: List[List[str]],
getters: List[List[str]],
values_to_set: List[list],
thread_count_per_type: int = 50,
thread_runs: int = 50):
MIN_SLEEP = 0.01
SLEEP_RANGE = 0.05
self.assertEqual(len(setters), len(getters))
for i, setter_list in enumerate(setters):
if values_to_set[i] is not None:
self.assertEqual(len(setter_list), len(values_to_set[i]))
lock = Lock()
running_threads = 0
def do(runs: int, thread_id: int, setters: List[str], getters: List[str], values_to_set: list, running_threads: int):
with lock:
running_threads = running_threads + 1
if getters is not None:
self.assertEqual(len(setters), len(getters))
if values_to_set is not None:
self.assertEqual(len(setters), len(values_to_set))
timeline = omni.timeline.get_timeline_interface()
rnd = random.Random()
rnd.seed(thread_id)
for run in range(runs):
i_attr = rnd.randint(0, len(setters) - 1)
if values_to_set is not None: # setter is a setter method that accepts a value
values = values_to_set[i_attr]
i_value = rnd.randint(0, len(values) - 1)
getattr(timeline, setters[i_attr])(values[i_value])
# We might want to see this when running tests, commented out for now
# print(f'Thread {thread_id} has called {setters[i_attr]}({values[i_value]})')
else: # "setter" is a method with no parameter (e.g. play())
getattr(timeline, setters[i_attr])()
sleep(MIN_SLEEP + rnd.random() * SLEEP_RANGE)
if getters is not None and values_to_set is not None:
current_value = getattr(timeline, getters[i_attr])()
self.assertTrue(current_value in values, f'Invalid value in thread {thread_id}: {current_value} is not in {values}')
with lock:
running_threads = running_threads - 1
thread_id = 0
threads = []
for thread_type_idx, setter in enumerate(setters):
for i in range(thread_count_per_type):
threads.append(
Thread(
target = do,
args = (
thread_runs,
thread_id,
setters[thread_type_idx],
getters[thread_type_idx],
values_to_set[thread_type_idx],
running_threads
)
)
)
threads[-1].start()
thread_id = thread_id + 1
self._buffered_evts = []
threads_running = True
while threads_running:
await self._app.next_update_async()
with lock:
threads_running = running_threads > 0
for thread in threads:
thread.join()
# an extra update to trigger last callbacks
await self._app.next_update_async()
# validate that we received only the expected events
all_setters = []
for setter_list in setters:
for setter in setter_list:
all_setters.append(setter)
allowed_events = [int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED_PERMANENT)]
for setter in all_setters:
allowed_events.append(int(self._setter_to_event_map[setter]))
for evt in self._buffered_evts:
self.assertTrue(evt in allowed_events, f'Error: event {evt} is not in allowed events {allowed_events} for setters {all_setters}')
def _on_timeline_event(self, e: carb.events.IEvent):
# callbacks are on the main thread
self.assertEqual(get_ident(), self._main_thread_id)
# save event type
self._buffered_evts.append(e.type)
| 9,135 | Python | 45.141414 | 141 | 0.592556 |
omniverse-code/kit/exts/omni.timeline/omni/timeline/tests/__init__.py | from .tests import *
from .test_thread_safety import * | 54 | Python | 26.499987 | 33 | 0.759259 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_node_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["GraphNodeDelegate"]
from .graph_model import GraphModel
from .graph_node_delegate_closed import GraphNodeDelegateClosed
from .graph_node_delegate_full import GraphNodeDelegateFull
from .graph_node_delegate_router import GraphNodeDelegateRouter
from pathlib import Path
import omni.ui as ui
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
# The main colors
LABEL_COLOR = 0xFFB4B4B4
BACKGROUND_COLOR = 0xFF34302A
BORDER_DEFAULT = 0xFFDBA656
BORDER_SELECTED = 0xFFFFFFFF
CONNECTION = 0xFF80C280
NODE_BACKGROUND = 0xFF675853
NODE_BACKGROUND_SELECTED = 0xFF7F6C66
class GraphNodeDelegate(GraphNodeDelegateRouter):
"""
The delegate with the Omniverse design that has both full and collapsed states.
"""
def __init__(self):
super().__init__()
def is_closed(model, node):
expansion_state = model[node].expansion_state
return expansion_state == GraphModel.ExpansionState.CLOSED
# Initial setup is the delegates for full and closed states.
self.add_route(GraphNodeDelegateFull())
self.add_route(GraphNodeDelegateClosed(), expression=is_closed)
@staticmethod
def get_style():
"""Return style that can be used with this delegate"""
style = {
"Graph": {"background_color": BACKGROUND_COLOR},
"Graph.Connection": {"color": CONNECTION, "background_color": CONNECTION, "border_width": 2.0},
# Node
"Graph.Node.Background": {"background_color": NODE_BACKGROUND},
"Graph.Node.Background:selected": {"background_color": NODE_BACKGROUND_SELECTED},
"Graph.Node.Border": {"background_color": BORDER_DEFAULT},
"Graph.Node.Border:selected": {"background_color": BORDER_SELECTED},
"Graph.Node.Resize": {"background_color": BORDER_DEFAULT},
"Graph.Node.Resize:selected": {"background_color": BORDER_SELECTED},
"Graph.Node.Description": {"color": LABEL_COLOR},
"Graph.Node.Description.Edit": {"color": LABEL_COLOR, "background_color": NODE_BACKGROUND},
# Header Input
"Graph.Node.Input": {
"background_color": BORDER_DEFAULT,
"border_color": BORDER_DEFAULT,
"border_width": 3.0,
},
# Header
"Graph.Node.Header.Label": {"color": 0xFFB4B4B4, "margin_height": 5.0, "font_size": 14.0},
"Graph.Node.Header.Label::Degenerated": {"font_size": 22.0},
"Graph.Node.Header.Collapse": {
"background_color": 0x0,
"padding": 0,
"image_url": f"{ICON_PATH}/hamburger-open.svg",
},
"Graph.Node.Header.Collapse::Minimized": {"image_url": f"{ICON_PATH}/hamburger-minimized.svg"},
"Graph.Node.Header.Collapse::Closed": {"image_url": f"{ICON_PATH}/hamburger-closed.svg"},
# Header Output
"Graph.Node.Output": {
"background_color": BACKGROUND_COLOR,
"border_color": BORDER_DEFAULT,
"border_width": 3.0,
},
# Port Group
"Graph.Node.Port.Group": {"color": 0xFFB4B4B4},
"Graph.Node.Port.Group::Plus": {"image_url": f"{ICON_PATH}/Plus.svg"},
"Graph.Node.Port.Group::Minus": {"image_url": f"{ICON_PATH}/Minus.svg"},
# Port Input
"Graph.Node.Port.Input": {
"background_color": BORDER_DEFAULT,
"border_color": BORDER_DEFAULT,
"border_width": 3.0,
},
"Graph.Node.Port.Input:selected": {"border_color": BORDER_SELECTED},
"Graph.Node.Port.Input.CustomColor": {"background_color": 0x0},
# Port
"Graph.Node.Port.Branch": {
"color": 0xFFB4B4B4,
"border_width": 0.75,
},
"Graph.Node.Port.Label": {
"color": 0xFFB4B4B4,
"margin_width": 5.0,
"margin_height": 3.0,
"font_size": 14.0,
},
"Graph.Node.Port.Label::output": {"alignment": ui.Alignment.RIGHT},
# Port Output
"Graph.Node.Port.Output": {
"background_color": BACKGROUND_COLOR,
"border_color": BORDER_DEFAULT,
"border_width": 3.0,
},
"Graph.Node.Port.Output.CustomColor": {"background_color": 0x0, "border_color": 0x0, "border_width": 3.0},
# Footer
"Graph.Node.Footer": {
"background_color": BACKGROUND_COLOR,
"border_color": BORDER_DEFAULT,
"border_width": 3.0,
"border_radius": 8.0,
},
"Graph.Node.Footer:selected": {"border_color": BORDER_SELECTED},
"Graph.Node.Footer.Image": {"image_url": f"{ICON_PATH}/0101.svg", "color": BORDER_DEFAULT},
"Graph.Selecion.Rect": {
"background_color": ui.color(1.0, 1.0, 1.0, 0.1),
"border_color": ui.color(1.0, 1.0, 1.0, 0.5),
"border_width": 1,
},
}
return style
@staticmethod
def specialized_color_style(name, color, icon, icon_tint_color=None):
"""
Return part of the style that has everything to color special node type.
Args:
name: Node type
color: Node color
icon: Filename to the icon the node type should display
icon_tint_color: Icon tint color
"""
style = {
# Node
f"Graph.Node.Border::{name}": {"background_color": color},
# Header Input
f"Graph.Node.Input::{name}": {"background_color": color, "border_color": color},
# Header Output
f"Graph.Node.Output::{name}": {"border_color": color},
# Port Input
f"Graph.Node.Port.Input::{name}": {"background_color": color, "border_color": color},
f"Graph.Node.Port.Input::{name}:selected": {"background_color": color, "BORDER_SELECTED": color},
# Port Output
f"Graph.Node.Port.Output::{name}": {"border_color": color},
# Footer
f"Graph.Node.Footer::{name}": {"border_color": color},
f"Graph.Node.Footer.Image::{name}": {"image_url": icon, "color": icon_tint_color or color},
}
return style
@staticmethod
def specialized_port_style(name, color):
"""
Return part of the style that has everything to color the customizable part of the port.
Args:
name: Port type type
color: Port color
"""
style = {
f"Graph.Node.Port.Input.CustomColor::{name}": {"background_color": color},
f"Graph.Node.Port.Output.CustomColor::{name}": {"background_color": color, "border_color": color},
f"Graph.Connection::{name}": {"color": color, "background_color": color},
}
return style
| 7,536 | Python | 41.342696 | 118 | 0.574973 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/isolation_graph_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["IsolationGraphModel"]
from .graph_model import GraphModel
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from .graph_model_batch_position_helper import GraphModelBatchPositionHelper
def _get_ports_recursive(model, root):
"""Recursively get all the ports"""
ports = model[root].ports
if ports:
recursive = []
for port in ports:
recursive.append(port)
subports = _get_ports_recursive(model, port)
if subports:
recursive += subports
return recursive
return ports
class IsolationGraphModel:
class MagicWrapperMeta(type):
"""
Python always looks in the class (and parent classes) __dict__ for
magic methods and __getattr__ doesn't work, but since we want to
override them, we need to use this trick with proxy property.
It makes the class looking like the source object.
See https://stackoverflow.com/questions/9057669 for details.
"""
def __init__(cls, name, bases, dct):
ignore = "class mro new init setattr getattribute dict"
def make_proxy(name):
def proxy(self, *args):
return getattr(self.source, name)
return proxy
type.__init__(cls, name, bases, dct)
ignore = set("__%s__" % n for n in ignore.split())
for name in dir(cls):
if name.startswith("__"):
if name not in ignore and name not in dct:
setattr(cls, name, property(make_proxy(name)))
class EmptyPort:
"""Is used by the model for an empty port"""
def __init__(self, parent: Union["IsolationGraphModel.InputNode", "IsolationGraphModel.OutputNode"]):
self.parent = parent
@staticmethod
def get_type_name() -> str:
"""The string type that goes the source model abd view"""
return "EmptyPort"
class InputNode(metaclass=MagicWrapperMeta):
"""
Is used by the model for the input node. This node represents input
ports of the compound node and it's placed to the subnetwork of the
compound.
"""
def __init__(self, model: GraphModel, source):
self._model = model
self._inputs = []
self.source = source
# TODO: circular reference
self.empty_port = IsolationGraphModel.EmptyPort(self)
def __getattr__(self, attr):
return getattr(self.source, attr)
def __hash__(self):
# Hash should be different from source and from OutputNode
return hash((self.source, "InputNode"))
@staticmethod
def get_type_name() -> str:
"""The string type that goes the source model and view"""
return "InputNode"
@property
def ports(self) -> Optional[List[Any]]:
"""The list of ports of this node. It only has input ports from the compound node."""
ports = _get_ports_recursive(self._model, self.source)
if ports is not None:
inputs = [(port, self._model[port].inputs) for port in ports]
self._inputs = [(p, i) for p, i in inputs if i is not None]
return [p for p, _ in self._inputs] + [self.empty_port]
class OutputNode(metaclass=MagicWrapperMeta):
"""
Is used by the model for the ouput node. This node represents output
ports of the comound node and it's placed to the subnetwork of the
compound.
"""
def __init__(self, model: GraphModel, source):
self.source = source
self._model = model
self._outputs = []
# TODO: circular reference
self.empty_port = IsolationGraphModel.EmptyPort(self)
def __getattr__(self, attr):
return getattr(self.source, attr)
def __hash__(self):
# Hash should be different from source and from InputNode
return hash((self.source, "OutputNode"))
@staticmethod
def get_type_name() -> str:
"""The string type that goes the source model and view"""
return "OutputNode"
@property
def ports(self) -> Optional[List[Any]]:
"""The list of ports of this node. It only has output ports from the compound node."""
ports = self._model[self.source].ports
if ports is not None:
outputs = [(port, self._model[port].outputs) for port in ports]
self._outputs = [(p, o) for p, o in outputs if o is not None]
return [p for p, _ in self._outputs] + [self.empty_port]
class _IsolationItemProxy(GraphModel._ItemProxy):
"""
The proxy class that redirects the model calls from view to the
source model or to the isolation model.
"""
def __init__(self, model: GraphModel, item: Any, isolation_model: "IsolationGraphModel"):
super().__init__(model, item)
object.__setattr__(self, "_isolation_model", isolation_model)
def __setattr__(self, attr, value):
"""
Called when an attribute assignment is attempted. This is called
instead of the normal mechanism (i.e. store the value in the
instance dictionary).
"""
if hasattr(type(self), attr):
proxy_property = getattr(type(self), attr)
proxy_property.fset(self, value)
else:
super().__setattr__(attr, value)
def is_input_node(
self, item: Union["IsolationGraphModel.InputNode", "IsolationGraphModel.OutputNode"] = None
) -> bool:
"""True if the current redirection is related to the input node"""
if item is None:
item = self._item
return isinstance(item, IsolationGraphModel.InputNode)
def is_output_node(
self, item: Union["IsolationGraphModel.InputNode", "IsolationGraphModel.OutputNode"] = None
) -> bool:
"""True if the current redirection is related to the output node"""
if item is None:
item = self._item
return isinstance(item, IsolationGraphModel.OutputNode)
def is_empty_port(self, item: "IsolationGraphModel.EmptyPort" = None) -> bool:
"""True if the current redirection is related to the empty port"""
if item is None:
item = self._item
return isinstance(item, IsolationGraphModel.EmptyPort)
# The methods of the model
@property
def name(self) -> str:
"""Redirects call to the source model if it's the model of the source model"""
if self.is_input_node():
return self._model[self._item.source].name + " (input)"
elif self.is_output_node():
return self._model[self._item.source].name + " (output)"
elif self.is_empty_port():
return type(self._item).get_type_name()
else:
return self._model[self._item].name
@name.setter
def name(self, value: str):
# Usually it's redirected automatically, but since we overrided property getter, we need to override setter
if self.is_input_node() or self.is_output_node():
self._model[self._item.source].name = value
else:
self._model[self._item].name = value
@property
def type(self) -> str:
"""Redirects call to the source model if it's the model of the source model"""
if self.is_input_node() or self.is_output_node() or self.is_empty_port():
return type(self._item).get_type_name()
else:
return self._model[self._item].type
@property
def ports(self) -> Optional[List[Any]]:
"""Redirects call to the source model if it's the model of the source model"""
if self.is_input_node() or self.is_output_node():
ports = self._item.ports
elif self.is_empty_port():
# TODO: Sub-ports
return
else:
ports = self._model[self._item].ports
# Save it for the future, so we know which ports belong to the current sub-network.
# TODO: read from cache when second call
for port in ports or []:
self._isolation_model._ports[port] = self._item
self._isolation_model._nodes[self._item] = ports
return ports
@ports.setter
def ports(self, value: List[Any]):
if self.is_input_node():
# Pretend like we set the ports of the compound node of the source model.
filtered = list(self._isolation_model._root_outputs.keys())
for port in value:
if self.is_empty_port(port):
continue
filtered.append(port)
self._model[self._item.source].ports = filtered
elif self.is_output_node():
# Pretend like we set the ports of the compound node of the source model.
filtered = []
for port in value:
if self.is_empty_port(port):
continue
filtered.append(port)
filtered += list(self._isolation_model._root_inputs.keys())
self._model[self._item.source].ports = filtered
else:
# Just redirect the call
self._model[self._item].ports = value
@property
def inputs(self) -> Optional[List[Any]]:
if self.is_empty_port():
if self.is_output_node(self._item.parent):
# Show dot on the left side
return []
else:
return
elif self._item in self._isolation_model._root_ports:
# This is the port of the root compound node
inputs = self._isolation_model._root_outputs.get(self._item, None)
if inputs is None:
return
else:
inputs = self._model[self._item].inputs
if not inputs:
return inputs
# Filter out the connections that go outside of this isolated model
return [
i
for i in inputs
if i in self._isolation_model._ports
or i in self._isolation_model._root_inputs
or i in self._isolation_model._root_outputs
]
@inputs.setter
def inputs(self, value: List[Any]):
if self.is_empty_port():
# The request to connect something to the Empty port of InputNode or OutputNode
target = self._item.parent.source
elif self.is_input_node() or self.is_output_node():
# The request to connect something to the InputNode or OutputNode itself
target = self._item.source
else:
target = self._item
if value is not None:
filtered = []
for p in value:
if isinstance(p, IsolationGraphModel.EmptyPort):
# If it's an EmptyPort, we need to connect it to the
# source directly. When the model receives the request
# to connect to the node itself, it will create a port
# for it.
source = p.parent.source
filtered.append(source)
else:
filtered.append(p)
value = filtered
self._model[target].inputs = value
@property
def outputs(self) -> Optional[List[Any]]:
if self.is_empty_port():
if self.is_input_node(self._item.parent):
# Show dot on the right side
return []
else:
return
elif self._item in self._isolation_model._root_ports:
outputs = self._isolation_model._root_inputs.get(self._item)
if outputs is None:
return
else:
outputs = self._model[self._item].outputs
if not outputs:
return outputs
# Filter out the connections that go outside of this isolated model
return [
o
for o in outputs
if o in self._isolation_model._ports
or o in self._isolation_model._root_inputs
or o in self._isolation_model._root_outputs
]
@property
def position(self) -> Optional[Tuple[float]]:
if self.is_input_node():
if self._isolation_model._root_inputs:
# TODO: It's not good to keep the position on the first available port. We need to group them.
port_to_keep_position = list(self._isolation_model._root_inputs.keys())[0]
position = self._model[port_to_keep_position].position
if position is not None:
return position
elif self._isolation_model._input_position:
return self._isolation_model._input_position
else:
return self._isolation_model._input_position
elif self.is_output_node():
if self._isolation_model._root_outputs:
# TODO: It's not good to keep the position on the first available port. We need to group them.
port_to_keep_position = list(self._isolation_model._root_outputs.keys())[0]
position = self._model[port_to_keep_position].position
if position is not None:
return position
elif self._isolation_model._output_position:
return self._isolation_model._output_position
else:
return self._isolation_model._output_position
else:
return self._model[self._item].position
@position.setter
def position(self, value: Optional[Tuple[float]]):
if self.is_input_node():
if self._isolation_model._root_inputs:
# TODO: get the proper port_to_keep_position
port_to_keep_position = list(self._isolation_model._root_inputs.keys())[0]
self._model[port_to_keep_position].position = value
else:
self._isolation_model._input_position = value
elif self.is_output_node():
if self._isolation_model._root_outputs:
# TODO: get the proper port_to_keep_position
port_to_keep_position = list(self._isolation_model._root_outputs.keys())[0]
self._model[port_to_keep_position].position = value
else:
self._isolation_model._output_position = value
else:
self._model[self._item].position = value
@property
def size(self) -> Optional[Tuple[float]]:
if self.is_input_node() or self.is_output_node():
# Can't set/get size of input/output node
return
else:
return self._model[self._item].size
@size.setter
def size(self, value: Optional[Tuple[float]]):
if self.is_input_node() or self.is_output_node():
# Can't set/get size of input/output node
pass
else:
self._model[self._item].size = value
@property
def display_color(self) -> Optional[Tuple[float]]:
if self.is_input_node() or self.is_output_node():
# Can't set/get display_color of input/output node
return
else:
return self._model[self._item].display_color
@display_color.setter
def display_color(self, value: Optional[Tuple[float]]):
if self.is_input_node() or self.is_output_node():
# Can't set display color of input/output
pass
else:
self._model[self._item].display_color = value
@property
def stacking_order(self) -> int:
if self.is_input_node() or self.is_output_node():
return 1
else:
return self._model[self._item].stacking_order
@property
def preview(self) -> Any:
"""Redirects call to the source model if it's the model of the source model"""
if self.is_input_node() or self.is_output_node():
return self._model[self._item.source].preview
else:
return self._model[self._item].preview
@property
def icon(self) -> Any:
"""Redirects call to the source model if it's the model of the source model"""
if self.is_input_node() or self.is_output_node():
return self._model[self._item.source].icon
else:
return self._model[self._item].icon
@property
def preview_state(self) -> GraphModel.PreviewState:
"""Redirects call to the source model if it's the model of the source model"""
if self.is_input_node() or self.is_output_node():
return self._model[self._item.source].preview_state
else:
return self._model[self._item].preview_state
@preview_state.setter
def preview_state(self, value: GraphModel.PreviewState):
if self.is_input_node() or self.is_output_node():
self._model[self._item.source].preview_state = value
else:
self._model[self._item].preview_state = value
############################################################################
def __getattr__(self, attr):
"""Pretend it's self._model"""
return getattr(self._model, attr)
def __getitem__(self, item):
"""Called to implement evaluation of self[key]"""
# Return a proxy that redirects its properties back to the model.
# return self._model[item]
return self._IsolationItemProxy(self._model, item, self)
def __init__(self, model: GraphModel, root):
self._model: Optional[GraphModel] = model
# It's important to set the proxy to set the position through this model
if self._model and isinstance(self._model, GraphModelBatchPositionHelper):
self._model.batch_proxy = self
self._root = root
self.clear_caches()
# Redirect events from the original model to here
self.__on_item_changed = GraphModel._Event()
self.__on_selection_changed = GraphModel._Event()
self.__on_node_changed = GraphModel._Event()
self.__item_changed_subscription = self._model.subscribe_item_changed(self._item_changed)
self.__selection_changed_subscription = self._model.subscribe_selection_changed(self._selection_changed)
self.__node_changed_subscription = self._model.subscribe_node_changed(self._rebuild_node)
# We create input and output nodes for the attributes of the parent compound
# node. When the parent doesn't have attributes, we need to keep the
# position locally.
self._input_position = None
self._output_position = None
# Virtual nodes
if self._root is not None and self._root_inputs:
self._input_nodes = [IsolationGraphModel.InputNode(self._model, self._root)]
else:
self._input_nodes = []
if self._root is not None and self._root_outputs:
self._output_nodes = [IsolationGraphModel.OutputNode(self._model, self._root)]
else:
self._output_nodes = []
def destroy(self):
self._model = None
self._root = None
self._ports = {}
self._nodes = {}
self._root_inputs = {}
self._root_outputs = {}
self.__on_item_changed = GraphModel._Event()
self.__on_selection_changed = GraphModel._Event()
self.__on_node_changed = GraphModel._Event()
self.__item_changed_subscription = None
self.__selection_changed_subscription = None
self._input_nodes = []
self._output_nodes = []
def clear_caches(self):
# Port to node
# TODO: WeakKeyDictionary
self._ports: Dict[Any, Any] = {}
# Nodes to ports
# TODO: WeakKeyDictionary
self._nodes: Dict[Any, Any] = {}
# Cache ports and inputs
self._root_ports: List[Any] = _get_ports_recursive(self._model, self._root) if (self._root is not None) else []
# Port to input/output
self._root_inputs: Dict[Any, Any] = {}
self._root_outputs: Dict[Any, Any] = {}
for p in self._root_ports or []:
inputs = self._model[p].inputs
if inputs is not None:
self._root_inputs[p] = inputs
outputs = self._model[p].outputs
if outputs is not None:
self._root_outputs[p] = outputs
def add_input_or_output(self, position: Tuple[float], is_input: bool = True):
if is_input:
if self._input_nodes:
# TODO: Remove when we can handle many nodes
if self._root_inputs:
# Set the position of the input node if the position is not set
port_position = list(self._root_inputs.keys())[0]
if not self[port_position].position:
self[port_position].position = position
return
node = IsolationGraphModel.InputNode(self._model, self._root)
self._input_nodes.append(node)
else:
if self._output_nodes:
# TODO: Remove when we can handle many nodes
if self._root_outputs:
# Set the position of the output node if the position is not set
port_position = list(self._root_outputs.keys())[0]
if not self[port_position].position:
self[port_position].position = position
return
node = IsolationGraphModel.OutputNode(self._model, self._root)
self._output_nodes.append(node)
self[node].position = position
# TODO: Root is changed
self._item_changed(None)
def _item_changed(self, item=None):
"""Call the event object that has the list of functions"""
if item is None:
self.clear_caches()
if item == self._root:
# Root item is changed. Rebuild all.
self.clear_caches()
item = None
if item in self._root_inputs.keys():
self.__on_item_changed(self._input_nodes[0])
elif item in self._root_outputs.keys():
self.__on_item_changed(self._output_nodes[0])
else:
# TODO: Filter unnecessary calls
self.__on_item_changed(item)
def subscribe_item_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_item_changed, fn)
def _selection_changed(self):
"""Call the event object that has the list of functions"""
# TODO: Filter unnecessary calls
self.__on_selection_changed()
def _rebuild_node(self, item=None, full=False):
"""Call the event object that has the list of functions"""
self.__on_node_changed(item, full=full)
def subscribe_selection_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_selection_changed, fn)
def subscribe_node_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_node_changed, fn)
@property
def nodes(self, item: Any = None):
"""It's only called to get the nodes from the top level"""
nodes = self._model[self._root].nodes
if nodes is not None:
# Inject the input and the output nodes
nodes += self._input_nodes + self._output_nodes
return nodes
def can_connect(self, source: Any, target: Any):
"""Return if it's possible to connect source to target"""
if isinstance(source, IsolationGraphModel.EmptyPort) or isinstance(target, IsolationGraphModel.EmptyPort):
return True
return self._model.can_connect(source, target)
def position_begin_edit(self, item: Any):
if isinstance(item, IsolationGraphModel.InputNode):
if self._root_inputs:
# The position of the input node
port_to_keep_position = list(self._root_inputs.keys())[0]
self._model.position_begin_edit(port_to_keep_position)
elif isinstance(item, IsolationGraphModel.OutputNode):
if self._root_outputs:
# The position of the output node
port_to_keep_position = list(self._root_outputs.keys())[0]
self._model.position_begin_edit(port_to_keep_position)
else:
# Position of the regular node
self._model.position_begin_edit(item)
def position_end_edit(self, item: Any):
if isinstance(item, IsolationGraphModel.InputNode):
if self._root_inputs:
# The position of the input node
port_to_keep_position = list(self._root_inputs.keys())[0]
self._model.position_end_edit(port_to_keep_position)
elif isinstance(item, IsolationGraphModel.OutputNode):
if self._root_outputs:
# The position of the output node
port_to_keep_position = list(self._root_outputs.keys())[0]
self._model.position_end_edit(port_to_keep_position)
else:
# Position of the regular node
self._model.position_end_edit(item)
@property
def selection(self) -> Optional[List[Any]]:
# Redirect to the model. We need it to override the setter
if self._model:
return self._model.selection
@selection.setter
def selection(self, value: Optional[List[Any]]):
if not self._model:
return
# Remove InputNode and OutputNode from selection
filtered = []
for v in value:
if not isinstance(v, IsolationGraphModel.EmptyPort):
filtered.append(v)
self._model.selection = filtered
| 27,756 | Python | 40 | 119 | 0.558834 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/backdrop_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["BackdropDelegate"]
from .abstract_graph_node_delegate import GraphNodeDescription
from .graph_node_delegate_full import GraphNodeDelegateFull
from .graph_node_delegate_full import LINE_VISIBLE_MIN
from .graph_node_delegate_full import TEXT_VISIBLE_MIN
import omni.ui as ui
class BackdropDelegate(GraphNodeDelegateFull):
"""
The delegate with the Omniverse design for the nodes of the closed state.
"""
def node_header(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the top of the node"""
node = node_desc.node
def set_color(model, node, item_model):
sub_models = item_model.get_item_children()
rgb = (
item_model.get_item_value_model(sub_models[0]).as_float,
item_model.get_item_value_model(sub_models[1]).as_float,
item_model.get_item_value_model(sub_models[2]).as_float,
)
model[node].display_color = rgb
with ui.ZStack(skip_draw_when_clipped=True):
with ui.VStack():
self._common_node_header_top(model, node)
with ui.VStack():
ui.Spacer(height=23)
color_widget = ui.ColorWidget(width=20, height=20, style={"margin": 1})
sub_models = color_widget.model.get_item_children()
# This constant is BORDER_DEFAULT = 0xFFDBA656
border_color = model[node].display_color or (0.337, 0.651, 0.859)
color_widget.model.get_item_value_model(sub_models[0]).as_float = border_color[0]
color_widget.model.get_item_value_model(sub_models[1]).as_float = border_color[1]
color_widget.model.get_item_value_model(sub_models[2]).as_float = border_color[2]
color_widget.model.add_end_edit_fn(lambda m, i: set_color(model, node, m))
def node_background(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the node background"""
node = node_desc.node
# Constants from GraphNodeDelegateFull.node_background
MARGIN_WIDTH = 7.5
MARGIN_TOP = 20.0
MARGIN_BOTTOM = 25.0
BORDER_THICKNESS = 3.0
BORDER_RADIUS = 3.5
HEADER_HEIGHT = 25.0
MIN_WIDTH = 180.0
TRIANGLE = 20.0
MIN_HEIGHT = 50.0
def on_size_changed(placer, model, node):
offset_x = placer.offset_x
offset_y = placer.offset_y
model[node].size = (offset_x.value, offset_y.value)
if offset_x.value < MIN_WIDTH:
placer.offset_x = MIN_WIDTH
if offset_y.value < MIN_HEIGHT:
placer.offset_y = MIN_HEIGHT
def set_description(field: ui.StringField, model: "GraphModel", node: any, description: str):
"""Called to set the description on the model and remove the field with the description"""
model[node].description = description
field.visible = False
def on_description(model: "GraphModel", node: any, frame: ui.Frame, description: str):
"""Called to create a field on the node to edit description"""
with frame:
field = ui.StringField(multiline=True, style_type_name_override="Graph.Node.Description.Edit")
if description:
field.model.as_string = description
field.model.add_end_edit_fn(lambda m: set_description(field, model, node, m.as_string))
field.focus_keyboard()
width, height = model[node].size or (MIN_WIDTH, MIN_HEIGHT)
with ui.ZStack(width=0, height=0):
super().node_background(model, node_desc)
# Properly alighned description
with ui.VStack():
ui.Spacer(height=HEADER_HEIGHT + MARGIN_TOP)
with ui.HStack():
ui.Spacer(width=MARGIN_WIDTH + BORDER_THICKNESS)
with ui.ZStack():
description = model[node].description
if description:
ui.Label(
description,
alignment=ui.Alignment.LEFT_TOP,
style_type_name_override="Graph.Node.Description",
)
# Frame with description field
frame = ui.Frame()
frame.set_mouse_double_clicked_fn(
lambda x, y, b, m, f=frame, d=description: on_description(model, node, f, d)
)
ui.Spacer(width=MARGIN_WIDTH + BORDER_THICKNESS)
ui.Spacer(height=MARGIN_BOTTOM + BORDER_THICKNESS)
# The triangle that resizes the node
with ui.VStack():
with ui.HStack():
placer = ui.Placer(draggable=True)
placer.offset_x = width
placer.offset_y = height
placer.set_offset_x_changed_fn(lambda _, p=placer, m=model, n=node: on_size_changed(p, m, n))
placer.set_offset_y_changed_fn(lambda _, p=placer, m=model, n=node: on_size_changed(p, m, n))
with placer:
triangle = ui.Triangle(
width=TRIANGLE,
height=TRIANGLE,
alignment=ui.Alignment.RIGHT_TOP,
style_type_name_override="Graph.Node.Resize",
)
triangle.set_mouse_pressed_fn(lambda x, y, b, m: b == 0 and model.size_begin_edit(node))
triangle.set_mouse_released_fn(lambda x, y, b, m: b == 0 and model.size_end_edit(node))
ui.Spacer(width=MARGIN_WIDTH + 0.5 * BORDER_THICKNESS)
ui.Spacer(height=MARGIN_BOTTOM + BORDER_THICKNESS)
def node_footer(self, model, node_desc: GraphNodeDescription):
pass
| 6,494 | Python | 44.41958 | 113 | 0.569911 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_node_delegate_full.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__ = ["color_to_hex", "GraphNodeDelegateFull"]
from .abstract_graph_node_delegate import AbstractGraphNodeDelegate
from .abstract_graph_node_delegate import GraphConnectionDescription
from .abstract_graph_node_delegate import GraphNodeDescription
from .abstract_graph_node_delegate import GraphNodeLayout
from .abstract_graph_node_delegate import GraphPortDescription
from .graph_model import GraphModel
from functools import partial
import colorsys
import math
import omni.ui as ui
# Zoom level when the text disappears and the replacement line appears
TEXT_VISIBLE_MIN = 0.6
# Zoom level when the line disappears
LINE_VISIBLE_MIN = 0.15
CONNECTION_CURVE = 60
def color_to_hex(color: tuple) -> int:
"""Convert float rgb to int"""
def to_int(f: float) -> int:
return int(255 * max(0.0, min(1.0, f)))
red = to_int(color[0])
green = to_int(color[1])
blue = to_int(color[2])
alpha = to_int(color[3]) if len(color) > 3 else 255
return (alpha << 8 * 3) + (blue << 8 * 2) + (green << 8 * 1) + red
class GraphNodeDelegateFull(AbstractGraphNodeDelegate):
"""
The delegate with the Omniverse design.
"""
def __init__(self, scale_factor=1.0):
self._scale_factor = scale_factor
def __scale(self, value):
"""Return the value multiplied by global scale multiplier"""
return value * self._scale_factor
def __build_rectangle(self, radius, width, height, draw_top, style_name, name, style_override=None):
"""
Build rectangle of the specific design.
Args:
radius: The radius of round corers. The corners are top-left and
bottom-right.
width: The width of triangle to cut. The top-right and
bottom-left trialgles are cut.
height: The height of triangle to cut. The top-right and
bottom-left trialgles are cut.
draw_top: When false the top corners are straight.
style_name: style_type_name_override of each widget
name: name of each widget
style_override: the style to apply to the top level node
"""
stack = ui.VStack()
if style_override:
stack.set_style(style_override)
with stack:
# Top of the rectangle
if draw_top:
with ui.HStack(height=0):
with ui.VStack(width=0):
ui.Circle(
radius=radius,
width=0,
height=0,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.RIGHT_BOTTOM,
style_type_name_override=style_name,
name=name,
)
ui.Rectangle(style_type_name_override=style_name, name=name)
ui.Rectangle(style_type_name_override=style_name, name=name)
ui.Triangle(
width=width,
height=height,
alignment=ui.Alignment.LEFT_TOP,
style_type_name_override=style_name,
name=name,
)
# Middle of the rectangle
ui.Rectangle(style_type_name_override=style_name, name=name)
# Bottom of the rectangle
with ui.HStack(height=0):
ui.Triangle(
width=width,
height=height,
alignment=ui.Alignment.RIGHT_BOTTOM,
style_type_name_override=style_name,
name=name,
)
ui.Rectangle(style_type_name_override=style_name, name=name)
with ui.VStack(width=0):
ui.Rectangle(style_type_name_override=style_name, name=name)
ui.Circle(
radius=radius,
width=0,
height=0,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_TOP,
style_type_name_override=style_name,
name=name,
)
# TODO: build_node_footer_input/build_node_footer_output
def node_background(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the node background"""
node = node_desc.node
# Constants
MARGIN_WIDTH = 7.5
MARGIN_TOP = 20.0
MARGIN_BOTTOM = 25.0
BORDER_THICKNESS = 3.0
BORDER_RADIUS = 3.5
HEADER_HEIGHT = 25.0
MIN_WIDTH = 180.0
TRIANGLE = 20.0
# Computed values
left_right_offset = MARGIN_WIDTH - BORDER_THICKNESS * 0.5
outer_radius = BORDER_RADIUS + BORDER_THICKNESS * 0.5
inner_radius = BORDER_RADIUS - BORDER_THICKNESS * 0.5
# The size of the triangle
outer_triangle = TRIANGLE
# The size of the triangle to make the thickness of the diagonal line
# the same as horizontal and vertial thickness. Works only with 45
# degrees diagonals
inner_triangle = outer_triangle - BORDER_THICKNESS / (
math.sqrt(2) * math.tan(math.radians((180.0 - 45.0) / 2.0))
)
style_name = str(model[node].type)
# Draw a rectangle and a top line
with ui.HStack():
# Left offset
ui.Spacer(width=self.__scale(left_right_offset))
with ui.VStack():
ui.Spacer(height=self.__scale(MARGIN_TOP))
# The node body
with ui.ZStack():
# This trick makes min width
ui.Spacer(width=self.__scale(MIN_WIDTH))
# The color override for the border
border_color = model[node].display_color
if border_color:
style = {"Graph.Node.Border": {"background_color": color_to_hex(border_color)}}
else:
style = None
# Build outer rectangle
self.__build_rectangle(
self.__scale(outer_radius),
self.__scale(outer_triangle),
self.__scale(outer_triangle),
True,
"Graph.Node.Border",
style_name,
style,
)
# Build inner rectangle
with ui.VStack():
ui.Spacer(height=self.__scale(HEADER_HEIGHT))
with ui.HStack():
ui.Spacer(width=self.__scale(BORDER_THICKNESS))
if border_color:
# 140% lightness from the border color
# 50% saturation from the border color
L_MULT = 1.4
S_MULT = 0.5
hls = colorsys.rgb_to_hls(border_color[0], border_color[1], border_color[2])
rgb = colorsys.hls_to_rgb(hls[0], min(1.0, (hls[1] * L_MULT)), hls[2] * S_MULT)
if len(border_color) > 3: # alpha
rgb = rgb + (border_color[3],)
style = {"background_color": color_to_hex(rgb)}
else:
style = None
self.__build_rectangle(
self.__scale(inner_radius),
self.__scale(inner_triangle),
self.__scale(inner_triangle),
False,
"Graph.Node.Background",
style_name,
style,
)
ui.Spacer(width=self.__scale(BORDER_THICKNESS))
ui.Spacer(height=self.__scale(BORDER_THICKNESS))
ui.Spacer(height=self.__scale(MARGIN_BOTTOM))
# Right offset
ui.Spacer(width=self.__scale(left_right_offset))
def node_header_input(self, model, node_desc: GraphNodeDescription):
"""Called to create the left part of the header that will be used as input when the node is collapsed"""
ui.Spacer(width=self.__scale(8))
def node_header_output(self, model, node_desc: GraphNodeDescription):
"""Called to create the right part of the header that will be used as output when the node is collapsed"""
ui.Spacer(width=self.__scale(8))
def _common_node_header_top(self, model, node):
"""Node header part that is used in both full and closed states"""
def switch_expansion(model, node):
current = model[node].expansion_state
model[node].expansion_state = GraphModel.ExpansionState((current.value + 1) % 3)
# Draw the node name and a bit of space
with ui.ZStack(width=0):
ui.Label(model[node].name, style_type_name_override="Graph.Node.Header.Label", visible_min=TEXT_VISIBLE_MIN)
with ui.Placer(stable_size=True, visible_min=LINE_VISIBLE_MIN, visible_max=TEXT_VISIBLE_MIN, offset_y=-8):
ui.Label(model[node].name, name="Degenerated", style_type_name_override="Graph.Node.Header.Label")
with ui.HStack():
# Collapse button
collapse = ui.ImageWithProvider(
width=self.__scale(18), height=self.__scale(18), style_type_name_override="Graph.Node.Header.Collapse"
)
expansion_state = model[node].expansion_state
if expansion_state == GraphModel.ExpansionState.CLOSED:
collapse.name = "Closed"
elif expansion_state == GraphModel.ExpansionState.MINIMIZED:
collapse.name = "Minimized"
else:
collapse.name = "Open"
collapse.set_mouse_pressed_fn(lambda x, y, b, m, model=model, node=node: switch_expansion(model, node))
def node_header(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the top of the node"""
with ui.VStack(skip_draw_when_clipped=True):
self._common_node_header_top(model, node_desc.node)
ui.Spacer(height=self.__scale(8))
def node_footer(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the bottom of the node"""
node = node_desc.node
style_name = str(model[node].type)
# Draw the circle and the image on the top of it
with ui.VStack(visible_min=LINE_VISIBLE_MIN, skip_draw_when_clipped=True):
ui.Spacer(height=self.__scale(10))
with ui.HStack(height=0):
ui.Spacer()
with ui.ZStack(width=self.__scale(50), height=self.__scale(50)):
ui.Rectangle(
style_type_name_override="Graph.Node.Footer", name=style_name, visible_min=TEXT_VISIBLE_MIN
)
ui.ImageWithProvider(
style_type_name_override="Graph.Node.Footer.Image",
name=style_name,
visible_min=TEXT_VISIBLE_MIN,
)
# Scale up the icon when zooming out
with ui.Placer(
stable_size=True,
visible_min=LINE_VISIBLE_MIN,
visible_max=TEXT_VISIBLE_MIN,
offset_x=self.__scale(-15),
offset_y=self.__scale(-30),
):
with ui.ZStack(width=0, height=0):
ui.Rectangle(style_type_name_override="Graph.Node.Footer", name=style_name)
ui.ImageWithProvider(
style_type_name_override="Graph.Node.Footer.Image",
name=style_name,
width=self.__scale(80),
height=self.__scale(80),
)
ui.Spacer()
ui.Spacer(height=self.__scale(2))
def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the left part of the port that will be used as input"""
node = node_desc.node
port = port_desc.port
connected_source = port_desc.connected_source
connected_target = port_desc.connected_target
if port is None:
ui.Spacer(width=self.__scale(7.5))
return
outputs = model[port].outputs
is_output = outputs is not None
if is_output:
ui.Spacer(width=self.__scale(7.5))
return
style_type_name = "Graph.Node.Port.Input"
customcolor_style_type_name = "Graph.Node.Port.Input.CustomColor"
inputs = model[port].inputs
node_type = str(model[node].type)
port_type = str(model[port].type)
with ui.HStack(skip_draw_when_clipped=True):
ui.Spacer(width=self.__scale(6))
with ui.ZStack(width=self.__scale(8)):
if inputs is not None:
# Half-circle that shows the port is able to have input connection
# Background of the node color
ui.Circle(
radius=self.__scale(6),
name=node_type,
style_type_name_override=style_type_name,
size_policy=ui.CircleSizePolicy.FIXED,
style={"border_color": 0x0, "border_width": 0},
alignment=ui.Alignment.LEFT_CENTER,
arc=ui.Alignment.RIGHT,
visible_min=TEXT_VISIBLE_MIN,
)
# Port has unique color
ui.Circle(
radius=self.__scale(6),
name=port_type,
style_type_name_override=customcolor_style_type_name,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_CENTER,
arc=ui.Alignment.RIGHT,
visible_min=TEXT_VISIBLE_MIN,
)
# Border of the node color
ui.Circle(
radius=self.__scale(6),
name=node_type,
style_type_name_override=style_type_name,
size_policy=ui.CircleSizePolicy.FIXED,
style={"background_color": 0x0},
alignment=ui.Alignment.LEFT_CENTER,
arc=ui.Alignment.RIGHT,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_source:
# Circle that shows that the port is a source for the connection
ui.Circle(
radius=self.__scale(7),
name=port_type,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.LEFT_CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_target:
# Circle that shows that the port is a target for the connection
ui.Circle(
radius=self.__scale(5),
name=port_type,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.LEFT_CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the right part of the port that will be used as output"""
node = node_desc.node
port = port_desc.port
connected_source = port_desc.connected_source
connected_target = port_desc.connected_target
if port is None:
ui.Spacer(width=self.__scale(7.5))
return
style_type_name = "Graph.Node.Port.Output"
customcolor_style_type_name = "Graph.Node.Port.Output.CustomColor"
outputs = model[port].outputs
inputs = model[port].inputs
node_type = str(model[node].type)
port_type = str(model[port].type)
with ui.ZStack(width=self.__scale(16), skip_draw_when_clipped=True):
if outputs is not None:
# Circle that shows the port is able to be an output connection
# Background of the node color
ui.Circle(
name=node_type,
style_type_name_override=style_type_name,
alignment=ui.Alignment.CENTER,
radius=self.__scale(6),
size_policy=ui.CircleSizePolicy.FIXED,
visible_min=TEXT_VISIBLE_MIN,
)
# Port has unique color
ui.Circle(
name=port_type,
style_type_name_override=customcolor_style_type_name,
style={"background_color": 0x0},
alignment=ui.Alignment.CENTER,
radius=self.__scale(6),
size_policy=ui.CircleSizePolicy.FIXED,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_source:
# Circle that shows that the port is a source for the connection
ui.Circle(
radius=self.__scale(7),
name=port_type,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_target or (outputs == [] and inputs):
# Circle that shows that the port is a target for the connection
ui.Circle(
radius=self.__scale(5),
name=port_type,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the middle part of the port"""
def set_expansion_state(model, port, state: GraphModel.ExpansionState, *args):
model[port].expansion_state = state
port = port_desc.port
level = port_desc.level
if port is None:
return
sub_ports = model[port].ports
is_group = sub_ports is not None
inputs = model[port].inputs
outputs = model[port].outputs
is_input = inputs is not None
is_output = outputs is not None
style_name = "input" if is_input and not is_output else "output"
with ui.HStack(skip_draw_when_clipped=True):
if level > 0:
style_type_name_override = "Graph.Node.Port.Branch"
if port_desc.relative_position == port_desc.parent_child_count - 1:
ui.Line(
width=4,
height=ui.Percent(50),
style_type_name_override=style_type_name_override,
alignment=ui.Alignment.RIGHT,
visible_min=TEXT_VISIBLE_MIN,
)
else:
ui.Line(
width=4,
style_type_name_override=style_type_name_override,
alignment=ui.Alignment.RIGHT,
visible_min=TEXT_VISIBLE_MIN,
)
ui.Line(
width=8,
style_type_name_override=style_type_name_override,
visible_min=TEXT_VISIBLE_MIN,
)
if is_group:
# +/- button
state = model[port].expansion_state
if state == GraphModel.ExpansionState.CLOSED:
image_name = "Plus"
next_state = GraphModel.ExpansionState.OPEN
else:
image_name = "Minus"
next_state = GraphModel.ExpansionState.CLOSED
ui.ImageWithProvider(
width=10,
style_type_name_override="Graph.Node.Port.Group",
name=image_name,
visible_min=TEXT_VISIBLE_MIN,
mouse_pressed_fn=partial(set_expansion_state, model, port, next_state),
)
with ui.ZStack():
ui.Label(
model[port].name,
style_type_name_override="Graph.Node.Port.Label",
name=style_name,
visible_min=TEXT_VISIBLE_MIN,
)
ui.Line(
style_type_name_override="Graph.Node.Port.Label",
visible_min=LINE_VISIBLE_MIN,
visible_max=TEXT_VISIBLE_MIN,
)
def connection(self, model, source: GraphConnectionDescription, target: GraphConnectionDescription):
"""Called to create the connection between ports"""
port_type = str(model[source.port].type)
if target.is_tangent_reversed != source.is_tangent_reversed:
# It's the same node connection. Set tangent in pixels.
start_tangent_width=ui.Pixel(20)
end_tangent_width=ui.Pixel(20)
else:
# If the connection is reversed, we need to mirror tangents
source_reverced_tangent = -1.0 if target.is_tangent_reversed else 1.0
target_reverced_gangent = -1.0 if source.is_tangent_reversed else 1.0
start_tangent_width=ui.Percent(-CONNECTION_CURVE * source_reverced_tangent)
end_tangent_width=ui.Percent(CONNECTION_CURVE * target_reverced_gangent)
ui.FreeBezierCurve(
target.widget,
source.widget,
start_tangent_width=start_tangent_width,
end_tangent_width=end_tangent_width,
name=port_type,
style_type_name_override="Graph.Connection",
)
| 23,474 | Python | 41.994505 | 120 | 0.516827 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_layout.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__ = ["SugiyamaLayout"]
from collections import defaultdict
from bisect import bisect
class SugiyamaLayout:
"""
Compute the coordinates for drawing directed graphs following the method
developed by Sugiyama.
This method consists of four phases:
1. Cycle Removal
2. Layer Assignment
3. Crossing Reduction
4. Coordinate Assignment
As input it takes the list of edges in the following format:
[(vertex1, vertex2), (vertex3, vertex4), ... ]
Once the object is created, it's possible to get the node layer number
immediately.
To get the node positions, it's necessary to set each node's size and
call `update_positions`.
Follows closely to the following papers:
[1] "An Efficient Implementation of Sugiyama's Algorithm for Layered Graph Drawing"
Eiglsperger Siebenhaller Kaufmann
[2] "Sugiyama Algorithm"
Nikolov
[3] "Graph Drawing Algorithms in Information Visualization"
Frishman
"""
class Node:
"""Temporary node that caches all the intermediate compute data"""
def __init__(self, id):
self.id = id
# Upstream and downstream nodes
self.upstream = []
self.downstream = []
# For iteration
self.is_currently_iterating = False
self.highest_iteration_index = 0
self.lowest_iteration_index = 0
# Layer and position
self.layer = None
self.is_dummy = False
# Barycenter is the position in the layer in [0..1] interval
self.barycenter = None
self.index_in_layer = None
# The final geometry
self.width = None
self.height = None
self.final_position = None
self.root = None
self.horizontal_aligned_to = None
self.vertical_aligned_to = None
self.offset = None
self.max_y = None
self.bound = [0.0, 0.0, 0.0, 0.0]
def add_upstream(self, node):
"""Add the upstream node. It will add current node to downstream as well."""
if node.id not in self.upstream:
self.upstream.append(node.id)
if self.id not in node.downstream:
node.downstream.append(self.id)
def __repr__(self):
result = f"<Node {self.id}: up"
for n in self.upstream:
result += f" {n}"
result += "; down"
for n in self.downstream:
result += f" {n}"
result += f"; layer_id{self.layer}>"
return result
def __init__(self, edges=[], vertical_distance=10.0, horizontal_distance=10.0):
# Minimal space between items
self.vertical_distance = vertical_distance
self.horizontal_distance = horizontal_distance
# Current alignment direction. It will call property setter.
self._alignment_direction = 0
# Counter for creating dummy nodes. Dummy nodes are negative ID.
self._dummy_counter = -1
self._edges = set(edges)
# All the nodes
self._nodes = {}
# Connected graphs
self._graphs = []
#
self._dummies = {}
# All the layers it's a dict with list of vertices id
self._layers = defaultdict(list)
# The action
self._split_to_graphs()
self._layout()
@property
def _alignment_direction(self):
return self.__alignment_direction
@property
def _alignment_direction_horizontal(self):
return self.__alignment_direction_horizontal
@property
def _alignment_direction_vertical(self):
return self.__alignment_direction_vertical
@_alignment_direction.setter
def _alignment_direction(self, alignment_direction):
"""
Alignment policy:
_alignment_direction=0 -> vertical=1, horizontal=-1
_alignment_direction=1 -> vertical=-1, horizontal=-1
_alignment_direction=2 -> vertical=1, horizontal=1
_alignment_direction=3 -> vertical=-1, horizontal=1
"""
self.__alignment_direction = alignment_direction
self.__alignment_direction_vertical, self.__alignment_direction_horizontal = {
0: (1, -1),
1: (-1, -1),
2: (1, 1),
3: (-1, 1),
}[alignment_direction]
@_alignment_direction_horizontal.setter
def _alignment_direction_horizontal(self, _alignment_direction_horizontal):
_alignment_direction = (_alignment_direction_horizontal + 1) + (1 - self.__alignment_direction_vertical) // 2
self._alignment_direction = _alignment_direction
@_alignment_direction_vertical.setter
def _alignment_direction_vertical(self, _alignment_direction_vertical):
_alignment_direction = (self.__alignment_direction_horizontal + 1) + (1 - _alignment_direction_vertical) // 2
self._alignment_direction = _alignment_direction
def _get_roots(self, graph):
# Nodes that doesn't have anything downstream
current_roots = []
for edge in graph:
vertex = edge[0]
if not self._nodes[vertex].downstream:
current_roots.append(self._nodes[vertex])
return current_roots
def __get_connected_dummy(self, node):
dummy_id = node.dummy_nodes.get(node.layer - 1, None)
return [dummy_id] if dummy_id is not None else []
def __is_between_dummies(self, node):
return any([x.is_dummy for x in self.__get_connected_dummy(node)])
def __iterate_node_edges(self, node, counter, visited, reversed_edges):
counter[0] += 1
node.highest_iteration_index = counter[0]
node.lowest_iteration_index = counter[0]
visited.append(node)
node.is_currently_iterating = True
for vertex in node.upstream:
upstream = self._nodes[vertex]
if upstream.highest_iteration_index == 0:
self.__iterate_node_edges(upstream, counter, visited, reversed_edges)
node.lowest_iteration_index = min(node.lowest_iteration_index, upstream.lowest_iteration_index)
elif upstream.is_currently_iterating:
# It's a loop. We need to invert this connection.
reversed_edges.append((node.id, upstream.id))
if upstream in visited:
node.lowest_iteration_index = min(node.lowest_iteration_index, upstream.highest_iteration_index)
if node.lowest_iteration_index == node.highest_iteration_index:
backtracing = [visited.pop()]
while backtracing[-1] != node:
backtracing.append(visited.pop())
node.is_currently_iterating = False
def _get_reversed_edges(self, graph, roots):
counter = [0]
visited = []
reversed_edges = []
for vertex, node in self._nodes.items():
node.highest_iteration_index = 0
# Start from roots
for root in roots:
self.__iterate_node_edges(root, counter, visited, reversed_edges)
# Iterate rest
for edge in graph:
for vertex in edge:
node = self._nodes[vertex]
if node.highest_iteration_index == 0:
self.__iterate_node_edges(node, counter, visited, reversed_edges)
return reversed_edges
def _invert_edge(self, edge):
"""Invert the flow direction of the given edge"""
v1 = edge[0]
v2 = edge[1]
node1 = self._nodes[v1]
node1.upstream.remove(v2)
node2 = self._nodes[v2]
node2.downstream.remove(v1)
node2.add_upstream(node1)
def _set_layer(self, node):
"""Set the layer id of the node"""
current_layer = node.layer
# Layers start from 1
new_layer = max([self._nodes[x].layer for x in node.downstream] + [0]) + 1
if current_layer == new_layer:
# Nothing changed
return
if current_layer is not None:
self._layers[current_layer].remove(node.id)
node.layer = new_layer
self._layers[node.layer].append(node.id)
def _iterate_layer(self, roots):
scaned_edges = {}
# Roots are in the first layer
current_layer = roots
while len(current_layer) > 0:
next_layer = []
for node in current_layer:
self._set_layer(node)
# Mark out-edges has scanned.
for vertex in node.upstream:
edge = (node.id, vertex)
scaned_edges[edge] = True
# Check if out-vertices are rank-able.
for x in node.upstream:
upstream = self._nodes[x]
if not (
False in [scaned_edges.get((vertex, upstream.id), False) for vertex in upstream.downstream]
):
if x not in next_layer:
next_layer.append(self._nodes[x])
current_layer = next_layer
def _create_dummy(self, layer, dummy_nodes):
"""Create a dummy node and put it to the layer."""
# Setup a new node
dummy_node = self._nodes[self._dummy_counter] = self.Node(self._dummy_counter)
self._dummy_counter -= 1
dummy_node.is_dummy = True
dummy_node.layer = layer
dummy_node.width = 0.0
dummy_node.height = 0.0
self._layers[layer].append(dummy_node.id)
dummy_node.dummy_nodes = dummy_nodes
dummy_nodes[layer] = dummy_node
return dummy_node
def _create_dummies(self, edge):
"""Create and all dummy nodes for the given edge."""
v1, v2 = edge
layer1, layer2 = self._nodes[v1].layer, self._nodes[v2].layer
if layer1 > layer2:
v1, v2 = v2, v1
layer1, layer2 = layer2, layer1
if (layer2 - layer1) > 1:
# "dummy vertices" are stored in the dict, keyed by their layer.
dummy_nodes = self._dummies[edge] = {}
node1 = self._nodes[v1]
node2 = self._nodes[v2]
dummy_nodes[layer1] = node1
dummy_nodes[layer2] = node2
# Disconnect the nodes
node1.upstream.remove(v2)
node2.downstream.remove(v1)
# Insert dummies between nodes
prev_dummy = node1
for layer_id in range(layer1 + 1, layer2):
dummy = self._create_dummy(layer_id, dummy_nodes)
prev_dummy.add_upstream(dummy)
prev_dummy = dummy
prev_dummy.add_upstream(node2)
def _get_cross_count(self, layer_id):
"""Number of crosses in the layer"""
neighbor_indices = []
layer = self._layers[layer_id]
for vertex in layer:
node = self._nodes[vertex]
neighbor_indices.extend(
sorted([self._nodes[neighbor].index_in_layer for neighbor in self._get_neighbors(node)])
)
s = []
count = 0
for i, neighbor_index in enumerate(neighbor_indices):
j = bisect(s, neighbor_index)
if j < i:
count += i - j
s.insert(j, neighbor_index)
return count
def _get_next_layer_id(self, layer_id):
"""The layer that is the next according to the current slignment direction"""
layer_id += 1 if self._alignment_direction_horizontal == -1 else -1
return layer_id
def _get_prev_layer_id(self, layer_id):
"""The layer that is the previous according to the current slignment direction"""
layer_id += 1 if self._alignment_direction_horizontal == 1 else -1
return layer_id
def _get_mean_value_position(self, node):
"""
Compute the position of the node according to the position of
neighbors in the previous layer. It's the mean value of adjacent
positions of neighbors.
"""
layer_id = node.layer
prev_layer = self._get_prev_layer_id(layer_id)
if prev_layer not in self._layers:
return node.barycenter
bars = [self._nodes[vertex].barycenter for vertex in self._get_neighbors(node)]
return node.barycenter if len(bars) == 0 else float(sum(bars)) / len(bars)
def _reduce_crossings(self, layer_id):
"""
Reorder the nodes in the layer to reduce the number of crossings in the layer.
Return the new number of crossing.
"""
layer = self._layers[layer_id]
num_nodes = len(layer)
total_crossings = 0
for i, j in zip(range(num_nodes - 1), range(1, num_nodes)):
vertex_i = layer[i]
vertex_j = layer[j]
barycenters_neighbors_i = [
self._nodes[vertex].barycenter for vertex in self._get_neighbors(self._nodes[vertex_i])
]
barycenters_neighbors_j = [
self._nodes[vertex].barycenter for vertex in self._get_neighbors(self._nodes[vertex_j])
]
crossings_ij = crossings_ji = 0
for neightbor_j in barycenters_neighbors_j:
crossings = len([neighbor_i for neighbor_i in barycenters_neighbors_i if neighbor_i > neightbor_j])
# Crossings we have now
crossings_ij += crossings
# Crossings we would have if swap verices
crossings_ji += len(barycenters_neighbors_i) - crossings
if crossings_ji < crossings_ij:
# Swap vertices
layer[i] = vertex_j
layer[j] = vertex_i
total_crossings += crossings_ji
else:
total_crossings += crossings_ij
return total_crossings
def _reorder(self, layer_id):
"""
Reorder the nodes within the layer to reduce the number of crossings in the layer.
Return the number of crossing.
"""
# TODO: Use code from _reduce_crossings to find the initial number of
# crossings.
c = self._get_cross_count(layer_id)
layer = self._layers[layer_id]
barycenter_height = 1.0 / (len(layer) - 1) if len(layer) > 1 else 1.0
if c > 0:
for vertex in layer:
node = self._nodes[vertex]
node.barycenter = self._get_mean_value_position(node)
# Reorder layers according to barycenter.
layer.sort(key=lambda x: self._nodes[x].barycenter)
c = self._reduce_crossings(layer_id)
# Re assign new position since it was reordered
for i, vertex in enumerate(layer):
self._nodes[vertex].index_in_layer = i
self._nodes[vertex].barycenter = i * barycenter_height
return c
def _ordering_pass(self, direction=-1):
"""
Ordering of the vertices such that the number of edge crossings is reduced.
"""
crossings = 0
self._alignment_direction_horizontal = direction
for layer_id in sorted(self._layers.keys())[::-direction]:
crossings += self._reorder(layer_id)
return crossings
def _get_neighbors(self, node):
"""
Neighbors are to left/right adjacent nodes. Node.upstream/downstream
have connections from all the layers. This returns from neighbour
layers according to the current alignment direction.
"""
alignment_direction_horizontal = self._alignment_direction_horizontal
# TODO: It's called very often. We need to cache it.
node.neighbors_at_direction = {-1: list(node.downstream), 1: list(node.upstream)}
if node.is_dummy:
return node.neighbors_at_direction[alignment_direction_horizontal]
for direction in (-1, 1):
tr = node.layer + direction
for i, x in enumerate(node.neighbors_at_direction[direction]):
if self._nodes[x].layer == tr:
continue
# TODO: check if we need this code. upstream/downstream has dummies.
edge = (node.id, x)
if edge not in self._dummies:
edge = (x, node.id)
dum = self._dummies[edge][tr]
node.neighbors_at_direction[direction][i] = dum.id
return node.neighbors_at_direction[alignment_direction_horizontal]
def _get_median_index(self, node):
"""
Find the position of node according to neigbor positions in neigbor layer.
"""
neighbors = self._get_neighbors(node)
index_in_layer = [self._nodes[x].index_in_layer for x in neighbors]
neighbors_size = len(index_in_layer)
if neighbors_size == 0:
return []
index_in_layer.sort()
index_in_layer = index_in_layer[:: self._alignment_direction_vertical]
i, j = divmod(neighbors_size - 1, 2)
return [index_in_layer[i]] if j == 0 else [index_in_layer[i], index_in_layer[i + j]]
def _horizontal_alignment(self):
"""
Horizontal alignment according to current alignment direction.
"""
alignment_direction_vertical, alignment_direction_horizontal = (
self._alignment_direction_vertical,
self._alignment_direction_horizontal,
)
for layer_id in sorted(self._layers.keys())[::-alignment_direction_horizontal]:
prev_layer_id = self._get_prev_layer_id(layer_id)
if prev_layer_id not in self._layers:
continue
current_vertex_index = None
layer = self._layers[layer_id]
prev_layer = self._layers[prev_layer_id]
for vertex in layer[::alignment_direction_vertical]:
node = self._nodes[vertex]
for median_vertex_index in self._get_median_index(node):
median_vertex = prev_layer[median_vertex_index]
if self._nodes[vertex].horizontal_aligned_to is vertex:
if alignment_direction_horizontal == 1:
edge = (vertex, median_vertex)
else:
edge = (median_vertex, vertex)
if edge in self._dummy_intersections:
continue
if (current_vertex_index is None) or (
alignment_direction_vertical * current_vertex_index
< alignment_direction_vertical * median_vertex_index
):
# Align median
self._nodes[median_vertex].horizontal_aligned_to = vertex
# Align the given one
median_root = self._nodes[median_vertex].root
self._nodes[vertex].horizontal_aligned_to = median_root
self._nodes[vertex].root = median_root
current_vertex_index = median_vertex_index
def _align_subnetwork(self, vertex):
"""
Vertical alignment according to current alignment direction.
"""
if self._nodes[vertex].max_y is not None:
return
self._nodes[vertex].max_y = 0.0
vertex_to_align = vertex
while True:
prev_index_in_layer = self._nodes[vertex_to_align].index_in_layer - self._alignment_direction_vertical
layer_id = self._nodes[vertex_to_align].layer
if 0 <= prev_index_in_layer < len(self._layers[layer_id]):
prev_vertex_id = self._layers[layer_id][prev_index_in_layer]
vertical_distance = (
self.vertical_distance
+ self._nodes[prev_vertex_id].height * 0.5
+ self._nodes[vertex_to_align].height * 0.5
)
# Recursively place subnetwork
root_vertex_id = self._nodes[prev_vertex_id].root
self._align_subnetwork(root_vertex_id)
# Adjust node position
if self._nodes[vertex].vertical_aligned_to is vertex:
self._nodes[vertex].vertical_aligned_to = self._nodes[root_vertex_id].vertical_aligned_to
if self._nodes[vertex].vertical_aligned_to == self._nodes[root_vertex_id].vertical_aligned_to:
self._nodes[vertex].max_y = max(
self._nodes[vertex].max_y, self._nodes[root_vertex_id].max_y + vertical_distance
)
else:
aligned_vertex = self._nodes[root_vertex_id].vertical_aligned_to
offset = self._nodes[vertex].max_y - self._nodes[root_vertex_id].max_y + vertical_distance
if self._nodes[aligned_vertex].offset is None:
self._nodes[aligned_vertex].offset = offset
else:
self._nodes[aligned_vertex].offset = min(self._nodes[aligned_vertex].offset, offset)
vertex_to_align = self._nodes[vertex_to_align].horizontal_aligned_to
if vertex_to_align is vertex:
# Already aligned
break
def _vertical_alignment(self):
"""
Vertical alignment according to current alignment direction.
"""
_alignment_direction_vertical, _alignment_direction_horizontal = (
self._alignment_direction_vertical,
self._alignment_direction_horizontal,
)
layer_ids = sorted(self._layers.keys())[::-_alignment_direction_horizontal]
for layer_id in layer_ids:
for vertex in self._layers[layer_id][::_alignment_direction_vertical]:
if self._nodes[vertex].root is vertex:
self._align_subnetwork(vertex)
# Mirror nodes when the alignment is bottom.
if _alignment_direction_vertical == -1:
for layer_id in layer_ids:
for vertex in self._layers[layer_id]:
y = self._nodes[vertex].max_y
if y:
self._nodes[vertex].max_y = -y
# Assign bound
bound = None
for layer_id in layer_ids:
for vertex in self._layers[layer_id][::_alignment_direction_vertical]:
self._nodes[vertex].bound[self._alignment_direction] = self._nodes[self._nodes[vertex].root].max_y
aligned_vertex = self._nodes[self._nodes[vertex].root].vertical_aligned_to
offset = self._nodes[aligned_vertex].offset
if offset is not None:
self._nodes[vertex].bound[self._alignment_direction] += _alignment_direction_vertical * offset
if bound is None:
bound = self._nodes[vertex].bound[self._alignment_direction]
else:
bound = min(bound, self._nodes[vertex].bound[self._alignment_direction])
# Initialize
for layer_id, layer in self._layers.items():
for vertex in layer:
self._nodes[vertex].root = vertex
self._nodes[vertex].horizontal_aligned_to = vertex
self._nodes[vertex].vertical_aligned_to = vertex
self._nodes[vertex].offset = None
self._nodes[vertex].max_y = None
def _split_to_graphs(self):
"""Split edges to multiple connected graphs. Result is self._graphs."""
# All vertices
vertices = set()
# Dict where key is vertex, value is all the connected vertices
dependencies = defaultdict(set)
for v1, v2 in self._edges:
vertices.add(v1)
vertices.add(v2)
dependencies[v1].add(v2)
dependencies[v2].add(v1)
if v1 in self._nodes:
n1 = self._nodes[v1]
else:
n1 = self.Node(v1)
self._nodes[v1] = n1
if v2 in self._nodes:
n2 = self._nodes[v2]
else:
n2 = self.Node(v2)
self._nodes[v2] = n2
n1.add_upstream(n2)
while vertices:
# Start with any vertex
current_vertices = [vertices.pop()]
# For each vertex, remove all connected from `vertices` and add it to current graph
for vertex in current_vertices:
for dependent in dependencies.get(vertex, []):
if dependent in vertices:
vertices.remove(dependent)
current_vertices.append(dependent)
# Here `current_vertices` has all the vertices that are conneted to a single graph
current_edges = set()
for vertex in current_vertices:
for edge in self._edges:
if edge[0] in current_vertices or edge[1] in current_vertices:
current_edges.add(edge)
self._graphs.append(current_edges)
def _find_dummy_intersections(self):
"""
Detect crossings in dummy nodes.
"""
self._dummy_intersections = []
for layer_id, layer_vertices in self._layers.items():
prev_layer_id = layer_id - 1
if prev_layer_id not in self._layers:
continue
first_vertex = 0
vertices_count = len(layer_vertices) - 1
prev_layer_vertices_count = len(self._layers[prev_layer_id]) - 1
vertex_range_from = 0
for i, current_vertex_id in enumerate(layer_vertices):
node = self._nodes[current_vertex_id]
if not node.is_dummy:
continue
if i == vertices_count or self.__is_between_dummies(node):
connected_dummy_index = prev_layer_vertices_count
if self.__is_between_dummies(node):
connected_dummy_index = self.__get_connected_dummy(node)[-1].index_in_layer
for vertex_in_this_layer in layer_vertices[vertex_range_from : i + 1]:
for neighbor in self._get_neighbors(self._nodes[vertex_in_this_layer]):
neighbor_index = self._nodes[neighbor].index_in_layer
if neighbor_index < first_vertex or neighbor_index > connected_dummy_index:
# Intersection found
self._dummy_intersections.append((neighbor, vertex_in_this_layer))
vertex_range_from = i + 1
first_vertex = connected_dummy_index
def _layout(self):
"""Perform first three steps of Sugiyama layouting"""
for graph in self._graphs:
# 1. Cycle Removal
roots = self._get_roots(graph)
reversed_edges = self._get_reversed_edges(graph, roots)
# Make the graph acyclic by reversing appropriate edges.
for edge in reversed_edges:
self._invert_edge(edge)
# Get roots one more time
roots += [node for node in self._get_roots(graph) if node not in roots]
# 2. Layer Assignment
self._iterate_layer(roots)
# TODO: Optimize layers. Root nodes could potentially go to other
# layers if it could minimize crossings
# Add dummies
for edge in graph:
self._create_dummies(edge)
# Pre-setup of some indices
for _, layer in self._layers.items():
# Barycenter is the position in the layer in [0..1] interval
barycenter_height = 1.0 / (len(layer) - 1) if len(layer) > 1 else 1.0
for i, vertex in enumerate(layer):
node = self._nodes[vertex]
node.index_in_layer = i
node.barycenter = i * barycenter_height
# 3. Crossing Reduction, 2 passes in both direction for optimal ordering
for i in range(2):
# Ordering pass for layers from 0 to end
crossings = self._ordering_pass()
if crossings > 0:
# Second pass in reverse direction
self._ordering_pass(direction=1)
self._ordering_pass()
# 3a. Crossing Reduction in dummy nodes
self._find_dummy_intersections()
def update_positions(self):
"""4. Coordinate Assignment"""
# Initialize node attributes.
# TODO: Put it to init
for _, layer in self._layers.items():
for vertex in layer:
node = self._nodes[vertex]
node.root = vertex
node.horizontal_aligned_to = vertex
node.vertical_aligned_to = vertex
node.offset = None
node.max_y = None
node.bound = [0.0, 0.0, 0.0, 0.0]
for _alignment_direction in range(4):
self._alignment_direction = _alignment_direction
self._horizontal_alignment()
self._vertical_alignment()
# Final coordinate assigment of all nodes:
x_counter = 0
for _, layer in self._layers.items():
if not layer:
continue
max_width = max([self._nodes[vertex].width / 2.0 for vertex in layer])
y_counter = None
for vertex in layer:
y = sorted(self._nodes[vertex].bound)
# Average of computed bound
average_y = (y[1] + y[2]) / 2.0
# Prevent node intersections
if y_counter is None:
y_counter = average_y
y_counter = max(y_counter, average_y)
# Final xy-coordinates. Negative X because we go from right to left.
self._nodes[vertex].final_position = (-x_counter - max_width, y_counter)
y_counter += self._nodes[vertex].height + self.vertical_distance
x_counter += 2 * max_width + self.horizontal_distance
def set_size(self, vertex, width, height):
"""Set the size of the node"""
node = self._nodes.get(vertex, None)
if not node:
# The node not in the list because the node is not connected to anythig.
# Since the graph layers start from 1, we put those non-graph
# vertices to the layer 0 and they will stay in a separate column.
layer_id = 0
node = self.Node(vertex)
node.layer = layer_id
node.index_in_layer = len(self._layers[layer_id])
self._nodes[node.id] = node
self._layers[layer_id].append(node.id)
node.width = width
node.height = height
def get_position(self, vertex):
"""The position of the node"""
node = self._nodes.get(vertex, None)
if node:
return node.final_position
def get_layer(self, vertex):
"""The layer id of the node"""
node = self._nodes.get(vertex, None)
if node:
return node.layer
| 31,702 | Python | 38.480697 | 117 | 0.562867 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_node_index.py | # Copyright (c) 2018-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__ = ["GraphNodeIndex"]
from .graph_model import GraphModel
from collections import defaultdict
from typing import Any, Set, Tuple
from typing import Dict
from typing import List
from typing import Optional
from typing import Union
import itertools
import weakref
class CachePort:
"""
The structure to keep in the ports and their properties and don't
access the model many times.
"""
def __init__(
self,
port: Any,
state: Optional[GraphModel.ExpansionState],
child_count: int,
level: int,
relative_position: int,
parent_child_count: int,
parent_cached_port: Optional[weakref.ProxyType] = None,
):
# Port from the model
self.port: Any = port
# Expansion state if it's a groop
self.state: Optional[GraphModel.ExpansionState] = state
# Number of children
self.child_count: int = child_count
# The level in the tree structure
self.level: int = level
# Position number in the parent list
self.relative_position = relative_position
# Number of children of the parent
self.parent_child_count = parent_child_count
# The visibility after collapsing
self.visibile: bool = True
# Inputs from the model
self.inputs: Optional[List[Any]] = None
# Outputs from the model
self.outputs: Optional[List[Any]] = None
self.parent_cached_node: Optional[weakref.ProxyType] = None
self.parent_cached_port: Optional[weakref.ProxyType] = parent_cached_port
def __repr__(self):
return f"<CachePort {self.port}>"
def __hash__(self):
if self.inputs:
inputs_hash = hash(tuple(hash(i) for i in self.inputs))
else:
inputs_hash = 0
if self.outputs:
outputs_hash = hash(tuple(hash(i) for i in self.outputs))
else:
outputs_hash = 0
return hash(
(
CachePort,
self.port,
self.state and self.state.value,
self.visibile,
inputs_hash,
outputs_hash,
)
)
def __eq__(self, other):
return hash(self) == hash(other)
class CacheNode:
"""The structure to keep in the cache and don't access the model many times"""
def __init__(
self,
node: Any,
state: Optional[GraphModel.ExpansionState],
cached_ports: List[CachePort],
stacking_order: int,
additional_hash=0,
):
# Node from the model
self.node: Any = node
# Expansion state if it's a groop
self.state: Optional[GraphModel.ExpansionState] = state
# Ports from the model
self.cached_ports: List[CachePort] = cached_ports
# Level represents the distance of the current node from the root
self.level = None
self.stacking_order: int = stacking_order
# The nodes dependent from the current node. If the nodes connected like this A.out -> B.in,
# then A.dependent = [B]
self.dependent = []
# Hash
self._additional_hash = additional_hash
self.inputs = []
self.outputs = []
# Add connection to the parent node
selfproxy = weakref.proxy(self)
for port in self.cached_ports:
port.parent_cached_node = selfproxy
def __repr__(self):
return f"<CacheNode {self.node}>"
def __hash__(self):
cached_ports_hash = hash(tuple(hash(p) for p in self.cached_ports))
return hash((CacheNode, self.node, self.state and self.state.value, cached_ports_hash, self._additional_hash))
def __eq__(self, other):
return hash(self) == hash(other)
class CacheConnection:
"""The structure to keep connections in the cache and don't access the model many times"""
def __init__(
self,
source_cached_port: CachePort,
target_cached_port: CachePort,
):
self.source_port: Any = source_cached_port.port
self.target_port: Any = target_cached_port.port
self.__hash = hash(
(
CacheConnection,
source_cached_port,
target_cached_port,
source_cached_port.parent_cached_node.__hash__(),
target_cached_port.parent_cached_node.__hash__(),
)
)
@property
def pair(self):
return (self.source_port, self.target_port)
def __repr__(self):
return f"<CacheConnection {self.pair}>"
def __hash__(self):
return self.__hash
def __eq__(self, other):
return hash(self) == hash(other)
class GraphNodeDiff:
"""
The object that keeps the difference that is the list of nodes and
connections to add and delete.
"""
def __init__(
self,
nodes_to_add: List[CacheNode] = None,
nodes_to_del: List[CacheNode] = None,
connections_to_add: List[CacheConnection] = None,
connections_to_del: List[CacheConnection] = None,
):
self.nodes_to_add = nodes_to_add
self.nodes_to_del = nodes_to_del
self.connections_to_add = connections_to_add
self.connections_to_del = connections_to_del
@property
def valid(self):
return (
self.nodes_to_add is not None
and self.nodes_to_del is not None
and self.connections_to_add is not None
and self.connections_to_del is not None
)
def __repr__(self):
return (
"<GraphNodeDiff\n"
f" Add: {self.nodes_to_add} {self.connections_to_add}\n"
f" Del: {self.nodes_to_del} {self.connections_to_del}\n"
">"
)
class GraphNodeIndex:
""" Hirarchy index of the model. Provides fast access to the nodes and connections."""
def __init__(self, model: Optional[GraphModel], port_grouping: bool):
# List of all the nodes from the model
self.cached_nodes: List[Optional[CacheNode]] = []
# List of all the connections from the model
self.cached_connections: List[Optional[CacheConnection]] = []
# Dictionary that has a node from the model as a key and the
# index of this node in all_cached_nodes.
self.node_to_id: Dict[Any, int] = {}
# Dictionary that has a port from the model as a key and the
# index of the parent node in self.cached_nodes.
self.port_to_id: Dict[Any, int] = {}
# Dictionary that has a port from the model as a key and the
# index of the port in cached_node.cached_ports.
port_to_port_id: Dict[Any, int] = {}
# Connection hash to ID in self.cached_connections.
self.connection_to_id: Dict[Tuple[Any, Any], int] = {}
# Set with all the ports from the model if this port is output. We need
# it to detect the flow direction.
self.ports_used_as_output = set()
# All the connections.
self.source_to_target = defaultdict(set)
# Dict[child port: parent port]
self.port_child_to_parent: Dict[Any, Any] = {}
if not model:
return
# Preparing the cache and indices.
for node in model.nodes or []:
# Caching ports
# TODO: Nested group support
root_ports = model[node].ports or []
root_port_count = len(root_ports)
cached_ports: List[CachePort] = []
for id, port in enumerate(root_ports):
if port_grouping:
sub_ports = model[port].ports
is_group = sub_ports is not None
else:
sub_ports = None
is_group = False
state = model[port].expansion_state
cached_port = CachePort(port, state, len(sub_ports) if is_group else 0, 0, id, root_port_count)
cached_ports.append(cached_port)
if is_group:
# TODO: Nested group support
cached_port_proxy = weakref.proxy(cached_port)
sub_port_count = len(sub_ports)
cached_sub_ports = [
CachePort(p, None, 0, 1, id, sub_port_count, cached_port_proxy)
for id, p in enumerate(sub_ports)
]
cached_ports += cached_sub_ports
# The ID of the current cached node in the cache
cached_node_id = len(self.cached_nodes)
# The global index
self.node_to_id[node] = cached_node_id
state = model[node].expansion_state
# Allows to draw backdrops in backgroud
stacking_order = model[node].stacking_order
# Hash name, description and color, so the node is autogenerated when it's changed.
additional_hash = hash((model[node].name, model[node].description, model[node].display_color))
# The global cache
self.cached_nodes.append(CacheNode(node, state, cached_ports, stacking_order, additional_hash))
# Cache connections
for cached_node_id, cached_node in enumerate(self.cached_nodes):
cached_ports = cached_node.cached_ports
# True if node has output node
node_has_outputs = False
# Parent port to put the connections to
cached_port_parent: Optional[CachePort] = None
# How many ports already hidden
hidden_port_counter = 0
# How many ports we need to hide
hidden_port_number = 0
# for port, port_state, port_child_count in zip(ports, port_states, port_child_counts):
for cached_port_id, cached_port in enumerate(cached_ports):
port = cached_port.port
# print("Cached ports", port, cached_port_id)
port_inputs = model[port].inputs
port_outputs = model[port].outputs
# Copy to detach from the model
port_inputs = port_inputs[:] if port_inputs is not None else None
port_outputs = port_outputs[:] if port_outputs is not None else None
cached_port.visibile = not cached_port_parent
if cached_port_parent:
# Put inputs/outputs to the parent
if port_inputs is not None:
cached_port_parent.inputs = cached_port_parent.inputs or []
cached_port_parent.inputs += port_inputs
if port_outputs is not None:
cached_port_parent.outputs = cached_port_parent.outputs or []
cached_port_parent.outputs += port_outputs
else:
# Put inputs/outputs to the port
cached_port.inputs = port_inputs
cached_port.outputs = port_outputs
if cached_port_parent:
connection_port = cached_port_parent.port
# Dict[child: parent]
self.port_child_to_parent[cached_port.port] = cached_port_parent.port
else:
connection_port = cached_port.port
if port_inputs:
for source in port_inputs:
# |--------| |-----------------|
# | source | ---> | connection_port |
# |--------| |-----------------|
# Ex:
# source is Usd.Prim(</World/Looks/OmniGlass/Shader>).GetAttribute('outputs:out')
# connection_port is Usd.Prim(</World/Looks/OmniGlass>).GetAttribute('outputs:mdl:displacement')
self.source_to_target[source].add(connection_port)
if port_outputs:
for source in port_outputs:
self.source_to_target[source].add(connection_port)
if port_outputs is not None:
node_has_outputs = True
self.port_to_id[port] = cached_node_id
port_to_port_id[port] = cached_port_id
# Check if the port is hidden and hide it. It happens
# when the port is collapsed.
if cached_port_parent:
hidden_port_counter += 1
hidden_port_number += cached_port.child_count
if hidden_port_counter == hidden_port_number:
# We hide enough
cached_port_parent = None
continue
if cached_port.child_count > 0 and cached_port.state == GraphModel.ExpansionState.CLOSED:
# The next one should be hidden
cached_port_parent = cached_port
hidden_port_counter = 0
hidden_port_number = cached_port.child_count
for cached_port in cached_ports:
# If the node don't have any output (in OmniGraph inputs and outputs are equal) we consider that all
# the input attributes are used as outputs.
if not node_has_outputs or cached_port.outputs is not None:
self.ports_used_as_output.add(cached_port.port)
# chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
cached_node.inputs = list(itertools.chain.from_iterable([p.inputs for p in cached_ports if p.inputs]))
cached_node.outputs = list(itertools.chain.from_iterable([p.outputs for p in cached_ports if p.outputs]))
# Replace input/output of cached ports to point to the parents of the collapsed ports
for cached_node in self.cached_nodes:
for cached_port in cached_node.cached_ports:
if cached_port.inputs:
inputs = []
for i in cached_port.inputs:
parent = self.port_child_to_parent.get(i, None)
if parent:
inputs.append(parent)
else:
inputs.append(i)
cached_port.inputs = inputs
if cached_port.outputs:
outputs = []
for i in cached_port.outputs:
parent = self.port_child_to_parent.get(i, None)
if parent:
outputs.append(parent)
else:
outputs.append(i)
cached_port.outputs = outputs
# Remove the collapsed ports from source_to_target and move the removed content to the port parents.
source_to_target_filtered = defaultdict(set)
for source, target in self.source_to_target.items():
if source in self.port_child_to_parent:
source_to_target_filtered[self.port_child_to_parent[source]].update(target)
else:
source_to_target_filtered[source].update(target)
self.source_to_target = source_to_target_filtered
# Save connections
for source, targets in self.source_to_target.items():
source_node_id = self.port_to_id[source]
source_port_id = port_to_port_id[source]
source_cached_port = self.cached_nodes[source_node_id].cached_ports[source_port_id]
for target in targets:
target_node_id = self.port_to_id[target]
target_port_id = port_to_port_id[target]
target_cached_port = self.cached_nodes[target_node_id].cached_ports[target_port_id]
connection = CacheConnection(source_cached_port, target_cached_port)
self.connection_to_id[connection.pair] = len(self.cached_connections)
self.cached_connections.append(connection)
def get_diff(self, other: "GraphNodeIndex"):
"""
Generate the difference object: the list of nodes and connections to add
and delete.
"""
# Nodes diff
self_nodes = set(self.cached_nodes[i] for _, i in self.node_to_id.items())
other_nodes = set(other.cached_nodes[i] for _, i in other.node_to_id.items())
nodes_to_add = list(other_nodes - self_nodes)
nodes_to_del = list(self_nodes - other_nodes)
if len(self.node_to_id) == len(nodes_to_del):
# If we need to remove all nodes, it's better to create a new graph node index
return GraphNodeDiff()
max_level = max(self.cached_nodes[i].stacking_order for _, i in self.node_to_id.items())
for node in nodes_to_add:
if node.stacking_order is not None and node.stacking_order < max_level:
# We can't put the node under others. Only to top.
return GraphNodeDiff()
# Connections diff
self_connections = set(self.cached_connections[i] for _, i in self.connection_to_id.items())
other_connections = set(other.cached_connections[i] for _, i in other.connection_to_id.items())
connections_to_add = list(other_connections - self_connections)
connections_to_del = list(self_connections - other_connections)
return GraphNodeDiff(nodes_to_add, nodes_to_del, connections_to_add, connections_to_del)
def mutate(self, diff: Union["GraphNodeIndex", GraphNodeDiff]) -> Tuple[Set]:
"""Apply the difference to the cache index."""
if isinstance(diff, GraphNodeIndex):
diff = self.get_diff(diff)
node_add = set()
node_del = set()
connection_add = set()
connection_del = set()
# Remove nodes from index
for cached_node in diff.nodes_to_del:
node = cached_node.node
node_id = self.node_to_id[node]
self.cached_nodes[node_id] = None
for cached_port in cached_node.cached_ports:
port = cached_port.port
self.port_to_id.pop(port)
if port in self.ports_used_as_output:
self.ports_used_as_output.remove(port)
self.port_child_to_parent.pop(port, None)
node_del.add(node)
self.node_to_id.pop(node)
# Remove connections from index
for cached_connection in diff.connections_to_del:
connection_id = self.connection_to_id[cached_connection.pair]
self.cached_connections[connection_id] = None
source_port = cached_connection.source_port
target_port = cached_connection.target_port
targets = self.source_to_target[source_port]
targets.remove(target_port)
if len(targets) == 0:
self.source_to_target.pop(source_port)
connection_del.add(cached_connection)
self.connection_to_id.pop(cached_connection.pair)
# Add nodes to index
for cached_node in diff.nodes_to_add:
node = cached_node.node
node_id = len(self.cached_nodes)
self.cached_nodes.append(cached_node)
self.node_to_id[node] = node_id
node_add.add(node)
cached_ports = cached_node.cached_ports
# True if node has output node
node_has_outputs = False
for cached_port in cached_ports:
port = cached_port.port
self.port_to_id[port] = node_id
self.ports_used_as_output
if cached_port.outputs is not None:
node_has_outputs = True
cached_port_parent = cached_port.parent_cached_port
if cached_port_parent:
self.port_child_to_parent[cached_port.port] = cached_port_parent.port
for cached_port in cached_ports:
# If the node don't have any output (in OmniGraph inputs and
# outputs are equal) we consider that all the input attributes
# are used as outputs.
if not node_has_outputs or cached_port.outputs is not None:
self.ports_used_as_output.add(cached_port.port)
# Add connections to index
for cached_connection in diff.connections_to_add:
connection_id = len(self.cached_connections)
self.cached_connections.append(cached_connection)
self.connection_to_id[cached_connection.pair] = connection_id
connection_add.add(cached_connection)
source_port = cached_connection.source_port
target_port = cached_connection.target_port
self.source_to_target[source_port].add(target_port)
return node_add, node_del, connection_add, connection_del
| 21,336 | Python | 38.078755 | 120 | 0.569226 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["GraphModel"]
from enum import Enum
from enum import IntFlag
from enum import auto
from typing import Any
from typing import Optional
from typing import Union
class GraphModel:
"""
The base class for the Graph model.
The model is the central component of the graph widget. It is the
application's dynamic data structure, independent of the user interface,
and it directly manages the data. It follows closely model–view pattern.
It defines the standard interface to be able to interoperate with the
components of the model-view architecture. It is not supposed to be
instantiated directly. Instead, the user should subclass it to create a
new model.
The model manages two kinds of data elements. Node and port are the
atomic data elements of the model. Both node and port can have any number
of sub-ports and any number of input and output connections.
There is no specific Python type for the elements of the model. Since
Python has dynamic types, the model can return any object as a node or a
port. When the widget needs to get a property of the node, it provides
the given node back to the model.
Example:
.. code:: python
class UsdShadeModel(GraphModel):
@property
def nodes(self, prim=None):
# Return Usd.Prim in a list
return [stage.GetPrimAtPath(selection)]
@property
def name(self, item=None):
# item here is Usd.Prim because UsdShadeModel.nodes returns
# Usd.Prim
return item.GetPath().name
# Accessing nodes and properties example
model = UsdShadeModel()
# UsdShadeModel decides the type of nodes. It's a list with Usd.Prim
nodes = model.nodes
for node in nodes:
# The node is accessed through evaluation of self[key]. It will
# return the proxy object that redirects its properties back to
# model. So the following line will call UsdShadeModel.name(node).
name = model[node].name
print(f"The model has node {name}")
"""
class _ItemProxy:
"""
The proxy that allows accessing the nodes and ports of the model
through evaluation of self[key]. This proxy object redirects its
properties to the model that has properties like this:
class Model:
@property
def name(self, item):
pass
@name.setter
def name(self, value, item):
pass
"""
def __init__(self, model, item):
"""Save model and item to be able to redirect the properties"""
# Since we already have __setattr__ reimplemented, the following
# code is the way to bypass it
super().__setattr__("_model", model)
super().__setattr__("_item", item)
def __getattr__(self, attr):
"""
Called when the default attribute access fails with an
AttributeError.
"""
model_property = getattr(type(self._model), attr)
return model_property.fget(self._model, self._item)
def __setattr__(self, attr, value):
"""
Called when an attribute assignment is attempted. This is called
instead of the normal mechanism (i.e. store the value in the
instance dictionary).
"""
model_property = getattr(type(self._model), attr)
model_property.fset(self._model, value, self._item)
# TODO: Maybe it's better to automatically call model._item_changed here?
# No, it's not better because in some cases node is changing and
# the widget doesn't change. For example when the user changes the
# position.
class _Event(set):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in list(self):
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({set.__repr__(self)})"
class ExpansionState(Enum):
OPEN = 0
MINIMIZED = 1
CLOSED = 2
class PreviewState(IntFlag):
NONE = 0
OPEN = auto()
CACHED = auto()
LARGE = auto()
class _EventSubscription:
"""
Event subscription.
_Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.add(self._fn)
def __del__(self):
"""Called by GC."""
self._event.remove(self._fn)
DISPLAY_NAME = None
def __init__(self):
super().__init__()
# TODO: begin_edit/end_edit
self.__on_item_changed = self._Event()
self.__on_selection_changed = self._Event()
self.__on_node_changed = self._Event()
def __getitem__(self, item):
"""Called to implement evaluation of self[key]"""
# Return a proxy that redirects its properties back to the model.
return self._ItemProxy(self, item)
def _item_changed(self, item=None):
"""Call the event object that has the list of functions"""
self.__on_item_changed(item)
def _rebuild_node(self, item=None, full=False):
"""Call the event object that has the list of functions"""
self.__on_node_changed(item, full=full)
def subscribe_item_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_item_changed, fn)
def _selection_changed(self):
"""Call the event object that has the list of functions"""
self.__on_selection_changed()
def subscribe_selection_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_selection_changed, fn)
def subscribe_node_changed(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_node_changed, fn)
@staticmethod
def has_nodes(obj):
"""Returns true if the model can currently build the graph network using the provided object"""
pass
# The list of properties of node and port.
@property
def name(self, item) -> str:
"""The name of the item how it should be displayed in the view"""
pass
@name.setter
def name(self, value: str, item=None):
"""Request to rename item"""
pass
@property
def type(self, item):
pass
@property
def inputs(self, item):
pass
@inputs.setter
def inputs(self, value, item=None):
pass
@property
def outputs(self, item):
pass
@outputs.setter
def outputs(self, value, item=None):
pass
@property
def nodes(self, item=None):
pass
@property
def ports(self, item=None):
pass
@ports.setter
def ports(self, value, item=None):
pass
@property
def expansion_state(self, item=None) -> ExpansionState:
return self.ExpansionState.OPEN
@expansion_state.setter
def expansion_state(self, value: ExpansionState, item=None):
pass
def can_connect(self, source, target):
"""Return if it's possible to connect source to target"""
return True
@property
def position(self, item=None):
"""Returns the position of the node"""
pass
@position.setter
def position(self, value, item=None):
"""The node position setter"""
pass
def position_begin_edit(self, item):
"""Called when the user started dragging the node"""
pass
def position_end_edit(self, item):
"""Called when the user finished dragging the node and released the mouse"""
pass
@property
def size(self, item):
"""The node size. Is used for nodes like Backdrop."""
pass
@size.setter
def size(self, value, item=None):
"""The node position setter"""
pass
def size_begin_edit(self, item):
"""Called when the user started resizing the node"""
pass
def size_end_edit(self, item):
"""Called when the user finished resizing the node and released the mouse"""
pass
@property
def description(self, item):
"""The text label that is displayed on the backdrop in the node graph."""
pass
@description.setter
def description(self, value, item=None):
"""The node description setter"""
pass
@property
def display_color(self, item):
"""The node color."""
pass
@display_color.setter
def display_color(self, value, item=None):
"""The node color setter"""
pass
@property
def stacking_order(self, item):
"""
This value is a hint when an application cares about the visibility
of a node and whether each node overlaps another.
"""
return 0
@property
def selection(self):
pass
@selection.setter
def selection(self, value: list):
pass
def special_select_widget(self, node, node_widget):
# Returning None means node_widget will get used
return None
def destroy(self):
pass
@property
def icon(self, item) -> Optional[Union[str, Any]]:
"""Return icon of the image"""
pass
@icon.setter
def icon(self, value: Optional[Union[str, Any]], item=None):
"""Set the icon of the image"""
pass
@property
def preview(self, item) -> Optional[Union[str, Any]]:
"""Return the preview of the image"""
pass
@preview.setter
def preview(self, value: Optional[Union[str, Any]], item=None):
"""Set the preview of the image"""
pass
@property
def preview_state(self, item) -> PreviewState:
"""Return the state of the preview of the node"""
return GraphModel.PreviewState.NONE
@preview_state.setter
def preview_state(self, value: PreviewState, item=None):
"""Set the state of the preview of the node"""
pass
| 11,338 | Python | 28.997354 | 103 | 0.602928 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/__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.
#
# This extension both provides generic Omni UI Graph interface and implements couple of graph models, including one for
# omni.graph. we need to split it eventually in 2 exts. So that one can use ui graph without omni.graph. For now
# just make it optional by handling import failure as non-error.
from .abstract_batch_position_getter import AbstractBatchPositionGetter
from .abstract_graph_node_delegate import AbstractGraphNodeDelegate
from .abstract_graph_node_delegate import GraphConnectionDescription
from .abstract_graph_node_delegate import GraphNodeDescription
from .abstract_graph_node_delegate import GraphNodeLayout
from .abstract_graph_node_delegate import GraphPortDescription
from .backdrop_delegate import BackdropDelegate
from .backdrop_getter import BackdropGetter
from .compound_node_delegate import CompoundInputOutputNodeDelegate
from .compound_node_delegate import CompoundNodeDelegate
from .graph_model import GraphModel
from .graph_model_batch_position_helper import GraphModelBatchPositionHelper
from .graph_node_delegate import GraphNodeDelegate
from .graph_node_delegate_router import GraphNodeDelegateRouter
from .graph_view import GraphView
from .isolation_graph_model import IsolationGraphModel
from .selection_getter import SelectionGetter
| 1,706 | Python | 54.064514 | 119 | 0.841149 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/compound_node_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CompoundNodeDelegate", "CompoundInputOutputNodeDelegate"]
from .abstract_graph_node_delegate import GraphNodeDescription
from .abstract_graph_node_delegate import GraphPortDescription
from .graph_node_delegate_full import GraphNodeDelegateFull
from typing import Any
from typing import List
import omni.ui as ui
class CompoundNodeDelegate(GraphNodeDelegateFull):
"""
The delegate for the compound nodes.
"""
pass
class CompoundInputOutputNodeDelegate(GraphNodeDelegateFull):
"""
The delegate for the input/output nodes of the compound.
"""
def __init__(self):
super().__init__()
self.__port_context_menu = None
def destroy(self):
self.__port_context_menu = None
def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
node = node_desc.node
port = port_desc.port
frame = ui.Frame()
with frame:
super().port_input(model, node_desc, port_desc)
frame.set_mouse_pressed_fn(lambda x, y, b, _, m=model, n=node, p=port: b == 1 and self.__on_menu(m, n, p))
def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
node = node_desc.node
port = port_desc.port
frame = ui.Frame()
with frame:
super().port_output(model, node_desc, port_desc)
frame.set_mouse_pressed_fn(lambda x, y, b, _, m=model, n=node, p=port: b == 1 and self.__on_menu(m, n, p))
def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
port = port_desc.port
stack = ui.ZStack()
with stack:
super().port(model, node_desc, port_desc)
# Draw input on top of the original port
field = ui.StringField(visible=False)
value_model = field.model
value_model.as_string = model[port].name
def begin_edit():
field.visible = True
def end_edit(value_model):
# Hide
field.visible = False
# Rename
model[port].name = value_model.as_string
# Activate input with double click
stack.set_mouse_double_clicked_fn(lambda x, y, b, m: begin_edit())
value_model.add_end_edit_fn(end_edit)
def __on_menu(self, model: "GraphModel", node: Any, port: Any):
def disconnect(model: "GraphModel", port: Any):
"""Disconnect everything from the given port"""
model[port].inputs = []
def remove(model: "GraphModel", node: Any, port: Any):
"""Remove the given port from the node"""
ports = model[node].ports
ports.remove(port)
model[node].ports = ports
def move_up(model: "GraphModel", node: Any, port: Any):
"""Move the given port one position up"""
ports: List = model[node].ports
index = ports.index(port)
if index > 0:
ports.insert(index - 1, ports.pop(index))
model[node].ports = ports
def move_down(model: "GraphModel", node: Any, port: Any):
"""Move the given port one position down"""
ports: List = model[node].ports
index = ports.index(port)
if index < len(ports) - 1:
ports.insert(index + 1, ports.pop(index))
model[node].ports = ports
def move_top(model: "GraphModel", node: Any, port: Any):
"""Move the given port to the top of the node"""
ports: List = model[node].ports
index = ports.index(port)
if index > 0:
ports.insert(0, ports.pop(index))
model[node].ports = ports
def move_bottom(model: "GraphModel", node: Any, port: Any):
"""Move the given port to the bottom of the node"""
ports: List = model[node].ports
index = ports.index(port)
if index < len(ports) - 1:
ports.insert(len(ports) - 1, ports.pop(index))
model[node].ports = ports
self.__port_context_menu = ui.Menu("CompoundInputOutputNodeDelegate Port Menu")
with self.__port_context_menu:
if model[port].inputs:
ui.MenuItem("Disconnect", triggered_fn=lambda m=model, p=port: disconnect(m, p))
ui.MenuItem("Remove", triggered_fn=lambda m=model, n=node, p=port: remove(m, n, p))
ui.MenuItem("Move Up", triggered_fn=lambda m=model, n=node, p=port: move_up(m, n, p))
ui.MenuItem("Move Down", triggered_fn=lambda m=model, n=node, p=port: move_down(m, n, p))
ui.MenuItem("Move Top", triggered_fn=lambda m=model, n=node, p=port: move_top(m, n, p))
ui.MenuItem("Move Bottom", triggered_fn=lambda m=model, n=node, p=port: move_bottom(m, n, p))
self.__port_context_menu.show()
| 5,359 | Python | 38.411764 | 114 | 0.605523 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_node_delegate_closed.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__ = ["GraphNodeDelegateClosed"]
from .abstract_graph_node_delegate import GraphNodeDescription
from .graph_node_delegate_full import GraphNodeDelegateFull
from .graph_node_delegate_full import LINE_VISIBLE_MIN
from .graph_node_delegate_full import TEXT_VISIBLE_MIN
import omni.ui as ui
class GraphNodeDelegateClosed(GraphNodeDelegateFull):
"""
The delegate with the Omniverse design for the nodes of the closed state.
"""
def __init__(self, scale_factor=1.0):
super().__init__(scale_factor)
def node_header_input(self, model, node_desc: GraphNodeDescription):
"""Called to create the left part of the header that will be used as input when the node is collapsed"""
node = node_desc.node
connected_source = node_desc.connected_source
connected_target = node_desc.connected_target
with ui.ZStack(width=8, skip_draw_when_clipped=True):
ui.Circle(
radius=6,
name=str(model[node].type),
style_type_name_override="Graph.Node.Input",
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.RIGHT_CENTER,
arc=ui.Alignment.RIGHT,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_source:
# Circle that shows that the port is a source for the connection
ui.Circle(
radius=7,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.RIGHT_CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_target:
# Circle that shows that the port is a target for the connection
ui.Circle(
radius=5,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.RIGHT_CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
def node_header_output(self, model, node_desc: GraphNodeDescription):
"""Called to create the right part of the header that will be used as output when the node is collapsed"""
node = node_desc.node
connected_source = node_desc.connected_source
connected_target = node_desc.connected_target
with ui.ZStack(width=8, skip_draw_when_clipped=True):
ui.Circle(
radius=6,
name=str(model[node].type),
style_type_name_override="Graph.Node.Output",
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_source:
# Circle that shows that the port is a source for the connection
ui.Circle(
radius=7,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.LEFT_CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
if connected_target:
# Circle that shows that the port is a target for the connection
ui.Circle(
radius=5,
size_policy=ui.CircleSizePolicy.FIXED,
style_type_name_override="Graph.Connection",
alignment=ui.Alignment.LEFT_CENTER,
visible_min=TEXT_VISIBLE_MIN,
)
def node_header(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the top of the node"""
node = node_desc.node
with ui.VStack(skip_draw_when_clipped=True):
self._common_node_header_top(model, node)
style_name = str(model[node].type)
# Draw the circle and the image on the top of it
with ui.HStack(height=0):
with ui.VStack():
ui.Label(
"Inputs",
alignment=ui.Alignment.CENTER,
style_type_name_override="Graph.Node.Port.Label",
visible_min=TEXT_VISIBLE_MIN,
)
ui.Spacer(height=15)
with ui.ZStack(width=50, height=50):
ui.Rectangle(
style_type_name_override="Graph.Node.Footer", name=style_name, visible_min=TEXT_VISIBLE_MIN
)
ui.ImageWithProvider(
style_type_name_override="Graph.Node.Footer.Image",
name=style_name,
visible_min=TEXT_VISIBLE_MIN,
)
# Scale up the icon when zooming out
with ui.Placer(
stable_size=True,
visible_min=LINE_VISIBLE_MIN,
visible_max=TEXT_VISIBLE_MIN,
offset_x=-15,
offset_y=-20,
):
with ui.ZStack(width=0, height=0):
ui.Rectangle(
style_type_name_override="Graph.Node.Footer", name=style_name, width=80, height=80
)
ui.ImageWithProvider(
style_type_name_override="Graph.Node.Footer.Image", name=style_name, width=80, height=80
)
with ui.VStack():
ui.Label(
"Outputs",
alignment=ui.Alignment.CENTER,
style_type_name_override="Graph.Node.Port.Label",
visible_min=TEXT_VISIBLE_MIN,
)
ui.Spacer(height=15)
ui.Spacer(height=18)
def node_footer(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the bottom of the node"""
# Don't draw footer
pass
| 6,666 | Python | 41.196202 | 120 | 0.539004 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_view.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__ = [
"GraphView",
]
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
import asyncio
import carb
import carb.settings
import functools
import traceback
import omni.kit.app
import omni.ui as ui
from .abstract_graph_node_delegate import AbstractGraphNodeDelegate
from .abstract_graph_node_delegate import GraphConnectionDescription
from .graph_layout import SugiyamaLayout
from .graph_model import GraphModel
from .graph_node import GraphNode
from .graph_node_index import GraphNodeDiff, GraphNodeIndex
CONNECTION_CURVE = 60
FLOATING_DELTA = 0.00001
def handle_exception(func):
"""
Decorator to print exception in async functions
TODO: The alternative way would be better, but we want to use traceback.format_exc for better error message.
result = await asyncio.gather(*[func(*args)], return_exceptions=True)
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
# We always cancel the task. It's not a problem.
pass
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
class GraphView:
"""
The visualisation layer of omni.kit.widget.graph. It behaves like a
regular widget and displays nodes and their connections.
"""
DEFAULT_DISTANCE_BETWEEN_NODES = 50.0
class _Proxy:
"""
A service proxy object to keep the given object in a central
location. It's used to keep the delegate and this object is passed to
the nodes, so when the delegate is changed, it's automatically
updated in all the nodes.
TODO: Add `set_delegate`. Otherwise it's useless.
"""
def __init__(self, reference=None):
self.set_object(reference)
def __getattr__(self, attr):
"""
Called when the default attribute access fails with an
AttributeError.
"""
return getattr(self._ref, attr)
def __setattr__(self, attr, value):
"""
Called when an attribute assignment is attempted. This is called
instead of the normal mechanism (i.e. store the value in the
instance dictionary).
"""
setattr(self._ref, attr, value)
def set_object(self, reference):
"""Replace the object this proxy holds with the new one"""
super().__setattr__("_ref", reference)
class _Event(set):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in self:
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({set.__repr__(self)})"
class _EventSubscription:
"""
Event subscription.
_Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.add(self._fn)
def __del__(self):
"""Called by GC."""
self._event.remove(self._fn)
def __init__(self, **kwargs):
"""
### Keyword Arguments:
`model : GraphModel`
Model to display the node graph
`delegate : AbstractGraphNodeDelegate`
Delegate to draw the node
`virtual_ports : bool`
True when the model should use reversed output for better look
of the graph.
`port_grouping : bool`
True when the widget should use sub-ports for port grouping.
All other kwargs are passed to CanvasFrame which is the root widget.
"""
# Selected nodes
self.__selection = []
self.__build_task = None
self._node_widgets = {}
self._connection_widgets = {}
self._node_placers = {}
self._delegate = self._Proxy()
# Regenerate the cache index when true
self._force_regenerate = True
self.__reference_style = kwargs.get("style", None)
self._model = None
self.set_model(kwargs.pop("model", None))
self.set_delegate(kwargs.pop("delegate", None))
self.__virtual_ports = kwargs.pop("virtual_ports", False)
self.__port_grouping = kwargs.pop("port_grouping", False)
self.__rectangle_selection = kwargs.pop("rectangle_selection", False)
self.__connections_on_top = kwargs.pop("connections_on_top", False)
self.__allow_same_side_connections = kwargs.pop("allow_same_side_connections", False)
self.__always_force_regenerate = kwargs.pop("always_force_regenerate", True)
# The variable raster_nodes is an experimental feature that can improve
# performance by rasterizing all the nodes when it is set to true.
# However, it is important to note that this feature may not always
# behave as expected and may cause issues with the editor. It is
# recommended to use this feature with caution and thoroughly test any
# changes before deploying them.
settings = carb.settings.get_settings()
self.__raster_nodes = kwargs.pop("raster_nodes", None)
if self.__raster_nodes is None:
self.__raster_nodes = settings.get("/exts/omni.kit.widget.graph/raster_nodes")
if self.__raster_nodes:
kwargs["compatibility"] = False
self._graph_node_index = GraphNodeIndex(None, self.__port_grouping)
if "style_type_name_override" not in kwargs:
kwargs["style_type_name_override"] = "Graph"
# The nodes for filtering upstrem.
self._filtering_nodes = None
# Nodes & Connections to force draw
self._force_draw_nodes = []
with ui.ZStack():
# Capturing selection
if self.__rectangle_selection:
ui.Spacer(
mouse_pressed_fn=self.__rectangle_selection_begin,
mouse_released_fn=self.__rectangle_selection_end,
mouse_moved_fn=self.__rectangle_selection_moved,
)
# The graph canvas
self.__root_frame = ui.CanvasFrame(**kwargs)
self.__root_stack = None
# Drawing selection
self.__selection_layer = ui.Frame(separate_window=True, visible=False)
with self.__selection_layer:
with ui.ZStack():
self.__selection_placer_start = ui.Placer(draggable=True)
self.__selection_placer_end = ui.Placer(draggable=True)
with self.__selection_placer_start:
rect_corner_start = ui.Spacer(width=1, height=1)
with self.__selection_placer_end:
rect_corner_end = ui.Spacer(width=1, height=1)
# The rectangle that is drawn when selection with the rectangle
ui.FreeRectangle(rect_corner_start, rect_corner_end, style_type_name_override="Graph.Selecion.Rect")
# Build the network
self.__on_item_changed(None)
# ZStack with connections to be able to add connections to the layout
self.__connections_stack = None
# The frame that follows mouse cursor when the user creates a new connection
self.__user_drag_connection_frame = None
# The frame with the temporary connection that is sticky to the port.
# We need it to demonstrate that the connection is valid.
self.__user_drag_connection_accepted_frame = None
# The source port when the user creates a new connection
self.__making_connection_source_node = None
self.__making_connection_source = None
self.__making_connection_source_widget = None
# The target port when the user creates a new connection
self.__making_connection_target_node = None
self.__making_connection_target = None
# Dict that has a port as a key and two frames with port widgets
self.__port_to_frames = {}
# Nodes that will be dragged once the mouse is moved
self.__nodes_to_drag = []
# Nodes that are currently dragged
self.__nodes_dragging = []
self.__can_connect = False
self.__position_changed = False
self.__on_post_delayed_build_layout = self._Event()
self.__on_pre_delayed_build_layout = self._Event()
# Selection caches
# Position when the user started selection
self.__rectangle_selection_start_position = None
# Positions of the nodes for selection caches
self.__positions_cache = None
# Selection when the user started rectangle
self.__selection_cache = []
# Flag for async method to deselect all. See
# `_clear_selection_next_frame_async` for details.
self.__need_clear_selection = False
def __getattr__(self, attr):
"""Pretend it's self.__root_frame"""
return getattr(self.__root_frame, attr)
def _post_delayed_build_layout(self):
"""Call the event object that has the list of functions"""
self.__on_post_delayed_build_layout()
def subscribe_post_delayed_build_layout(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_post_delayed_build_layout, fn)
def _pre_delayed_build_layout(self):
"""Call the event object that has the list of functions"""
self.__on_pre_delayed_build_layout()
def subscribe_pre_delayed_build_layout(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_pre_delayed_build_layout, fn)
def layout_all(self):
"""Reset positions of all the nodes in the model"""
# Turn force_regenerate on whenever calling layout_all, so it doesn't always
# need to be called right before the layout_all call.
self._force_regenerate = True
for node in self._model.nodes:
self._model[node].position = None
self.__on_item_changed(None)
def set_expansion(self, state: GraphModel.ExpansionState):
"""
Open, close or minimize all the nodes in the model.
"""
for node in self._model.nodes:
self._model[node].expansion_state = state
@property
def raster_nodes(self):
# Read only
return self.__raster_nodes
@property
def model(self):
return self._model
@model.setter
def model(self, model):
self._force_regenerate = True
self.set_model(model)
@property
def virtual_ports(self):
"""
Typically source connections go from the left side of the node to the
right side of the node. But sometimes it looks messy when circular
connections. When `virtual_ports` is true, and the connection is
circular, the view draws it from the right side to the left side.
Example:
A.out -------------> B.surface
A.color [REVERSED] <- B.color
"""
return self.__virtual_ports
@virtual_ports.setter
def virtual_ports(self, value):
self.__virtual_ports = not not value
self.__on_item_changed(None)
def set_model(self, model: GraphModel):
"""Replace the model of the widget. It will refresh all the content."""
self._filtering_nodes = None
if self._model:
self._model.destroy()
self._model = model
# Re-subscribe
if self._model:
self._model_subscription = self._model.subscribe_item_changed(self.__on_item_changed)
self._selection_subscription = self._model.subscribe_selection_changed(self.__on_selection_changed)
self._node_subscription = self._model.subscribe_node_changed(self.__rebuild_node)
else:
self._model_subscription = None
self._selection_subscription = None
self._node_subscription = None
self.__on_item_changed(None)
self.__on_selection_changed()
def set_delegate(self, delegate: AbstractGraphNodeDelegate):
"""Replace the delegate of the widget"""
self._force_regenerate = True
self._delegate.set_object(delegate)
self.__on_item_changed(None)
def filter_upstream(self, nodes: list):
"""Remove nodes that are not upstream of the given nodes"""
self._filtering_nodes = nodes
self.__on_item_changed(None)
def get_bbox_of_nodes(self, nodes: list):
"""Get the bounding box of nodes"""
if not nodes:
nodes = self._model.nodes
if not nodes:
return
min_pos_x = None
min_pos_x_node = None
min_pos_y = None
min_pos_y_node = None
max_pos_x = None
max_pos_x_node = None
max_pos_y = None
max_pos_y_node = None
for node in nodes:
if node not in self._node_widgets:
continue
pos = self._model[node].position
if pos is None:
continue
if min_pos_x is None:
min_pos_x = pos[0]
min_pos_x_node = node
min_pos_y = pos[1]
min_pos_y_node = node
max_pos_x = pos[0]
max_pos_x_node = node
max_pos_y = pos[1]
max_pos_y_node = node
continue
if pos[0] < min_pos_x:
min_pos_x = pos[0]
min_pos_x_node = node
previous_max_max_x = max_pos_x + self._node_widgets[max_pos_x_node].computed_width
if pos[0] + self._node_widgets[node].computed_width < previous_max_max_x:
pass
else:
max_pos_x = pos[0]
max_pos_x_node = node
if pos[1] < min_pos_y:
min_pos_y = pos[1]
min_pos_y_node = node
previous_max_max_y = max_pos_y + self._node_widgets[max_pos_y_node].computed_height
if pos[1] + self._node_widgets[node].computed_height < previous_max_max_y:
pass
else:
max_pos_y = pos[1]
max_pos_y_node = node
if max_pos_x_node in self._node_widgets:
computed_width = (max_pos_x + self._node_widgets[max_pos_x_node].computed_width) - min_pos_x
computed_height = (max_pos_y + self._node_widgets[max_pos_y_node].computed_height) - min_pos_y
else:
min_pos_x = 0
min_pos_y = 0
computed_height = 500
computed_width = 500
return computed_width, computed_height, min_pos_x, min_pos_y
def focus_on_nodes(self, nodes: Optional[List[Any]] = None):
"""Focus the view on nodes"""
if not nodes:
nodes = self._model.nodes
if not nodes:
return
computed_width, computed_height, min_pos_x, min_pos_y = self.get_bbox_of_nodes(nodes)
# TODO: Looks like it's a bug of ui.CanvasFrame.computed_width. But it works for now.
if self.__raster_nodes:
canvas_computed_width = self.__root_frame.computed_width
canvas_computed_height = self.__root_frame.computed_height
else:
canvas_computed_width = self.__root_frame.computed_width * self.zoom
canvas_computed_height = self.__root_frame.computed_height * self.zoom
zoom = min([canvas_computed_width / computed_width, canvas_computed_height / computed_height])
# We need to clamp the zoom with zoom_min and zoom_max here since we need to update the zoom of graphView and
# use the clamped zoom to compute self.pan_x and self.pan_y
# this FLOATING_DELTA is needed to avoid floating issue
zoom = max(min(zoom, self.zoom_max - FLOATING_DELTA), self.zoom_min + FLOATING_DELTA)
self.zoom = zoom
self.pan_x = -min_pos_x * zoom + canvas_computed_width / 2 - computed_width * zoom / 2
self.pan_y = -min_pos_y * zoom + canvas_computed_height / 2 - computed_height * zoom / 2
async def restore_smooth_async():
"""Set smooth_zoom to True"""
await omni.kit.app.get_app().next_update_async()
self.__root_frame.smooth_zoom = True
if self.smooth_zoom:
# Temporarly disable smooth_zoom
self.__root_frame.smooth_zoom = False
asyncio.ensure_future(restore_smooth_async())
@property
def selection(self):
"""Return selected nodes"""
return self.__selection
@selection.setter
def selection(self, value):
"""Set selection"""
if self._model:
self._model.selection = value
def __rebuild_node(self, item, full=False):
"""Rebuild the delegate of the node, this could be used to just update the look of one node"""
if item:
if full:
self._force_draw_nodes.append(item)
# Still need to call __delayed_build_layout where this is called.
return
node = self._node_widgets[item]
if node:
# Doesn't rebuild ports or connections
node.rebuild_layout()
def __on_item_changed(self, item):
"""Called by the model when something is changed"""
if item is not None:
# Only one item is changed. Not necessary to rebuild the whole network.
placer = self._node_placers.get(item, None)
if placer:
position = self._model[item].position
if position:
placer.offset_x = position[0]
placer.offset_y = position[1]
placer.invalidate_raster()
# TODO: Rebuild the node
return
# The whole graph is changed. Rebuild
if self.__build_task:
self.__build_task.cancel()
# Build the layout in the next frame because it's possible that
# multiple items is changed and in this case we still need to execute
# __build_layouts once.
self.__build_task = asyncio.ensure_future(self.__delayed_build_layout())
def __on_selection_changed(self):
"""Called by the model when selection is changed"""
if not self._model:
return
# Deselect existing selection
for node in self.__selection:
widget = self._node_widgets.get(node, None)
if not widget:
continue
widget.selected = False
# Keep only nodes if we have a widget for them. We need it to skip
# nodes that are selected in model but they are filtered out here
self.__selection = []
for model_selection_node in self._model.selection or []:
for widget_node in self._node_widgets:
if model_selection_node == widget_node:
self.__selection.append(widget_node)
# Select new selection
for node in self.__selection:
widget = self._node_widgets.get(node, None)
if not widget:
continue
widget.selected = True
def __cache_positions(self):
"""Creates cache for all the positions of all the nodes"""
if self.__positions_cache is not None:
return
class PositionCache:
def __init__(self, node: Any, pos: List[float], size: List[float]):
self.node = node
self.__x0 = pos[0]
self.__y0 = pos[1]
self.__x1 = pos[0] + size[0]
self.__y1 = pos[1] + size[1]
def __repr__(self):
return f"<PositionCache {self.node} {self.__x0} {self.__y0} {self.__x1} {self.__y1}"
def is_in_rect(self, x_min: float, y_min: float, x_max: float, y_max: float):
return not (x_max < self.__x0 or x_min > self.__x1 or y_max < self.__y0 or y_min > self.__y1)
self.__positions_cache = []
for node in self._model.nodes or []:
# NOTE: If we ever have selection objects that aren't positioned in the top left corner of the
# node (like the header), we will need to get the select_widget's position instead, here.
pos = self._model[node].position
if pos:
widget = self._node_widgets.get(node, None)
if not widget:
continue
select_widget = self._model.special_select_widget(node, widget) or widget
size = [select_widget.computed_width, select_widget.computed_height]
self.__positions_cache.append(PositionCache(node, pos, size))
self.__selection_cache = self.model.selection or []
async def _clear_selection_next_frame_async(self, model):
"""
Called by background layer to clear selection. The idea is that if no
node cancels it, then the yser clicked in the background and we need
to deselect all.
"""
await omni.kit.app.get_app().next_update_async()
if self.__need_clear_selection:
model.selection = []
def _on_rectangle_select(self, model, start, end, modifier=0):
"""Called when the user is performing the rectangle selection"""
# this function could be triggered when we multi-selected nodes and move one of them too quickly.
# in this case, we don't want to update the selection.
if start == end:
return
# Don't clear selection frame after
self.__need_clear_selection = False
self.__cache_positions()
x_min = min(start[0], end[0])
x_max = max(start[0], end[0])
y_min = min(start[1], end[1])
y_max = max(start[1], end[1])
selection = []
for position_cache in self.__positions_cache:
if position_cache.is_in_rect(x_min, y_min, x_max, y_max):
selection.append(position_cache.node)
if modifier & carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT:
# Add to the current selection
selection = self.__selection_cache + [s for s in selection if s not in self.__selection_cache]
elif modifier & carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL:
# Subtract from the current selection
selection = [s for s in self.__selection_cache if s not in selection]
model.selection = selection
def _on_node_selected(self, model, node, modifier=0, pressed=True):
"""Called when the user is picking to select nodes"""
# Stop rectangle selection
self.__rectangle_selection_start_position = None
# Don't clear selection frame after
self.__need_clear_selection = False
selection = model.selection
if selection is None:
return
# Copy
selection = selection[:]
if modifier & carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT:
if not pressed:
return
# Add
if node not in selection:
selection.append(node)
elif modifier & carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL:
if not pressed:
return
# Add / Remove
if node in selection:
selection.remove(node)
else:
selection.append(node)
else:
if pressed and node in selection:
return
# Set
selection = [node]
model.selection = selection
@handle_exception
async def __delayed_build_layout(self):
"""
Rebuild all the nodes and connections in the next update cycle. It's
delayed because it's possible that it's called multiple times a
frame. And we need to create all the widgets only one.
The challenge here is the ability of USD making input-to-input and output-to-output connections. In USD it's
perfectly fine to have the following network:
A.out --> B.out
A.in <-- B.in
So it doesn't matter if the port is input or output. To draw such connections properly and to know which side
of the node it should connect, we need to find out the direction of the flow in this node network. This is the
overview of the algorithm to trace the nodes and compute the direction of the flow.
STEP 1. Create the cache of the model and indices to be able to access the cache fast.
STEP 2. Scan all the nodes and find roots. A root is a node that doesn't have an output connected to another
node.
STEP 3. Trace connections of roots and assign them level. Level is the distance of the node from the root.
The root has level 0. The nodes connected to root has level one. The next connected nodes have level 2 etc.
We assume that level is the flow direction. The flow goes from nodes to root.
STEP 4. It's easy to check if the connection goes to the direction opposite to flow. Such connections have
virtual ports.
"""
self._pre_delayed_build_layout()
await omni.kit.app.get_app().next_update_async()
# STEP 1
# Small explanation on input/output, source/target. Input and output is
# just a USD tag. We inherit this terminology to be USD compliant.
# Input/output is not the direction of the data flow. To express the
# data flow direction we use source/target. In USD it's possible to
# have input-to-input and output-to-output connections.
graph_node_index = GraphNodeIndex(self._model, self.__port_grouping)
if self.__always_force_regenerate or self._force_regenerate:
self._force_regenerate = False
regenerate_all = True
else:
# Diff
diff = self._graph_node_index.get_diff(graph_node_index)
regenerate_all = not diff.valid
if regenerate_all:
self._graph_node_index = graph_node_index
# Clean up the previous nodes
for _, node_widget in self._node_widgets.items():
node_widget.destroy()
for _, connection_widget in self._connection_widgets.items():
connection_widget.destroy()
self._node_widgets = {}
self._connection_widgets = {}
self.__port_to_frames = {}
else:
if self._force_draw_nodes:
self.__add_force_redraws_to_diff(diff, graph_node_index)
nodes_add, nodes_del, connections_add, connections_del = self._graph_node_index.mutate(diff)
# Utility to access the index
def get_node_level_from_port(port, port_to_id, all_cached_nodes):
if port is None:
return 0
node_id = port_to_id.get(port, None)
if node_id is None:
return 0
return all_cached_nodes[node_id].level
# List of all the nodes from the model. Members are CacheNode objects
all_cached_nodes = self._graph_node_index.cached_nodes
all_cached_connections = self._graph_node_index.cached_connections
# Dictionary that has a port from the model as a key and the index of the parent node in all_cached_nodes.
port_to_id = self._graph_node_index.port_to_id
# Dictionary that has a port from the model as a key and a flag if this port is output. We need it to detect
# the flow direction.
ports_used_as_output = self._graph_node_index.ports_used_as_output
# All the connections. Usded to determine if we need to draw output circle.
source_to_target = self._graph_node_index.source_to_target
# Dict[child port: parent port]
port_child_to_parent: Dict[Any, Any] = self._graph_node_index.port_child_to_parent
if not self._model:
return
# STEP 2
# True if the node in all_cached_nodes is a root node. The node A is a root node if other nodes are not
# connected to outputs of A.
is_root_node = [True] * len(all_cached_nodes)
for cache_node in all_cached_nodes:
if not cache_node:
continue
if not regenerate_all and cache_node.node not in nodes_add:
continue
for source in cache_node.inputs + cache_node.outputs:
if source not in ports_used_as_output:
continue
# The source node is not root because it has output connected to this node
source_node_id = port_to_id.get(source, None)
if source_node_id is None:
continue
is_root_node[source_node_id] = False
if self._filtering_nodes:
root_nodes = [cached_node for cached_node in all_cached_nodes if cached_node.node in self._filtering_nodes]
else:
root_nodes = [cached_node for cached_node, is_root in zip(all_cached_nodes, is_root_node) if is_root]
if not root_nodes and all_cached_nodes:
# We have a circular connected network. In this way it doesn't matter which node to pick, but we assume that
# the first node of the model will be the root node.
root_nodes = [all_cached_nodes[0]]
# STEP 3
# Create the list of edges. We need to put them into layout.
edges = []
edges_sorted = []
for i, cache_node in enumerate(all_cached_nodes):
if not cache_node:
continue
if not regenerate_all and cache_node.node not in nodes_add:
continue
for source in cache_node.inputs + cache_node.outputs:
source_node_id = port_to_id.get(source, None)
if source_node_id is None:
# try to resolve id of parent instead
parent_source = port_child_to_parent.get(source, None)
if parent_source is not None:
source_node_id = port_to_id.get(parent_source, None)
if source_node_id is None:
continue
v1 = source_node_id
v2 = i
edge_sorted = (v1, v2) if v1 < v2 else (v2, v1)
if v1 != v2 and edge_sorted not in edges_sorted:
edges.append((v2, v1))
edges_sorted.append(edge_sorted)
if regenerate_all:
self.layout = SugiyamaLayout(edges=edges, vertical_distance=20.0, horizontal_distance=200.0)
for i, cache_node in enumerate(all_cached_nodes):
if not cache_node:
continue
if not regenerate_all and cache_node.node not in nodes_add:
continue
level = self.layout.get_layer(i)
# If level is None, it means the node is not connected to anything. We assume its level is 0.
cache_node.level = level or 0
# STEP 4. Generate widgets.
node_and_level = []
if self.__root_stack is None or regenerate_all:
with self.__root_frame:
self.__root_stack = ui.ZStack()
if regenerate_all:
self.__connections_stack = None
if not regenerate_all:
# Delete nodes
for node in nodes_del:
self._node_widgets[node].visible = False
self._node_widgets[node].destroy()
# Delete connections
for connection in connections_del:
connection_widget = self._connection_widgets[connection]
connection_widget.visible = False
connection_widget.clear()
connection_widget.destroy()
# If 1 to keep indentation. Otherwise indentation is changed, it's bad
# for code review.
if 1:
with self.__root_stack:
# Save the connections. It's the list of tuples (target_port, source_port)
for node_id, cached_node in sorted(
enumerate(n for n in all_cached_nodes if n), key=lambda a: a[1].stacking_order
):
if not regenerate_all and cached_node.node not in nodes_add:
continue
stacking_order = cached_node.stacking_order
# Create ZStack for connections between -1 and 0 stacking
# order. It allows to put the connections under nodes and
# over the backdrops.
if not self.__connections_on_top and not self.__connections_stack and stacking_order >= 0:
with ui.Frame(separate_window=True):
self.__connections_stack = ui.ZStack()
expansion_state = self._model[cached_node.node].expansion_state
# Filtered ports
ports = []
# Two bools per port:
# (True if it's target, True if it's source)
# So the connection can have four states: input/output and
# source/target. They can be mixed every possible way.
port_input = []
# Two bools per port
# (True if it's target, True if it's source)
port_output = []
port_levels: List[int] = []
port_position: List[int] = []
parent_child_count: List[int] = []
node_input = (False, False)
node_output = (False, False)
# Save connections and check if the node has virtual input/output
for cached_port in cached_node.cached_ports:
if not cached_port.visibile:
continue
target_port = cached_port.port
# Or it happens when the node is minimized
# TODO: compute it when computing port_visibility
if (
expansion_state == GraphModel.ExpansionState.MINIMIZED
or expansion_state == GraphModel.ExpansionState.CLOSED
):
if not cached_port.inputs and not cached_port.outputs:
if target_port not in source_to_target:
# Filter out ports with no connections
continue
# True if the port has input (left side) connection
# from this port to another
input_is_source_connection = False
# True if the port has input (left side) connection
# from another port to this port
input_is_target_connection = False
# True if the port has output (right side) connection
# from this port to another
output_is_source_connection = False
# True if the port has output (right side) connection
# from another port to this port
output_is_target_connection = False
if cached_port.inputs:
for source_port in cached_port.inputs:
if source_port not in port_to_id:
carb.log_warn(
f"[Graph UI] The port {target_port} can't be connected to the port "
f"{source_port} because it doesn't exist in the model"
)
continue
if (
self.virtual_ports
and get_node_level_from_port(source_port, port_to_id, all_cached_nodes)
< cached_node.level
):
# The input port is connected from the downflow node
#
# Example:
# A.out -------------------------> B.surface
# A.color [checking this option] <- B.color
output_is_target_connection = True
else:
# Example:
# A.out -> [checking this option] B.in
input_is_target_connection = True
if cached_port.outputs:
for source_port in cached_port.outputs:
if source_port not in port_to_id:
carb.log_warn(
f"[Graph UI] The port {target_port} can't be connected to the port "
f"{source_port} because it doesn't exist in the model"
)
continue
if (
self.virtual_ports
and get_node_level_from_port(source_port, port_to_id, all_cached_nodes)
< cached_node.level
):
output_is_target_connection = True
else:
input_is_target_connection = True
# The output port has input connection. A.out -> [checking this option] B.out
if target_port in source_to_target:
for t in source_to_target[target_port]:
compare_level = get_node_level_from_port(t, port_to_id, all_cached_nodes)
if (
self.virtual_ports
and compare_level is not None
and cached_node.level < compare_level
):
# Example:
# A.out -------------------------> B.surface
# A.color <- [checking this option] B.color
input_is_source_connection = True
else:
# A.out [checking this option] -> B.in
output_is_source_connection = True
node_input = (
node_input[0] or input_is_source_connection,
node_input[1] or input_is_target_connection,
)
node_output = (
node_output[0] or output_is_source_connection,
node_output[1] or output_is_target_connection,
)
if expansion_state == GraphModel.ExpansionState.CLOSED:
continue
# Ports
ports.append(target_port)
port_input.append((input_is_source_connection, input_is_target_connection))
port_output.append((output_is_source_connection, output_is_target_connection))
port_levels.append(cached_port.level)
port_position.append(cached_port.relative_position)
parent_child_count.append(cached_port.parent_child_count)
# Rasterize the nodes. This is an experimental feature that
# can improve performance.
raster_policy = ui.RasterPolicy.AUTO if self.__raster_nodes else ui.RasterPolicy.NEVER
# The side effect of having level, is the possibility to put the node to the correct position.
placer = ui.Placer(
draggable=True, frames_to_start_drag=2, name="node_graph", raster_policy=raster_policy
)
# Set position if possible
position = self._model[cached_node.node].position
if position:
placer.offset_x = position[0]
placer.offset_y = position[1]
def save_position(placer, model, node):
if self.__nodes_to_drag:
for drag_node in self.__nodes_to_drag:
model.position_begin_edit(drag_node)
self.__nodes_dragging[:] = self.__nodes_to_drag[:]
self.__nodes_to_drag[:] = []
# Without this, unselected backdrops can still be dragged by their placer
if not self.__nodes_dragging:
if model[node].position:
placer.offset_x.value, placer.offset_y.value = model[node].position
return
node_position = (placer.offset_x.value, placer.offset_y.value)
model[node].position = node_position
self.__position_changed = True
placer.set_offset_x_changed_fn(
lambda _, p=placer, m=self._model, n=cached_node.node: save_position(p, m, n)
)
placer.set_offset_y_changed_fn(
lambda _, p=placer, m=self._model, n=cached_node.node: save_position(p, m, n)
)
with placer:
# The node widget
node_widget = GraphNode(
self._model,
cached_node.node,
node_input,
node_output,
list(zip(ports, port_input, port_output, port_levels, port_position, parent_child_count)),
self._delegate,
)
def position_begin_edit(model, node, modifier):
self.__nodes_to_drag[:] = [node]
self.__nodes_dragging[:] = []
self.__position_changed = False
def position_end_edit(model, node, modifier):
self.__nodes_to_drag[:] = []
for drag_node in self.__nodes_dragging:
model.position_end_edit(drag_node)
self.__nodes_dragging[:] = []
return self.__position_changed
select_widget = self._model.special_select_widget(cached_node.node, node_widget) or node_widget
# Select node
select_widget.set_mouse_pressed_fn(
lambda x, y, b, modifier, model=self._model, node=cached_node.node: b == 0
and (
position_begin_edit(model, node, modifier)
or self._on_node_selected(model, node, modifier, True)
)
)
select_widget.set_mouse_released_fn(
lambda x, y, b, modifier, model=self._model, node=cached_node.node: b == 0
and (
position_end_edit(model, node, modifier)
or self._on_node_selected(model, node, modifier, False)
)
)
# Save the node so it's not removed
self._node_widgets[cached_node.node] = node_widget
self._node_placers[cached_node.node] = placer
node_and_level.append((cached_node.node, node_widget, placer, node_id))
# Save the ports for fast access
if expansion_state == GraphModel.ExpansionState.CLOSED:
for cached_port in cached_node.cached_ports:
self.__port_to_frames[cached_port.port] = (
node_widget.header_input_frame,
node_widget.header_output_frame,
)
else:
self.__port_to_frames.update(node_widget.ports)
for port, input_output in node_widget.ports.items():
input_port_widget, output_port_widget = input_output
if input_port_widget:
# Callback when mouse enters/leaves the port widget
input_port_widget.set_mouse_hovered_fn(
lambda h, n=cached_node.node, p=port, w=input_port_widget: self.__on_port_hovered(
n, p, w, h
)
)
input_port_widget.set_mouse_pressed_fn(
lambda x, y, b, m, n=cached_node.node, p=port: self._on_port_context_menu(n, p)
if b == 1
else None
)
if self.__allow_same_side_connections and output_port_widget:
# Callback when mouse enters/leaves the port widget
output_port_widget.set_mouse_hovered_fn(
lambda h, n=cached_node.node, p=port, w=output_port_widget: self.__on_port_hovered(
n, p, w, h
)
)
for port, input_output in node_widget.user_drag.items():
_, drag_widget = input_output
port_widget = self.__port_to_frames.get(port, (None, None))[1]
# Callback when user starts doing a new connection
drag_widget.set_mouse_pressed_fn(
lambda *_, f=port_widget, t=drag_widget, n=cached_node.node, p=port: self.__on_start_connection(
n, p, f, t
)
)
# Callback when user finishes doing a new connection
drag_widget.set_mouse_released_fn(lambda *_: self._on_new_connection())
# The connections ZStack is not created if all the nodes are under connections
if not self.__connections_stack:
with ui.Frame(separate_window=True):
self.__connections_stack = ui.ZStack()
# Buffer to keep the lines already built. We use it for filtering.
built_lines = set()
# Build all the connections
for connection in all_cached_connections:
if not connection:
continue
if not regenerate_all and connection not in connections_add:
continue
target = connection.target_port
source = connection.source_port
target_node_id = port_to_id.get(target, None)
target_cached_node = all_cached_nodes[target_node_id]
target_level = target_cached_node.level
source_node_id = port_to_id.get(source, None)
source_cached_node = all_cached_nodes[source_node_id]
source_level = source_cached_node.level
# Check if the direction of this connection is the same as flow
if self.virtual_ports:
is_reversed_connection = source_level < target_level
else:
is_reversed_connection = False
target_node = target_cached_node.node
source_node = source_cached_node.node
# 0 means the frame from input (left side). 1 is output (right side).
target_frames = self.__port_to_frames.get(target, None)
source_frames = self.__port_to_frames.get(source, None)
if self.__allow_same_side_connections and target_node == source_node:
is_reversed_target = True
is_reversed_source = False
f1 = target_frames[1]
f2 = source_frames[1]
else:
is_reversed_target = is_reversed_connection
is_reversed_source = is_reversed_connection
f1 = target_frames[1 if is_reversed_connection else 0]
f2 = source_frames[0 if is_reversed_connection else 1]
# Filter out lines already built.
line1 = (f1, f2)
line2 = (f2, f1)
if line1 in built_lines or line2 in built_lines:
continue
built_lines.add(line1)
# Objects passed to the delegate
source_connection_description = GraphConnectionDescription(
source_node, source, f2, source_level, is_reversed_source
)
target_connection_description = GraphConnectionDescription(
target_node, target, f1, target_level, is_reversed_target
)
with self.__connections_stack:
connection_frame = ui.Frame()
self._connection_widgets[connection] = connection_frame
with connection_frame:
self._delegate.connection(
self._model, source_connection_description, target_connection_description
)
with self.__connections_stack:
self.__user_drag_connection_frame = ui.Frame()
self.__user_drag_connection_accepted_frame = ui.Frame()
self.__making_connection_source_node = None
self.__making_connection_source = None
self.__making_connection_source_widget = None
# Init selection state
self.__on_selection_changed()
# Arrange node position in the next frame because now the node is not
# created and it's not possible to get its size.
if not node_and_level:
self._post_delayed_build_layout()
return
await self.__arrange_nodes(node_and_level)
self._post_delayed_build_layout()
def __add_force_redraws_to_diff(self, diff: GraphNodeDiff, graph_node_index: GraphNodeIndex):
"""
Add the force_redraw_nodes, if any, by adding them to both the nodes_to_add and nodes_to_del sides.
Also do the same with any connections to the node(s). By deleting and then adding, it forces a redraw.
"""
cached_add_connections = set()
cached_del_connections = set()
for force_node in self._force_draw_nodes:
# Add node to nodes_to_add
if force_node in graph_node_index.node_to_id:
force_add_cache_node = graph_node_index.cached_nodes[
graph_node_index.node_to_id[force_node]
]
if force_add_cache_node not in diff.nodes_to_add:
diff.nodes_to_add.append(force_add_cache_node)
# Add any inputs or outputs
for c_port in force_add_cache_node.cached_ports:
# Check for outputs
source = c_port.port
targets = graph_node_index.source_to_target.get(c_port.port, [])
for t in targets:
if (source, t) in graph_node_index.connection_to_id:
cached_add_connection = graph_node_index.cached_connections[
graph_node_index.connection_to_id[(source, t)]
]
cached_add_connections.add(cached_add_connection)
if (source, t) in self._graph_node_index.connection_to_id:
cached_del_connection = self._graph_node_index.cached_connections[
self._graph_node_index.connection_to_id[(source, t)]
]
cached_del_connections.add(cached_del_connection)
# Check for inputs
if not targets:
target = source
if c_port.inputs:
for inp in c_port.inputs:
source = inp
if (source, target) in graph_node_index.connection_to_id:
cached_add_connection = graph_node_index.cached_connections[
graph_node_index.connection_to_id[(source, target)]
]
cached_add_connections.add(cached_add_connection)
if (source, target) in self._graph_node_index.connection_to_id:
cached_del_connection = self._graph_node_index.cached_connections[
self._graph_node_index.connection_to_id[(source, target)]
]
cached_del_connections.add(cached_del_connection)
# Add node to nodes_to_del
if force_node in self._graph_node_index.node_to_id:
force_del_cache_node = self._graph_node_index.cached_nodes[
self._graph_node_index.node_to_id[force_node]
]
if force_del_cache_node not in diff.nodes_to_del:
diff.nodes_to_del.append(force_del_cache_node)
# Add all connections to the diff
for c_connection in cached_add_connections:
if c_connection not in diff.connections_to_add:
diff.connections_to_add.append(c_connection)
for c_connection in cached_del_connections:
if c_connection not in diff.connections_to_del:
diff.connections_to_del.append(c_connection)
self._force_draw_nodes = []
async def __arrange_nodes(self, node_and_level):
"""
Set the the position of the nodes. If the node doesn't have a
predefined position (TODO), the position is assigned automatically.
It's async because it waits until the node is created to get its size.
"""
# Wait untill the node appears on the screen.
while node_and_level[0][1].computed_width == 0.0:
await omni.kit.app.get_app().next_update_async()
# Set size
for _, node_widget, _, layout_node_id in node_and_level:
self.layout.set_size(layout_node_id, node_widget.computed_width, node_widget.computed_height)
# Recompute positions
self.layout.update_positions()
# Set positions in graph view
for node, node_widget, placer, layout_node_id in node_and_level:
model_position = self._model[node].position
self._model[node].size = (node_widget.computed_width, node_widget.computed_height)
if not model_position:
# The model doesn't have the position. Set it.
model_position = self.layout.get_position(layout_node_id)
if model_position:
self._model[node].position = model_position
placer.offset_x = model_position[0]
placer.offset_y = model_position[1]
def __on_start_connection(self, node, port, from_widget, to_widget):
"""Called when the user starts creating connection"""
# Keep the source port
self.__making_connection_source_node = node
self.__making_connection_source = port
self.__making_connection_source_widget = from_widget
self.__user_drag_connection_frame.visible = True
self.__user_drag_connection_accepted_frame.visible = False
with self.__user_drag_connection_frame:
if from_widget and to_widget:
# Temporary connection line follows the mouse
# Objects passed to the delegate
source_connection_description = GraphConnectionDescription(node, port, from_widget, 0, False)
target_connection_description = GraphConnectionDescription(None, None, to_widget, 0, False)
self._delegate.connection(self._model, source_connection_description, target_connection_description)
else:
# Dummy widget will destroy the temporary connection line if it exists
ui.Spacer()
def __on_port_hovered(self, node, port, widget, hovered):
"""Called when the mouse pointer enters the area of the port"""
if not self.__making_connection_source:
# We are not in connection mode, return
if self.__making_connection_target:
self.__making_connection_target = None
if self.__making_connection_target_node:
self.__making_connection_target_node = None
return
# We are here because the user is trying to connect ports
if hovered:
# The user entered the port widget
self.__making_connection_target_node = node
self.__making_connection_target = port
self.__can_connect = self._model.can_connect(self.__making_connection_source, port)
if self.__allow_same_side_connections and node == self.__making_connection_source_node:
is_reversed_source = False
is_reversed_target = True
else:
is_reversed_source = False
is_reversed_target = False
# Replace connection with the sticky one
if self.__can_connect:
# Show sticky connection and hide the one that follows the mouse
self.__user_drag_connection_frame.visible = False
self.__user_drag_connection_accepted_frame.visible = True
with self.__user_drag_connection_accepted_frame:
# Temporary connection line sticked to the port
# Objects passed to the delegate
source_connection_description = GraphConnectionDescription(
self.__making_connection_source_node,
self.__making_connection_source,
self.__making_connection_source_widget,
0,
is_reversed_source,
)
target_connection_description = GraphConnectionDescription(
self.__making_connection_target_node,
self.__making_connection_target,
widget,
0,
is_reversed_target,
)
self._delegate.connection(self._model, source_connection_description, target_connection_description)
elif self.__making_connection_target == port:
# Check that mouse left the currently hovered port because
# sometimes __on_port_hovered gets called like this:
# __on_port_hovered("A", 1)
# __on_port_hovered("B", 1)
# __on_port_hovered("A", 0)
self.__making_connection_target_node = None
self.__making_connection_target = None
# Hide sticky connection and show the one that follows the mouse
self.__user_drag_connection_frame.visible = True
self.__user_drag_connection_accepted_frame.visible = False
def __disconnect_inputs(self, port):
"""Remove connections from port"""
self._model[port].inputs = []
def __canvas_space(self, x: float, y: float):
"""Convert mouse to canvas space"""
if self.__raster_nodes:
return self.__root_frame.screen_to_canvas_x(x), self.__root_frame.screen_to_canvas_y(y)
offset_x = x - self.__root_frame.screen_position_x * self.zoom
offset_y = y - self.__root_frame.screen_position_y * self.zoom
offset_x = (offset_x - self.pan_x) / self.zoom
offset_y = (offset_y - self.pan_y) / self.zoom
return offset_x, offset_y
def __rectangle_selection_begin(self, x: float, y: float, button: int, modifier: int):
"""Mouse pressed callback"""
if not self._model or button != 0:
return
if (
not modifier & carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT
and not modifier & carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL
):
self.__need_clear_selection = True
asyncio.ensure_future(self._clear_selection_next_frame_async(self._model))
# if there is modifier, but the modifier is not shift or control, we skip drawing the selection
# so that users are free use other modifier for other actions
if modifier:
return
self.__rectangle_selection_start_position = self.__canvas_space(x, y)
# Mouse position in widget space
x_w = x - self.__selection_layer.screen_position_x
y_w = y - self.__selection_layer.screen_position_y
self.__selection_placer_start.offset_x = x_w
self.__selection_placer_start.offset_y = y_w
self.__selection_placer_end.offset_x = x_w
self.__selection_placer_end.offset_y = y_w
def __rectangle_selection_end(self, x: float, y: float, button: int, modifier: int):
"""Mouse released callback"""
if self.__rectangle_selection_start_position is None:
return
# Clean up selection caches
self.__selection_placer_start.offset_x = 0
self.__selection_placer_start.offset_y = 0
self.__selection_placer_end.offset_x = 0
self.__selection_placer_end.offset_y = 0
self.__selection_layer.visible = False
self.__rectangle_selection_start_position = None
self.__positions_cache = None
self.__selection_cache = []
def __rectangle_selection_moved(self, x: float, y: float, modifier: int, pressed: bool):
"""Mouse moved callback"""
if self.__rectangle_selection_start_position is None:
# No rectangle selection
return
self._on_rectangle_select(
self._model, self.__rectangle_selection_start_position, self.__canvas_space(x, y), modifier
)
# Mouse position in widget space
x_w = x - self.__selection_layer.screen_position_x
y_w = y - self.__selection_layer.screen_position_y
self.__selection_layer.visible = True
self.__selection_placer_end.offset_x = x_w
self.__selection_placer_end.offset_y = y_w
def _on_new_connection(self):
"""Called when the user finished creating connection. This method sends the connection to the model."""
if (
not self.__making_connection_source
or not self.__making_connection_target
or not self.__making_connection_target_node
):
self.__making_connection_source = None
self.__making_connection_target_node = None
self.__making_connection_target = None
if (
self.__making_connection_source_node
or self.__making_connection_source
or self.__making_connection_source_widget
):
# We are here because the user cancelled the connection (most
# likely RMB is pressed). We need to clear the current connection.
self.__on_start_connection(None, None, None, None)
return
if self.__can_connect:
# Set the connection in the model.
self._model[self.__making_connection_target].inputs = [self.__making_connection_source]
self.__on_start_connection(None, None, None, None)
def _on_port_context_menu(self, node, port):
"""Open context menu for specific port"""
self.__port_context_menu = ui.Menu("Port Context Menu", visible=False)
with self.__port_context_menu:
if self._model[port].inputs:
self.__port_context_menu.visible = True
ui.MenuItem("Disconnect", triggered_fn=lambda p=port: self.__disconnect_inputs(p))
self.__port_context_menu.show()
def _on_set_zoom_key_shortcut(self, mouse_button, key):
"""allow user to set the key shortcut for the graphView zoom"""
self.__root_frame.set_zoom_key_shortcut(mouse_button, key)
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
self.set_model(None)
self.__root_frame = None
self._delegate = None
# Destroy each node
for _, node_widget in self._node_widgets.items():
node_widget.destroy()
for _, connection_widget in self._connection_widgets.items():
connection_widget.destroy()
self._node_widgets = {}
self._connection_widgets = {}
self._node_placers = {}
self.__port_context_menu = None
self.__connections_stack = None
self.__port_to_frames = {}
self.__user_drag_connection_frame = None
self.__user_drag_connection_accepted_frame = None
self.__making_connection_source_node = None
self.__making_connection_source = None
self.__making_connection_source_widget = None
# Destroy the graph index
self._graph_node_index = GraphNodeIndex(None, self.__port_grouping)
@property
def zoom(self):
"""The zoom level of the scene"""
return self.__root_frame.zoom
@zoom.setter
def zoom(self, value):
"""The zoom level of the scene"""
self.__root_frame.zoom = value
@property
def zoom_min(self):
"""The minminum zoom level of the scene"""
return self.__root_frame.zoom_min
@zoom_min.setter
def zoom_min(self, value):
"""The minminum zoom level of the scene"""
self.__root_frame.zoom_min = value
@property
def zoom_max(self):
"""The maximum zoom level of the scene"""
return self.__root_frame.zoom_max
@zoom_max.setter
def zoom_max(self, value):
"""The maximum zoom level of the scene"""
self.__root_frame.zoom_max = value
@property
def pan_x(self):
"""The horizontal offset of the scene"""
return self.__root_frame.pan_x
@pan_x.setter
def pan_x(self, value):
"""The horizontal offset of the scene"""
self.__root_frame.pan_x = value
@property
def pan_y(self):
"""The vertical offset of the scene"""
return self.__root_frame.pan_y
@pan_y.setter
def pan_y(self, value):
"""The vertical offset of the scene"""
self.__root_frame.pan_y = value
| 69,581 | Python | 41.925355 | 128 | 0.540679 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_node.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__ = ["GraphNode"]
from .abstract_graph_node_delegate import GraphNodeDescription
from .abstract_graph_node_delegate import GraphNodeLayout
from .abstract_graph_node_delegate import GraphPortDescription
from .graph_model import GraphModel
import omni.ui as ui
class GraphNode:
"""
Represents the Widget for the single node. Uses the model and the
delegate to fill up its layout.
"""
def __init__(self, model: GraphModel, item, has_input_connection, has_output_connection, ports: list, delegate):
"""
Save the model, item and delegate to reuse when drawing the widget
"""
# Port to the tuple of two widgets that represent the port
self._port_to_frames = {}
# Port to the tuple of two widgets that are used to draw line to show the connection is in process
self._port_to_user_drag = {}
self._port_to_user_drag_placer = {}
# center port widget (i.e. name labels and string edit fields)
self._port_center_widgets = {}
self._header_input_widget = None
self._header_output_widget = None
self._has_input_connection = has_input_connection
self._has_output_connection = has_output_connection
self._header_widget = None
self._footer_widget = None
self._node_bg_widget = None
self.__root_frame = ui.Frame(width=0, height=0, skip_draw_when_clipped=True)
# TODO: WeakRef for the model?
self.__model = model
self.__delegate = delegate
self.__item = item
self.__ports = ports
# Build everything
self.__build_layout()
def __getattr__(self, attr):
"""Pretend it's self.__root_frame"""
return getattr(self.__root_frame, attr)
def rebuild_layout(self):
node_desc = GraphNodeDescription(self.__item, self._has_input_connection[0], self._has_input_connection[1])
def __build_node_bg():
self.__delegate.node_background(self.__model, node_desc)
def __build_footer():
self.__delegate.node_footer(self.__model, node_desc)
def __build_header():
self.__delegate.node_header(self.__model, node_desc)
if not self._header_widget.has_build_fn():
self._header_widget.set_build_fn(__build_header)
self._header_widget.rebuild()
if not self._node_bg_widget.has_build_fn():
self._node_bg_widget.set_build_fn(__build_node_bg)
self._node_bg_widget.rebuild()
if not self._footer_widget.has_build_fn():
self._footer_widget.set_build_fn(__build_footer)
self._footer_widget.rebuild()
def __build_layout(self):
"""
Build the Node layout with the delegate. See GraphNodeDelegate for info.
When it's called, it will replace all the sub-widgets.
"""
self._port_to_frames.clear()
self._port_to_user_drag.clear()
self._port_to_user_drag_placer.clear()
self._port_center_widgets.clear()
# Sorting ports for column layout. If the port has inputs only, it goes
# to input_ports. IF the port has both inputs and outputs, it goes to
# mixed_ports.
mixed_ports = []
input_ports = []
output_ports = []
node_desc = GraphNodeDescription(self.__item, self._has_input_connection[0], self._has_input_connection[1])
node_layout = self.__delegate.get_node_layout(self.__model, node_desc)
for port_entry in self.__ports:
if node_layout == GraphNodeLayout.LIST or node_layout == GraphNodeLayout.HEAP:
mixed_ports.append(port_entry)
elif node_layout == GraphNodeLayout.COLUMNS:
port, port_input_flags, port_output_flags, level, position, parent_child_count = port_entry
inputs = self.__model[port].inputs
outputs = self.__model[port].outputs
if inputs is None and outputs is None:
input_ports.append(port_entry)
elif inputs is not None and outputs is None:
input_ports.append(port_entry)
elif inputs is None and outputs is not None:
output_ports.append(port_entry)
else:
mixed_ports.append(port_entry)
with self.__root_frame:
# See GraphNodeDelegate for the detailed information on the layout
with ui.ZStack(height=0):
self._node_bg_widget = ui.Frame()
with self._node_bg_widget:
self.__delegate.node_background(self.__model, node_desc)
if node_layout == GraphNodeLayout.HEAP:
stack = ui.ZStack(height=0)
else:
stack = ui.VStack(height=0)
with stack:
# Header
with ui.HStack():
self._header_input_widget = ui.Frame(width=0)
with self._header_input_widget:
port_widget = self.__delegate.node_header_input(self.__model, node_desc)
# The way to set the center of connection. If the
# port function doesn't return anything, the
# connection is centered to the frame. If it
# returns a widget, the connection is centered to
# the widget returned.
if port_widget:
self._header_input_widget = port_widget
self._header_widget = ui.Frame()
with self._header_widget:
self.__delegate.node_header(self.__model, node_desc)
self._header_output_widget = ui.Frame(width=0)
with self._header_output_widget:
port_widget = self.__delegate.node_header_output(self.__model, node_desc)
# Set the center of connection.
if port_widget:
self._header_output_widget = port_widget
# One port per line
for port, port_input_flags, port_output_flags, port_level, pos, siblings in mixed_ports:
self.__build_port(
node_desc,
port,
port_input_flags,
port_output_flags,
port_level,
pos,
siblings,
node_layout == GraphNodeLayout.HEAP,
)
# Two ports per line
with ui.HStack():
# width=0 lets each column only take up the amount of space it needs
with ui.VStack(height=0, width=0):
for port, port_input_flags, port_output_flags, port_level, pos, siblings in input_ports:
self.__build_port(
node_desc, port, port_input_flags, None, port_level, pos, siblings, False
)
ui.Spacer() # spreads the 2 sides apart from each other
with ui.VStack(height=0, width=0):
for port, port_input_flags, port_output_flags, port_level, pos, siblings in output_ports:
self.__build_port(
node_desc, port, None, port_output_flags, port_level, pos, siblings, False
)
# Footer
self._footer_widget = ui.Frame()
with self._footer_widget:
self.__delegate.node_footer(self.__model, node_desc)
def __build_port(
self,
node_desc: GraphNodeDescription,
port,
port_input_flags,
port_output_flags,
level: int,
relative_position: int,
parent_child_count: int,
is_heap: bool,
):
"""The layout for one single port line."""
# port_input_flags is a tuple of 2 bools. The first item is the flag
# that is True if the port is a source in connection to the input (left
# side). The second item is the flag that is True when this port is a
# target in the connection to the input. port_output_flags is the same
# for output (right side). If port_input_flags or port_output_flags is
# None, it doesn't produce left or right part.
if is_heap:
width = ui.Fraction(1)
stack = ui.ZStack()
else:
width = ui.Pixel(0)
stack = ui.HStack()
with stack:
if port_input_flags is None:
input_port_widget = None
else:
input_port_widget = ui.Frame(width=width)
with input_port_widget:
port_desc = GraphPortDescription(
port, level, relative_position, parent_child_count, port_input_flags[0], port_input_flags[1]
)
port_widget = self.__delegate.port_input(self.__model, node_desc, port_desc)
# Set the center of connection.
if port_widget:
input_port_widget = port_widget
port_desc = GraphPortDescription(port, level, relative_position, parent_child_count)
port_center_widget = self.__delegate.port(self.__model, node_desc, port_desc)
self._port_center_widgets[port_desc.port] = port_center_widget
def fit_to_mose(placer: ui.Placer, x: float, y: float):
"""
If the port is big we need to make the placer small enough
and move it to the mouse cursor to make the connection follow
the mouse
"""
# The new size
SIZE = 3.0
placer.width = ui.Pixel(SIZE)
placer.height = ui.Pixel(SIZE)
# Move to the mouse position
placer.offset_x = x - placer.screen_position_x - SIZE / 2
placer.offset_y = y - placer.screen_position_y - SIZE / 2
def reset_offset(placer: ui.Placer):
# Put it back to the port
placer.offset_x = 0
placer.offset_y = 0
# Restore the size
placer.width = ui.Fraction(1)
placer.height = ui.Fraction(1)
def set_draggable(placer: ui.Placer, frame: ui.Frame, draggable: bool):
placer.draggable = draggable
if port_output_flags is None:
output_port_widget = None
else:
with ui.ZStack(width=width):
# The placer and the widget that follows the
# mouse cursor when the user creates a
# connection
output_userconnection_placer = ui.Placer(stable_size=True, draggable=True)
output_userconnection_placer.set_mouse_pressed_fn(
lambda x, y, *_, p=output_userconnection_placer: fit_to_mose(p, x, y)
)
output_userconnection_placer.set_mouse_released_fn(
lambda *_, p=output_userconnection_placer: reset_offset(p)
)
if port_center_widget:
port_center_widget.set_mouse_pressed_fn(
lambda *_, p=output_userconnection_placer, w=port_center_widget: set_draggable(p, w, False)
)
port_center_widget.set_mouse_released_fn(
lambda *_, p=output_userconnection_placer, w=port_center_widget: set_draggable(p, w, True)
)
self._port_to_user_drag_placer[port] = output_userconnection_placer
with output_userconnection_placer:
# This widget follows the cursor when the
# user creates a connection. Line is
# stuck to this widget.
rect = ui.Spacer()
self._port_to_user_drag[port] = (None, rect)
# The port widget
output_port_widget = ui.Frame()
with output_port_widget:
port_desc = GraphPortDescription(
port,
level,
relative_position,
parent_child_count,
port_output_flags[0],
port_output_flags[1],
)
port_widget = self.__delegate.port_output(self.__model, node_desc, port_desc)
# Set the center of connection.
if port_widget:
output_port_widget = port_widget
# Save input and output frame for each port
self._port_to_frames[port] = (input_port_widget, output_port_widget)
@property
def ports(self):
return self._port_to_frames
@property
def port_center_widgets(self):
"""
Return the dict for port center widgets (which contains the port name label and edit fields).
Dictionary key is the port, value is ui.Widget or None if the delegate does not return a widget
"""
return self._port_center_widgets
@property
def user_drag(self):
"""
Return the dict with the port as the key and widget that follows the
mouse cursor when the user creates a connection.
"""
return self._port_to_user_drag
@property
def user_drag_placer(self):
"""
Return the dict with the port as the key and placer that follows the
mouse cursor when the user creates a connection.
"""
return self._port_to_user_drag_placer
@property
def header_input_frame(self):
"""
Return the Frame that holds the inputs on the left side of the header bar.
"""
return self._header_input_widget
@property
def header_output_frame(self):
"""
Return the Frame that holds the outputs on the right side of the header bar.
"""
return self._header_output_widget
@property
def header_frame(self):
"""
Return the Frame that holds the entire header bar.
"""
return self._header_widget
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
self._port_to_frames = None
self._port_to_user_drag = None
self._port_to_user_drag_placer = None
self._port_center_widgets = None
if self.__root_frame:
self.__root_frame.destroy()
self.__root_frame = None
self.__model = None
self.__delegate = None
self._header_widget = None
self._footer_widget = None
self._node_bg_widget = None
@property
def skip_draw_clipped(self):
"""Get skip_draw_when_clipped property of the root frame"""
return self.__root_frame.skip_draw_when_clipped
@skip_draw_clipped.setter
def skip_draw_clipped(self, value):
"""Set skip_draw_when_clipped property of the root frame"""
self.__root_frame.skip_draw_when_clipped = value
@property
def selected(self):
"""Return the widget selected style state"""
if self.__root_frame:
return self.__root_frame.selected
@selected.setter
def selected(self, value):
"""Set the widget selected style state"""
if self.__root_frame:
self.__root_frame.selected = value
@property
def visible(self) -> bool:
return self.__root_frame.visible
@visible.setter
def visible(self, value: bool):
self.__root_frame.visible = value
| 16,808 | Python | 39.997561 | 119 | 0.539624 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/abstract_batch_position_getter.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__ = ["AbstractBatchPositionGetter"]
from typing import Any, List, Optional
import weakref
import abc
from .graph_model import GraphModel
class AbstractBatchPositionGetter(abc.ABC):
"""Helper to get the nodes to move at the same time"""
def __init__(self, model: GraphModel):
self.model = model
@property
def model(self):
return self.__model()
@model.setter
def model(self, value):
self.__model = weakref.ref(value)
@abc.abstractmethod
def __call__(self, drive_item: Any) -> Optional[List[Any]]:
pass
| 1,009 | Python | 29.60606 | 76 | 0.718533 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/backdrop_getter.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__ = ["BackdropGetter"]
from functools import lru_cache
from typing import Any, Callable, List, Optional
import carb.input
from .abstract_batch_position_getter import AbstractBatchPositionGetter
from .graph_model import GraphModel
@lru_cache()
def __get_input() -> carb.input.IInput:
return carb.input.acquire_input_interface()
def _is_alt_down() -> bool:
input = __get_input()
return (
input.get_keyboard_value(None, carb.input.KeyboardInput.LEFT_ALT)
+ input.get_keyboard_value(None, carb.input.KeyboardInput.RIGHT_ALT)
> 0
)
class BackdropGetter(AbstractBatchPositionGetter):
"""Helper to get the nodes that placed in the given backdrop"""
def __init__(self, model: GraphModel, is_backdrop_fn: Callable[[Any], bool], graph_widget = None):
super().__init__(model)
# Callback to determine if the node is a backdrop
self.__is_backdrop_fn = is_backdrop_fn
self.__graph_widget = graph_widget
def __call__(self, drive_item: Any) -> Optional[List[Any]]:
# Get siblings and return
MIN_OFFSET = 25 # Same value used in _create_backdrop_for_selected_nodes()
# If user presses ALT while moving the backdrop, don't carry nodes with it.
if _is_alt_down():
return []
model = self.model
if model and self.__is_backdrop_fn(drive_item):
position = model[drive_item].position
size = model[drive_item].size
if position and size:
result = []
for node in model.nodes:
node_position = model[node].position
if not node_position:
continue
# Add the node size offset to the extent
if self.__graph_widget:
widget = self.__graph_widget._graph_view._node_widgets[node]
s = (widget.computed_width, widget.computed_height)
else:
s = (0, 0) # For backwards compatibility
# Check if the node is inside the backdrop
if (
node_position[0] < position[0]
or node_position[1] < position[1]
or node_position[0] + s[0] > position[0] + size[0] + MIN_OFFSET
or node_position[1] + s[1] > position[1] + size[1] + MIN_OFFSET
):
continue
result.append(node)
return result
| 3,013 | Python | 35.313253 | 102 | 0.58845 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_model_batch_position_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__ = ["GraphModelBatchPositionHelper"]
from .abstract_batch_position_getter import AbstractBatchPositionGetter
from typing import Any, Callable, Dict, List, Tuple, Union
import weakref
class GraphModelBatchPositionHelper:
"""
The model that manages batch position of the items. It can be used to manage
the position of multi selection, backdrops and upstreams.
"""
def __init__(self):
super().__init__()
# Indicates that the method multiselection_set_position is called and
# not finished. We need it because multiselection_set_position can be
# called recursively
self.__position_set_in_process = False
# The same for multiselection_position_begin_edit
self.__position_begin_edit_in_process = False
# The same for multiselection_position_end_edit
self.__position_end_edit_in_process = False
# The node that drives position of many nodes. It's the node the user
# actually drags.
self.__current_drive_node = None
# Other nodes in the selection
self.__driven_nodes: List = []
self.__position_difference: Dict[Any, Union[List, Tuple]] = {}
# Functions to get the nodes that are moving
self.__get_moving_items_fns = {}
# Proxy is the isolation model. We need it to set the position of
# input/output nodes.
self.__batch_proxy = None
self.batch_proxy = self
@property
def batch_proxy(self):
"""
Proxy is the isolation model. We need it because it converts calls to
input/output nodes.
"""
return self.__batch_proxy()
@batch_proxy.setter
def batch_proxy(self, value):
# Weak ref so we don't have circular references
self.__batch_proxy = weakref.ref(value)
for _, fn in self.__get_moving_items_fns.items():
if isinstance(fn, AbstractBatchPositionGetter):
fn.model = value
def add_get_moving_items_fn(self, fn: Callable[[Any], List[Any]]):
"""
Add the function that is called in batch_position_begin_edit to
determine which items to move
"""
def get_new_id(batch_position_fns: Dict[int, Callable]):
if not batch_position_fns:
return 0
return max(batch_position_fns.keys()) + 1
class Subscription:
"""The object that will remove the callback when destroyed"""
def __init__(self, parent, id):
self.__parent = weakref.ref(parent)
self.__id = id
def __del__(self):
parent = self.__parent()
if parent:
parent._remove_batch_position_fn(self.__id)
id = get_new_id(self.__get_moving_items_fns)
self.__get_moving_items_fns[id] = fn
def _remove_get_moving_items_fn(self, id: int):
self.__get_moving_items_fns.pop(id, None)
def batch_set_position(self, position: List[float], item: Any = None):
"""
Should be called in the position setter to make sure the position
setter is called for all the selected nodes
"""
if self.__position_set_in_process:
return
if self.__current_drive_node != item:
# Somehow it's possible that batch_set_position is called for the
# wrong node. We need to filter such cases. It happens rarely, but
# when it happens, it leads to a crash because the node applies the
# diff to itself infinitely.
# TODO: investigate OM-58441 more
return
self.__position_set_in_process = True
try:
current_position = position
if not current_position:
# Can't do anything without knowing position
return
for node in self.__driven_nodes:
diff = self.__position_difference.get(node, None)
if diff:
self.batch_proxy[node].position = (
diff[0] + current_position[0],
diff[1] + current_position[1],
)
# TODO: except
finally:
self.__position_set_in_process = False
def batch_position_begin_edit(self, item: Any):
"""
Should be called from position_begin_edit to make sure
position_begin_edit is called for all the selected nodes
"""
if self.__position_begin_edit_in_process:
return
self.__position_begin_edit_in_process = True
try:
# The current node is the drive node.
self.__current_drive_node = item
# Get driven nodes from the callbacks
driven_nodes = []
for _, fn in self.__get_moving_items_fns.items():
driven_nodes += fn(self.__current_drive_node) or []
# Just in case filter out drive node
self.__driven_nodes = [i for i in driven_nodes if i != self.__current_drive_node]
current_position = self.batch_proxy[self.__current_drive_node].position
if not current_position:
# Can't do anything without knowing position
return
for node in self.__driven_nodes:
node_position = self.batch_proxy[node].position
if node_position:
self.__position_difference[node] = (
node_position[0] - current_position[0],
node_position[1] - current_position[1],
)
self.batch_proxy.position_begin_edit(node)
# TODO: except
finally:
self.__position_begin_edit_in_process = False
def batch_position_end_edit(self, item: Any):
"""
Should be called from position_begin_edit to make sure
position_begin_edit is called for all the selected nodes
"""
if self.__position_end_edit_in_process:
return
self.__position_end_edit_in_process = True
try:
for node in self.__driven_nodes:
self.batch_proxy.position_end_edit(node)
# Clean up
self.__driven_nodes = []
self.__position_difference = {}
# TODO: except
finally:
self.__position_end_edit_in_process = False
| 6,864 | Python | 34.386598 | 93 | 0.584062 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/graph_node_delegate_router.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__ = ["GraphNodeDelegateRoutingError", "GraphNodeDelegateRouter", "RoutingCondition"]
from .abstract_graph_node_delegate import AbstractGraphNodeDelegate
from .abstract_graph_node_delegate import GraphConnectionDescription
from .abstract_graph_node_delegate import GraphNodeDescription
from .abstract_graph_node_delegate import GraphPortDescription
from collections import namedtuple
RoutingCondition = namedtuple("RoutingCondition", ["type", "expression", "delegate"])
class GraphNodeDelegateRoutingError(Exception):
"""
This exception is used when it's not possible to do routing. Can only
happen if there is no default route in the table.
"""
pass
class GraphNodeDelegateRouter(AbstractGraphNodeDelegate):
"""
The delegate that keeps multiple delegates and pick them depending on the
routing conditions.
It's possible to add the routing conditions with `add_route`, and
conditions could be a type or a lambda expression.
The latest added routing is stronger than previously added. Routing added
without conditions is the default.
We use type routing to make the specific kind of nodes unique, and also
we can use the lambda function to make the particular state of nodes
unique (ex. full/collapsed).
It's possible to use type and lambda routing at the same time.
Usage examples:
delegate.add_route(TextureDelegate(), type="Texture2d")
delegate.add_route(CollapsedDelegate(), expressipon=is_collapsed)
"""
def __init__(self):
super().__init__()
self.__routing_table = []
def add_route(self, delegate: AbstractGraphNodeDelegate, type=None, expression=None):
"""Add delegate to the routing tablle"""
if not delegate:
return
if type is None and expression is None:
# It's a default delegate, we don't need what we had before
self.__routing_table.clear()
self.__routing_table.append(RoutingCondition(type, expression, delegate))
def __route(self, model, node):
"""Return the delegate for the given node"""
for c in reversed(self.__routing_table):
if (c.type is None or model[node].type == c.type) and (c.expression is None or c.expression(model, node)):
return c.delegate
raise GraphNodeDelegateRoutingError("Can't route.")
def get_node_layout(self, model, node_desc: GraphNodeDescription):
"""Called to determine the node layout"""
return self.__route(model, node_desc.node).get_node_layout(model, node_desc)
def node_background(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the node background"""
return self.__route(model, node_desc.node).node_background(model, node_desc)
def node_header_input(self, model, node_desc: GraphNodeDescription):
"""Called to create the left part of the header that will be used as input when the node is collapsed"""
return self.__route(model, node_desc.node).node_header_input(model, node_desc)
def node_header_output(self, model, node_desc: GraphNodeDescription):
"""Called to create the right part of the header that will be used as output when the node is collapsed"""
return self.__route(model, node_desc.node).node_header_output(model, node_desc)
def node_header(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the top of the node"""
return self.__route(model, node_desc.node).node_header(model, node_desc)
def node_footer(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the bottom of the node"""
return self.__route(model, node_desc.node).node_footer(model, node_desc)
def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the left part of the port that will be used as input"""
return self.__route(model, node_desc.node).port_input(model, node_desc, port_desc)
def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the right part of the port that will be used as output"""
return self.__route(model, node_desc.node).port_output(model, node_desc, port_desc)
def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the middle part of the port"""
return self.__route(model, node_desc.node).port(model, node_desc, port_desc)
def connection(self, model, source: GraphConnectionDescription, target: GraphConnectionDescription):
"""Called to create the connection between ports"""
return self.__route(model, source.node).connection(model, source, target)
def destroy(self):
while self.__routing_table:
routing_condition = self.__routing_table.pop()
routing_condition.delegate.destroy()
| 5,426 | Python | 43.851239 | 118 | 0.707519 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/selection_getter.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__ = ["SelectionGetter"]
from .abstract_batch_position_getter import AbstractBatchPositionGetter
from typing import Any
import weakref
from .graph_model import GraphModel
class SelectionGetter(AbstractBatchPositionGetter):
"""
Helper to get the selection of the given model. It's supposed to be
used with GraphModelBatchPosition.
"""
def __init__(self, model: GraphModel):
super().__init__(model)
def __call__(self, drive_item: Any):
model = self.model
if model:
return model.selection
| 988 | Python | 33.103447 | 76 | 0.737854 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/abstract_graph_node_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["GraphNodeLayout", "GraphNodeDescription", "GraphPortDescription", "GraphConnectionDescription", "AbstractGraphNodeDelegate"]
from enum import Enum, auto
class GraphNodeLayout(Enum):
LIST = auto()
COLUMNS = auto()
HEAP = auto()
class GraphNodeDescription:
"""The object that holds the main attributes of the node"""
def __init__(self, node, connected_source=None, connected_target=None):
self.node = node
self.connected_source = connected_source
self.connected_target = connected_target
class GraphPortDescription:
"""The object that holds the main attributes of the port"""
def __init__(
self, port, level, relative_position, parent_child_count, connected_source=None, connected_target=None
):
self.port = port
self.level = level
self.relative_position = relative_position
self.parent_child_count = parent_child_count
self.connected_source = connected_source
self.connected_target = connected_target
class GraphConnectionDescription:
"""The object that holds the main attributes of the connection"""
def __init__(self, node, port, widget, level, is_tangent_reversed=False):
self.node = node
self.port = port
self.widget = widget
self.level = level
self.is_tangent_reversed = is_tangent_reversed
class AbstractGraphNodeDelegate:
"""
The delegate generates widgets that together form the node using the
model. The following figure shows the LIST layout of the node. For every
zone, there is a method that is called to build this zone.
::
+-------------------------+
| node_background |
| +---+-------------+---+ |
| |[A]| node_header |[B]| |
| +---+-------------+---+ |
| |[C]| port |[D]| |
| +---+-------------+---+ |
| |[D]| port |[D]| |
| +---+-------------+---+ |
| |[E]| node_footer |[F]| |
| +---+-------------+---+ |
+-------------------------+
COLUMN layout allows to put input and output ports at the same line:
::
+-------------------------+
| node_background |
| +---+-------------+---+ |
| |[A]| node_header |[B]| |
| +---+------+------+---+ |
| |[C]| port | port |[D]| |
| | | |------+---| |
| |---+------| port |[D]| |
| |[D]| port | | | |
| +---+------+------+---+ |
| |[E]| node_footer |[F]| |
| +---+-------------+---+ |
+-------------------------+
::
[A] node_header_input
[B] node_header_output
[C] port_input
[D] port_output
[E] node_footer_input (TODO)
[F] node_footer_output (TODO)
"""
def destroy(self):
pass
def get_node_layout(self, model, node_desc: GraphNodeDescription):
"""Called to determine the node layout"""
return GraphNodeLayout.LIST
def node_background(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the node background"""
pass
def node_header_input(self, model, node_desc: GraphNodeDescription):
"""Called to create the left part of the header that will be used as input when the node is collapsed"""
pass
def node_header_output(self, model, node_desc: GraphNodeDescription):
"""Called to create the right part of the header that will be used as output when the node is collapsed"""
pass
def node_header(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the top of the node"""
pass
def node_footer(self, model, node_desc: GraphNodeDescription):
"""Called to create widgets of the bottom of the node"""
pass
def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the left part of the port that will be used as input"""
pass
def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the right part of the port that will be used as output"""
pass
def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
"""Called to create the middle part of the port"""
pass
def connection(self, model, source_desc: GraphConnectionDescription, target_desc: GraphConnectionDescription):
"""Called to create the connection between ports"""
pass
| 5,051 | Python | 33.602739 | 136 | 0.583449 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/tests/test_delegate.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from omni.kit.widget.graph.graph_node_delegate import GraphNodeDelegate
from omni.kit.widget.graph.graph_view import GraphView
from omni.ui.tests.test_base import OmniUiTest
from .test_graph import Model
import omni.kit.app
class TestDelegate(OmniUiTest):
async def test_general(self):
"""Testing general properties of the GraphView default delegate"""
window = await self.create_test_window(768, 512)
style = GraphNodeDelegate.get_style()
# Don't use the image because the image scaling looks different in editor and kit-mini
style["Graph.Node.Footer.Image"]["image_url"] = ""
style["Graph.Node.Header.Collapse"]["image_url"] = ""
style["Graph.Node.Header.Collapse::Minimized"]["image_url"] = ""
style["Graph.Node.Header.Collapse::Closed"]["image_url"] = ""
with window.frame:
delegate = GraphNodeDelegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style, pan_x=600, pan_y=170)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(3):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_zoom(self):
"""Testing zooming of the GraphView default delegate"""
window = await self.create_test_window(384, 256)
style = GraphNodeDelegate.get_style()
# Don't use the image because the image scaling looks different in editor and kit-mini
style["Graph.Node.Footer.Image"]["image_url"] = ""
style["Graph.Node.Header.Collapse"]["image_url"] = ""
style["Graph.Node.Header.Collapse::Minimized"]["image_url"] = ""
style["Graph.Node.Header.Collapse::Closed"]["image_url"] = ""
with window.frame:
delegate = GraphNodeDelegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style, zoom=0.5, pan_x=300, pan_y=85)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(3):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_focus(self):
"""Testing focusing of the GraphView default delegate"""
window = await self.create_test_window(768, 512)
style = GraphNodeDelegate.get_style()
# Don't use the image because the image scaling looks different in editor and kit-mini
style["Graph.Node.Footer.Image"]["image_url"] = ""
style["Graph.Node.Header.Collapse"]["image_url"] = ""
style["Graph.Node.Header.Collapse::Minimized"]["image_url"] = ""
style["Graph.Node.Header.Collapse::Closed"]["image_url"] = ""
with window.frame:
delegate = GraphNodeDelegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(3):
await omni.kit.app.get_app().next_update_async()
graph_view.focus_on_nodes()
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
| 3,782 | Python | 41.988636 | 110 | 0.654944 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/tests/test_graph_with_subports.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["TestGraphWithSubports"]
import omni.kit.test
from omni.kit.widget.graph import GraphNodeDescription
from omni.kit.widget.graph import GraphPortDescription
from omni.kit.widget.graph.abstract_graph_node_delegate import AbstractGraphNodeDelegate
from omni.kit.widget.graph.graph_model import GraphModel
from omni.kit.widget.graph.graph_view import GraphView
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
from functools import partial
inputs = ["First.color1", "First.color1.tex", "First.color1.shader", "First.color2", "Third.size", "Fourth.color1", "Fourth.color1.tex", "Fourth.color1.shader",]
outputs = ["First.result", "Second.out", "Third.outcome", "Third.outcome.out1", "Third.outcome.out2"]
connections = {"First.color1.tex": ["Second.out"], "First.color2": ["Third.outcome.out2"], "Fourth.color1.tex": ["Third.outcome.out1"]}
style = {
"Graph": {"background_color": 0xFF000000},
"Graph.Connection": {"color": 0xFFDBA656, "background_color": 0xFFDBA656, "border_width": 2.0},
}
BORDER_WIDTH = 16
class Model(GraphModel):
def __init__(self):
super().__init__()
@property
def nodes(self, item=None):
if item:
return
return sorted(set([n.split(".")[0] for n in inputs + outputs]))
@property
def name(self, item=None):
return item.split(".")[-1]
@property
def ports(self, item=None):
item_len = len(item.split("."))
if item_len == 1 or item_len == 2:
result = [n for n in inputs + outputs if n.startswith(item) and len(n.split(".")) == item_len + 1]
return result
return []
@property
def expansion_state(self, item=None):
"""the expansion state of a node or a port"""
item_len = len(item.split("."))
if item_len == 2:
return GraphModel.ExpansionState.CLOSED
return GraphModel.ExpansionState.OPEN
@property
def inputs(self, item):
if item in inputs:
return connections.get(item, [])
return None
@property
def outputs(self, item):
if item in outputs:
return []
return None
class ExpandModel(Model):
def __init__(self):
super().__init__()
@property
def expansion_state(self, item=None):
"""the expansion state of a node or a port"""
return GraphModel.ExpansionState.OPEN
class Delegate(AbstractGraphNodeDelegate):
def node_background(self, model, node_desc: GraphNodeDescription):
ui.Rectangle(style={"background_color": 0xFF015C3A})
def node_header(self, model, node_desc: GraphNodeDescription):
ui.Label(model[node_desc.node].name, style={"font_size": 12, "margin": 6, "color": 0xFFDBA656})
def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
# this is output port
if model[port_desc.port].inputs is None:
color = 0x0
elif port_desc.connected_target:
color = 0xFFDBA6FF
else:
color = 0xFFDBA656
ui.Circle(width=10, style={"background_color": color})
def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
# this is output port
if model[port_desc.port].outputs is None:
color = 0x0
elif port_desc.connected_source:
color = 0xFFDBA6FF
else:
color = 0xFFDBA656
ui.Circle(width=10, style={"background_color": color})
def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
def set_expansion_state(model, port, state: GraphModel.ExpansionState, *args):
model[port].expansion_state = state
port = port_desc.port
level = port_desc.level
sub_ports = model[port].ports
is_group = len(sub_ports) > 0
def draw_collapse_button():
if is_group:
state = model[port].expansion_state
if state == GraphModel.ExpansionState.CLOSED:
button_name = "+"
next_state = GraphModel.ExpansionState.OPEN
else:
button_name = "-"
next_state = GraphModel.ExpansionState.CLOSED
ui.Label(button_name,
width=10,
style={"font_size": 10, "margin": 2},
mouse_pressed_fn=partial(set_expansion_state, model, port, next_state))
else:
ui.Spacer(width=10)
def draw_branch():
if level > 0:
ui.Line(width=8, style={"color": 0xFFFFFFFF})
alignment = ui.Alignment.LEFT if model[port].inputs is not None else ui.Alignment.RIGHT
with ui.HStack():
if alignment == ui.Alignment.RIGHT:
ui.Spacer(width=40)
else:
draw_collapse_button()
draw_branch()
ui.Label(model[port].name, style={"font_size": 10, "margin": 2}, alignment=alignment)
if alignment == ui.Alignment.RIGHT:
draw_branch()
draw_collapse_button()
else:
ui.Spacer(width=40)
def connection(self, model, source, target):
"""Called to create the connection between ports"""
# If the connection is reversed, we need to mirror tangents
ui.FreeBezierCurve(target.widget, source.widget, style={"color": 0xFFFFFFFF})
class TestGraphWithSubports(OmniUiTest):
"""Testing GraphView"""
async def test_general(self):
"""Testing general properties of GraphView with port_grouping is True"""
window = await self.create_test_window(512, 256)
with window.frame:
delegate = Delegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style, pan_x=400, pan_y=100, port_grouping=True)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(3):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_expansion(self):
"""Testing subport expansion"""
window = await self.create_test_window(512, 256)
with window.frame:
delegate = Delegate()
model = ExpandModel()
graph_view = GraphView(model=model, delegate=delegate, style=style, pan_x=400, pan_y=100, port_grouping=True)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(3):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test() | 7,229 | Python | 36.268041 | 161 | 0.618481 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/tests/test_graph.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["TestGraph"]
import omni.kit.test
from omni.kit.widget.graph import GraphNodeDescription
from omni.kit.widget.graph import GraphNodeLayout
from omni.kit.widget.graph import GraphPortDescription
from omni.kit.widget.graph.abstract_graph_node_delegate import AbstractGraphNodeDelegate
from omni.kit.widget.graph.graph_model import GraphModel
from omni.kit.widget.graph.graph_view import GraphView
from omni.ui import color as cl
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
inputs = ["First.color1", "First.color2", "Third.size"]
outputs = ["First.result", "Second.out", "Third.outcome"]
connections = {"First.color1": ["Second.out"], "First.color2": ["Third.outcome"]}
style = {
"Graph": {"background_color": 0xFF000000},
"Graph.Connection": {"color": 0xFFDBA656, "background_color": 0xFFDBA656, "border_width": 2.0},
}
BORDER_WIDTH = 16
class Model(GraphModel):
def __init__(self):
super().__init__()
self.__positions = {}
@property
def nodes(self, item=None):
if item:
return
return sorted(set([n.split(".")[0] for n in inputs + outputs]))
@property
def name(self, item=None):
return item.split(".")[-1]
@property
def ports(self, item=None):
if item in inputs:
return
if item in outputs:
return
return [n for n in inputs + outputs if n.startswith(item)]
@property
def inputs(self, item):
if item in inputs:
return connections.get(item, [])
@property
def outputs(self, item):
if item in outputs:
return []
@property
def position(self, item=None):
"""Returns the position of the node"""
return self.__positions.get(item, None)
@position.setter
def position(self, value, item=None):
"""The node position setter"""
self.__positions[item] = value
class Delegate(AbstractGraphNodeDelegate):
def node_background(self, model, node_desc: GraphNodeDescription):
ui.Rectangle(style={"background_color": 0xFF015C3A})
def node_header(self, model, node_desc: GraphNodeDescription):
ui.Label(model[node_desc.node].name, style={"font_size": 12, "margin": 6, "color": 0xFFDBA656})
def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
color = 0xFFDBA656 if port_desc.connected_target else 0x0
ui.Circle(width=10, style={"background_color": color})
def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
color = 0xFFDBA656 if port_desc.connected_source else 0x0
ui.Circle(width=10, style={"background_color": color})
def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
ui.Label(model[port_desc.port].name, style={"font_size": 10, "margin": 2})
def connection(self, model, source, target):
"""Called to create the connection between ports"""
# If the connection is reversed, we need to mirror tangents
ui.FreeBezierCurve(target.widget, source.widget, style={"color": 0xFFFFFFFF})
class DelegateHeap(AbstractGraphNodeDelegate):
def get_node_layout(self, model, node_desc: GraphNodeDescription):
return GraphNodeLayout.HEAP
def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
return ui.Rectangle(style={"background_color": cl(1.0, 0.0, 0.0, 1.0)})
def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
return ui.Rectangle(style={"background_color": cl(0.0, 1.0, 1.0, 0.5)})
def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription):
with ui.HStack():
ui.Spacer(width=BORDER_WIDTH)
with ui.VStack():
ui.Spacer(height=BORDER_WIDTH)
frame = ui.Frame(separate_window=True)
with frame:
with ui.ZStack():
ui.Rectangle(width=32, height=32, style={"background_color": cl(0.75)})
ui.Spacer(height=BORDER_WIDTH)
ui.Spacer(width=BORDER_WIDTH)
return frame
def connection(self, model, source, target):
"""Called to create the connection between ports"""
ui.OffsetLine(
target.widget,
source.widget,
alignment=ui.Alignment.UNDEFINED,
begin_arrow_type=ui.ArrowType.ARROW,
bound_offset=20,
style_type_name_override="Graph.Connection",
style={"color": cl.white, "border_width": 1.0},
)
class TestGraph(OmniUiTest):
"""Testing GraphView"""
async def test_general(self):
"""Testing general properties of GraphView"""
window = await self.create_test_window(512, 256)
with window.frame:
delegate = Delegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style, pan_x=400, pan_y=100)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_zoom(self):
"""Testing zooming of GraphView"""
window = await self.create_test_window(256, 128)
with window.frame:
delegate = Delegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style, zoom=0.5, pan_x=200, pan_y=50)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_focus(self):
"""Testing focusing of GraphView"""
window = await self.create_test_window(512, 256)
with window.frame:
delegate = Delegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style)
# Wait several frames to draw and auto-layout.
for i in range(10):
await omni.kit.app.get_app().next_update_async()
graph_view.focus_on_nodes()
for i in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertAlmostEqual(graph_view.zoom, 1.6606260538101196)
await self.finalize_test()
async def test_focus_with_zoom_limits(self):
"""Testing focusing of GraphView"""
window = ui.Window("test", width=512, height=256)
with window.frame:
delegate = Delegate()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style, zoom_max=1.5)
# Wait several frames to draw and auto-layout.
for i in range(10):
await omni.kit.app.get_app().next_update_async()
graph_view.focus_on_nodes()
for i in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertAlmostEqual(graph_view.zoom, 1.5, places=4)
async def test_heap(self):
"""Testing general properties of GraphView"""
window = await self.create_test_window(512, 256)
with window.frame:
delegate = DelegateHeap()
model = Model()
graph_view = GraphView(model=model, delegate=delegate, style=style, pan_x=400, pan_y=100)
# Two frames because the first frame is to draw, the second frame is to auto-layout.
for i in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
| 8,241 | Python | 34.991266 | 110 | 0.638393 |
omniverse-code/kit/exts/omni.kit.widget.graph/omni/kit/widget/graph/tests/test_graph_cache.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_graph import Model
from omni.ui.tests.test_base import OmniUiTest
from ..graph_node_index import GraphNodeIndex
class ModelPlus(Model):
def __init__(self):
super().__init__()
self._inputs = ["First.color1", "First.color2", "Third.size"]
self._outputs = ["First.result", "Second.out", "Third.outcome"]
self._connections = {"First.color1": ["Second.out"], "First.color2": ["Third.outcome"]}
def change(self):
self._inputs = ["First.color1", "First.color2", "Fourth.size"]
self._outputs = ["First.result", "Second.out", "Fourth.outcome"]
self._connections = {"First.color1": ["Second.out"], "First.color2": ["Fourth.outcome"]}
@property
def nodes(self, item=None):
if item:
return
return sorted(set([n.split(".")[0] for n in self._inputs + self._outputs]))
@property
def name(self, item=None):
return item.split(".")[-1]
@property
def ports(self, item=None):
if item in self._inputs:
return
if item in self._outputs:
return
return [n for n in self._inputs + self._outputs if n.startswith(item)]
@property
def inputs(self, item):
if item in self._inputs:
return self._connections.get(item, [])
@property
def outputs(self, item):
if item in self._outputs:
return []
class TestGraphCache(OmniUiTest):
async def test_general(self):
model = ModelPlus()
cache1 = GraphNodeIndex(model, True)
cache2 = GraphNodeIndex(model, True)
diff = cache1.get_diff(cache2)
self.assertTrue(diff.valid)
self.assertTrue(not diff.nodes_to_add)
self.assertTrue(not diff.connections_to_add)
self.assertTrue(not diff.nodes_to_del)
self.assertTrue(not diff.connections_to_del)
model.change()
cache2 = GraphNodeIndex(model, True)
diff = cache1.get_diff(cache2)
self.assertTrue(diff.valid)
# Check the difference
to_add = list(sorted([n.node for n in diff.nodes_to_add]))
self.assertEqual(to_add, ["First", "Fourth"])
to_add = list(sorted([(c.source_port, c.target_port) for c in diff.connections_to_add]))
self.assertEqual(to_add, [("Fourth.outcome", "First.color2"), ("Second.out", "First.color1")])
to_del = list(sorted([n.node for n in diff.nodes_to_del]))
self.assertEqual(to_del, ["First", "Third"])
to_del = list(sorted([(c.source_port, c.target_port) for c in diff.connections_to_del]))
self.assertEqual(to_del, [("Second.out", "First.color1"), ("Third.outcome", "First.color2")])
| 3,154 | Python | 35.264367 | 102 | 0.631896 |
omniverse-code/kit/exts/omni.kit.livestream.native/omni/kit/livestream/native/scripts/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.
"""Native streaming extension."""
import carb
import omni.ext
import omni.kit.livestream.bind
class NativeStreamingExtension(omni.ext.IExt):
"""Native streaming extension."""
def __init__(self) -> None:
super().__init__()
self._stream_interface = None
def on_startup(self) -> None:
self._kit_livestream = omni.kit.livestream.bind.acquire_livestream_interface()
self._kit_livestream.startup()
self._register_streaming_interface()
def on_shutdown(self) -> None:
self._unregister_streaming_interface()
self._kit_livestream.shutdown()
self._kit_livestream = None
def _register_streaming_interface(self) -> None:
"""Register the streaming interface for the extension."""
try:
from omni.services.streaming.manager import get_stream_manager, StreamManager
from .streaming_interface import NativeStreamInterface
self._stream_interface = NativeStreamInterface()
stream_manager: StreamManager = get_stream_manager()
stream_manager.register_stream_interface(stream_interface=self._stream_interface)
stream_manager.enable_stream_interface(stream_interface_id=self._stream_interface.id)
except ImportError:
carb.log_info("The Streaming Manager extension was not available when enabling native streaming features.")
except Exception as exc:
carb.log_error(f"An error occurred while attempting to register the native streaming interface: {str(exc)}.")
def _unregister_streaming_interface(self) -> None:
"""Unregister the streaming interface for the extension."""
if self._stream_interface is None:
# No stream interface was register when enabling the extension, so there is no need to attempt to unregister
# it and the function can exit early:
return
try:
from omni.services.streaming.manager import get_stream_manager, StreamManager
stream_manager: StreamManager = get_stream_manager()
stream_manager.disable_stream_interface(stream_interface_id=self._stream_interface.id)
stream_manager.unregister_stream_interface(stream_interface_id=self._stream_interface.id)
except ImportError:
carb.log_info("The Streaming Manager extension was not available when disabling native streaming features.")
except Exception as exc:
carb.log_error(f"An error occurred while attempting to unregister the native streaming interface: {str(exc)}.")
| 3,019 | Python | 44.757575 | 123 | 0.700232 |
omniverse-code/kit/exts/omni.kit.livestream.native/omni/kit/livestream/native/scripts/streaming_interface.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.
"""Native streaming interface."""
import os
from typing import List
import psutil
import carb.settings
from omni.services.streaming.manager import StreamInterface
class NativeStreamInterface(StreamInterface):
"""Native streaming interface."""
@property
def id(self) -> str:
return "Native"
@property
def menu_label(self) -> str:
return "Native"
@property
def module_name(self) -> str:
return __name__
@property
def stream_urls(self) -> List[str]:
return self.local_ips
async def is_healthy(self) -> bool:
"""
Check if the streaming server is in a state that is considered healthy (i.e. that the streaming server listens
for connection requests on the configured port).
Args:
None
Returns:
bool: A flag indicating whether the streaming server is in a healthy state.
"""
# Confirm if the superclass may have already flagged the stream as being in an unhealthy state, in order to
# potentially return early:
is_healthy = await super().is_healthy()
if not is_healthy:
return is_healthy
# Check that the host process has the expected native streaming server port in a "LISTENING" state by querying
# its process, rather than issuing an actual request against the server:
kit_process = psutil.Process(pid=os.getpid())
expected_server_port = self._get_native_streaming_port_number()
is_listening_on_expected_port = False
for connection in kit_process.connections():
if connection.laddr.port == expected_server_port:
if connection.status is psutil.CONN_LISTEN:
is_listening_on_expected_port = True
break
return is_listening_on_expected_port
def _get_native_streaming_port_number(self) -> int:
"""
Return the port number of on which the streaming server is expected to receive connection requests.
Args:
None
Returns:
int: The port number of on which the streaming server is expected to receive connection requests.
"""
settings = carb.settings.get_settings()
native_server_port = settings.get_as_int("app/livestream/port")
return native_server_port
| 2,789 | Python | 31.44186 | 118 | 0.665113 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/__init__.py | # NOTE: all imported classes must have different class names
from .new_stage import *
from .templates import *
| 111 | Python | 26.999993 | 60 | 0.774775 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/stage_templates_menu.py | import locale
import carb
import functools
import carb.settings
import omni.kit.app
from functools import partial
def get_action_name(name):
return name.lower().replace('-', '_').replace(' ', '_')
class StageTemplateMenu:
def __init__(self):
pass
def on_startup(self):
self._build_sub_menu()
omni.kit.menu.utils.add_menu_items(self._menu_list, "File")
# update submenu if defaultTemplate changes
self._update_setting = omni.kit.app.SettingChangeSubscription(
"/persistent/app/newStage/defaultTemplate", lambda *_: omni.kit.menu.utils.refresh_menu_items("File")
)
def on_shutdown(self):
self._update_setting = None
omni.kit.menu.utils.remove_menu_items(self._menu_list, "File")
self._menu_list = None
def _build_sub_menu(self):
from omni.kit.menu.utils import MenuItemDescription
def sort_cmp(template1, template2):
return locale.strcoll(template1[0], template2[0])
sub_menu = []
default_template = omni.kit.stage_templates.get_default_template()
stage_templates = omni.kit.stage_templates.get_stage_template_list()
def template_ticked(sn: str) -> bool:
return omni.kit.stage_templates.get_default_template() == sn
for template_list in stage_templates:
for template in sorted(template_list.items(), key=functools.cmp_to_key(sort_cmp)):
stage_name = template[0]
sub_menu.append(
MenuItemDescription(
name=stage_name.replace("_", " ").title(),
ticked=True,
ticked_fn=lambda sn=template[0]: template_ticked(sn),
onclick_action=("omni.kit.stage.templates", f"create_new_stage_{get_action_name(stage_name)}")
)
)
self._menu_list = [
MenuItemDescription(
name="New From Stage Template", glyph="file.svg", appear_after=["Open Recent", "New"], sub_menu=sub_menu
)
]
def _rebuild_sub_menu(self):
if self._menu_list:
omni.kit.menu.utils.remove_menu_items(self._menu_list, "File")
self._build_sub_menu()
omni.kit.menu.utils.add_menu_items(self._menu_list, "File")
| 2,350 | Python | 34.089552 | 120 | 0.589362 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/stage_templates_page.py | import re
import os
import carb.settings
import omni.kit.app
import omni.ui as ui
from functools import partial
from omni.kit.window.preferences import PreferenceBuilder, show_file_importer, SettingType, PERSISTENT_SETTINGS_PREFIX
class StageTemplatesPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Template Startup")
# update on setting change
def on_change(item, event_type):
if event_type == carb.settings.ChangeEventType.CHANGED:
omni.kit.window.preferences.rebuild_pages()
self._update_setting = omni.kit.app.SettingChangeSubscription(PERSISTENT_SETTINGS_PREFIX + "/app/newStage/templatePath", on_change)
def build(self):
template_paths = carb.settings.get_settings().get("/persistent/app/newStage/templatePath")
default_template = omni.kit.stage_templates.get_default_template()
script_names = []
new_templates = omni.kit.stage_templates.get_stage_template_list()
for templates in new_templates:
for template in templates.items():
script_names.append(template[0])
if len(script_names) == 0:
script_names = ["None##None"]
with ui.VStack(height=0):
with self.add_frame("New Stage Template"):
with ui.VStack():
for index, path in enumerate(template_paths):
with ui.HStack(height=24):
self.label("Path to user templates")
widget = ui.StringField(height=20)
widget.model.set_value(path)
ui.Button(style={"image_url": "resources/icons/folder.png"}, clicked_fn=lambda p=self.cleanup_slashes(carb.tokens.get_tokens_interface().resolve(path)), i=index, w=widget: self._on_browse_button_fn(p, i, w), width=24)
self.create_setting_widget_combo("Default Template", PERSISTENT_SETTINGS_PREFIX + "/app/newStage/defaultTemplate", script_names)
def _on_browse_button_fn(self, path, index, widget):
""" Called when the user picks the Browse button. """
show_file_importer(
"Select Template Directory",
click_apply_fn=lambda p=self.cleanup_slashes(path), i=index, w=widget: self._on_file_pick(
p, index=i, widget=w),
filename_url=path)
def _on_file_pick(self, full_path, index, widget):
""" Called when the user accepts directory in the Select Directory dialog. """
directory = self.cleanup_slashes(full_path, True)
settings = carb.settings.get_settings()
template_paths = settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/newStage/templatePath")
template_paths[index] = directory
settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/newStage/templatePath", template_paths)
widget.model.set_value(directory)
| 2,921 | Python | 46.901639 | 245 | 0.636768 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/new_stage.py | import os
import carb
import carb.settings
import omni.ext
import omni.kit.app
import omni.usd
import asyncio
import glob
import omni.kit.actions.core
from inspect import signature
from functools import partial
from pxr import Sdf, UsdGeom, Usd, Gf
from contextlib import suppress
from .stage_templates_menu import get_action_name
_extension_instance = None
_extension_path = None
_template_list = []
_clear_dirty_task = None
def _try_unregister_page(page: str):
with suppress(Exception):
import omni.kit.window.preferences
omni.kit.window.preferences.unregister_page(page)
# must be initalized before templates
class NewStageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
global _extension_path
global clear_dirty_task
_extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
_clear_dirty_task = None
register_template("empty", self.new_stage_empty, 0)
omni.kit.stage_templates.templates.load_templates()
self.load_user_templates()
# as omni.kit.stage_templates loads before the UI, it cannot depend on omni.kit.window.preferences or other extensions.
self._preferences_page = None
self._menu_button1 = None
self._menu_button2 = None
self._hooks = []
manager = omni.kit.app.get_app().get_extension_manager()
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_page(),
on_disable_fn=lambda _: self._unregister_page(),
ext_name="omni.kit.window.preferences",
hook_name="omni.kit.stage_templates omni.kit.window.preferences listener",
)
)
self._stage_template_menu = None
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_menu(),
on_disable_fn=lambda _: self._unregister_menu(),
ext_name="omni.kit.menu.utils",
hook_name="omni.kit.stage_templates omni.kit.menu.utils listener",
)
)
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_property_menu(),
on_disable_fn=lambda _: self._unregister_property_menu(),
ext_name="omni.kit.property.usd",
hook_name="omni.kit.stage_templates omni.kit.property.usd listener",
)
)
global _extension_instance
_extension_instance = self
def on_shutdown(self):
global _extension_instance
global _template_list
global _clear_dirty_task
if _clear_dirty_task:
_clear_dirty_task.cancel()
_clear_dirty_task = None
unregister_template("empty")
self._unregister_page()
self._unregister_menu()
self._unregister_property_menu()
self._hooks = None
_extension_instance = None
_template_list = None
for user_template in self._user_scripts:
del user_template
omni.kit.stage_templates.templates.unload_templates()
self._user_scripts = None
def _register_page(self):
try:
from omni.kit.window.preferences import register_page
from .stage_templates_page import StageTemplatesPreferences
self._preferences_page = register_page(StageTemplatesPreferences())
except ModuleNotFoundError:
pass
def _unregister_page(self):
if self._preferences_page:
try:
import omni.kit.window.preferences
omni.kit.window.preferences.unregister_page(self._preferences_page)
self._preferences_page = None
except ModuleNotFoundError:
pass
def _register_menu(self):
try:
from .stage_templates_menu import StageTemplateMenu
self._stage_template_menu = StageTemplateMenu()
self._stage_template_menu.on_startup()
except ModuleNotFoundError:
pass
def _unregister_menu(self):
if self._stage_template_menu:
try:
self._stage_template_menu.on_shutdown()
self._stage_template_menu = None
except ModuleNotFoundError:
pass
def _has_axis(self, objects, axis):
if not "stage" in objects:
return False
stage = objects["stage"]
if stage:
return UsdGeom.GetStageUpAxis(stage) != axis
else:
carb.log_error("_click_set_up_axis stage not found")
return False
def _click_set_up_axis(self, payload, axis):
stage = payload.get_stage()
if stage:
rootLayer = stage.GetRootLayer()
if rootLayer:
rootLayer.SetPermissionToEdit(True)
with Usd.EditContext(stage, rootLayer):
UsdGeom.SetStageUpAxis(stage, axis)
from omni.kit.property.usd import PrimPathWidget
PrimPathWidget.rebuild()
else:
carb.log_error("_click_set_up_axis rootLayer not found")
else:
carb.log_error("_click_set_up_axis stage not found")
def _register_property_menu(self):
# +add menu item(s)
from omni.kit.property.usd import PrimPathWidget
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
self._menu_button1 = None
self._menu_button2 = None
carb.log_error("context_menu is disabled!")
return None
self._menu_button1 = PrimPathWidget.add_button_menu_entry(
"Stage/Set up axis +Y",
show_fn=partial(self._has_axis, axis=UsdGeom.Tokens.y),
onclick_fn=partial(self._click_set_up_axis, axis=UsdGeom.Tokens.y),
add_to_context_menu=False,
)
self._menu_button2 = PrimPathWidget.add_button_menu_entry(
"Stage/Set up axis +Z",
show_fn=partial(self._has_axis, axis=UsdGeom.Tokens.z),
onclick_fn=partial(self._click_set_up_axis, axis=UsdGeom.Tokens.z),
add_to_context_menu=False,
)
def _unregister_property_menu(self):
if self._menu_button1 or self._menu_button2:
try:
from omni.kit.property.usd import PrimPathWidget
if self._menu_button1:
PrimPathWidget.remove_button_menu_entry(self._menu_button1)
self._menu_button1 = None
if self._menu_button2:
PrimPathWidget.remove_button_menu_entry(self._menu_button2)
self._menu_button2 = None
except ModuleNotFoundError:
pass
def new_stage_empty(self, rootname):
pass
def load_user_templates(self):
settings = carb.settings.get_settings()
template_paths = settings.get("/persistent/app/newStage/templatePath")
# Create template directories
original_umask = os.umask(0)
for path in template_paths:
path = carb.tokens.get_tokens_interface().resolve(path)
if not os.path.isdir(path):
try:
os.makedirs(path)
except Exception:
carb.log_error(f"Failed to create directory {path}")
os.umask(original_umask)
# Load template scripts
self._user_scripts = []
for path in template_paths:
for full_path in glob.glob(f"{path}/*.py"):
try:
with open(os.path.normpath(full_path)) as f:
user_script = f.read()
carb.log_verbose(f"loaded new_stage template {full_path}")
exec(user_script)
self._user_scripts.append(user_script)
except Exception as e:
carb.log_error(f"error loading {full_path}: {e}")
def register_template(name, new_stage_fn, group=0, rebuild=True):
"""Register new_stage Template
Args:
param1 (str): template name
param2 (callable): function to create template
param3 (int): group number. User by menu to split into groups with seperators
Returns:
bool: True for success, False when template already exists.
"""
# check if element exists
global _template_list
exists = get_stage_template(name)
if exists:
carb.log_warn(f"template {name} already exists")
return False
try:
exists = _template_list[group]
except IndexError:
_template_list.insert(group, {})
_template_list[group][name] = (name, new_stage_fn)
omni.kit.actions.core.get_action_registry().register_action(
"omni.kit.stage.templates",
f"create_new_stage_{get_action_name(name)}",
lambda t=name: omni.kit.window.file.new(t),
display_name=f"Create New Stage {name}",
description=f"Create New Stage {name}",
tag="Create Stage Template",
)
if rebuild:
rebuild_stage_template_menu()
return True
def unregister_template(name, rebuild: bool=True):
"""Remove registered new_stage Template
Args:
param1 (str): template name
Returns:
nothing
"""
global _template_list
if _template_list is not None:
for templates in _template_list:
if name in templates:
del templates[name]
if rebuild:
rebuild_stage_template_menu()
omni.kit.actions.core.get_action_registry().deregister_action("omni.kit.stage.templates", f"create_new_stage_{get_action_name(name)}")
def rebuild_stage_template_menu() -> None:
if _extension_instance and _extension_instance._stage_template_menu:
_extension_instance._stage_template_menu._rebuild_sub_menu()
def get_stage_template_list():
"""Get list of loaded new_stage templates
Args:
none
Returns:
list: list of groups of new_stage template names & create function pointers
"""
global _template_list
if not _template_list or len(_template_list) == 0:
return None
return _template_list
def get_stage_template(name):
"""Get named new_stage template & create function pointer
Args:
param1 (str): template name
Returns:
tuple: new_stage template name & create function pointer
"""
global _template_list
if not _template_list:
return None
for templates in _template_list:
if name in templates:
return templates[name]
return None
def get_default_template():
"""Get name of default new_stage template. Used when new_stage is called without template name specified
Args:
param1 (str): template name
Returns:
str: new_stage template name
"""
settings = carb.settings.get_settings()
return settings.get("/persistent/app/newStage/defaultTemplate")
def new_stage_finalize(create_result, error_message, usd_context, template=None, on_new_stage_fn=None):
global _clear_dirty_task
if _clear_dirty_task:
_clear_dirty_task.cancel()
_clear_dirty_task = None
if create_result:
stage = usd_context.get_stage()
# already finilized
if stage.HasDefaultPrim():
return
with Usd.EditContext(stage, stage.GetRootLayer()):
settings = carb.settings.get_settings()
default_prim_name = settings.get("/persistent/app/stage/defaultPrimName")
up_axis = settings.get("/persistent/app/stage/upAxis")
time_codes_per_second = settings.get_as_float("/persistent/app/stage/timeCodesPerSecond")
time_code_range = settings.get("/persistent/app/stage/timeCodeRange")
if time_code_range is None:
time_code_range = [0, 100]
rootname = f"/{default_prim_name}"
# Set up axis
if up_axis == "Y" or up_axis == "y":
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
else:
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
# Set timecodes per second
stage.SetTimeCodesPerSecond(time_codes_per_second)
# Start and end time code
if time_code_range:
stage.SetStartTimeCode(time_code_range[0])
stage.SetEndTimeCode(time_code_range[1])
# Create defaultPrim
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path(rootname)).GetPrim()
if not default_prim:
carb.log_error("Failed to create defaultPrim at {rootname}")
return
stage.SetDefaultPrim(default_prim)
if template is None:
template = get_default_template()
# Run script
item = get_stage_template(template)
if item and item[1]:
try:
create_fn = item[1]
sig = signature(create_fn)
if len(sig.parameters) == 1:
create_fn(rootname)
elif len(sig.parameters) == 2:
create_fn(rootname, usd_context.get_name())
else:
carb.log_error(f"template {template} has incorrect parameter count")
except Exception as error:
carb.log_error(f"exception in {template} {error}")
omni.kit.undo.clear_stack()
usd_context.set_pending_edit(False)
# Clear the stage dirty state again, as bound materials can set it
async def clear_dirty(usd_context):
import omni.kit.app
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
usd_context.set_pending_edit(False)
_clear_dirty_task = None
if on_new_stage_fn:
on_new_stage_fn(create_result, error_message)
_clear_dirty_task = asyncio.ensure_future(clear_dirty(usd_context))
def new_stage(on_new_stage_fn=None, template="empty", usd_context=None):
"""Execute new_stage
Args:
param2 (str): template name, if not specified default name is used
param3 (omni.usd.UsdContext): usd_context, the usd_context to create new stage
Returns:
nothing
"""
if usd_context is None:
usd_context = omni.usd.get_context()
if on_new_stage_fn is not None:
carb.log_warn(
"omni.kit.stage_templates.new_stage(callback, ...) is deprecated. \
Use `omni.kit.stage_templates.new_stage_with_callback` instead."
)
new_stage_with_callback(on_new_stage_fn, template, usd_context)
else:
new_stage_finalize(usd_context.new_stage(), "", usd_context, template=template, on_new_stage_fn=None)
def new_stage_with_callback(on_new_stage_fn=None, template="empty", usd_context=None):
"""Execute new_stage
Args:
param1 (callable): callback when new_stage is created
param2 (str): template name, if not specified default name is used
param3 (omni.usd.UsdContext): usd_context, the usd_context to create new stage
Returns:
nothing
"""
if usd_context is None:
usd_context = omni.usd.get_context()
usd_context.new_stage_with_callback(
partial(new_stage_finalize, usd_context=usd_context, template=template, on_new_stage_fn=on_new_stage_fn)
)
async def new_stage_async(template="empty", usd_context=None):
"""Execute new_stage asynchronously
Args:
param1 (str): template name, if not specified default name is used
param2 (omni.usd.UsdContext): usd_context, the usd_context to create new stage
Returns:
awaitable object until stage is created
"""
if usd_context is None:
usd_context = omni.usd.get_context()
f = asyncio.Future()
def on_new_stage(result, err_msg):
if not f.done():
f.set_result((result, err_msg))
new_stage_with_callback(on_new_stage, template, usd_context)
return await f
def get_extension_path(sub_directory):
global _extension_path
path = _extension_path
if sub_directory:
path = os.path.normpath(os.path.join(path, sub_directory))
return path
def set_transform_helper(
prim_path,
translate=Gf.Vec3d(0, 0, 0),
euler=Gf.Vec3d(0, 0, 0),
scale=Gf.Vec3d(1, 1, 1),
):
rotation = (
Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2])
* Gf.Rotation(Gf.Vec3d.YAxis(), euler[1])
* Gf.Rotation(Gf.Vec3d.XAxis(), euler[0])
)
xform = Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate)
omni.kit.commands.execute(
"TransformPrim",
path=prim_path,
new_transform_matrix=xform,
)
| 17,039 | Python | 31.706334 | 138 | 0.601326 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/templates/default_stage.py | import carb
import omni.ext
import omni.kit.commands
from pxr import UsdLux, UsdShade, Kind, Vt, Gf, UsdGeom, Sdf
from ..new_stage import *
class DefaultStage:
def __init__(self):
register_template("default stage", self.new_stage)
def __del__(self):
unregister_template("default stage")
def new_stage(self, rootname, usd_context_name):
# S3 URL's
carlight_hdr = Sdf.AssetPath("https://omniverse-content-production.s3.us-west-2.amazonaws.com/Assets/Scenes/Templates/Default/SubUSDs/textures/CarLight_512x256.hdr")
grid_basecolor = Sdf.AssetPath("https://omniverse-content-production.s3.us-west-2.amazonaws.com/Assets/Scenes/Templates/Default/SubUSDs/textures/ov_uv_grids_basecolor_1024.png")
# change ambientLightColor
carb.settings.get_settings().set("/rtx/sceneDb/ambientLightColor", (0, 0, 0))
carb.settings.get_settings().set("/rtx/indirectDiffuse/enabled", True)
carb.settings.get_settings().set("/rtx/domeLight/upperLowerStrategy", 0)
carb.settings.get_settings().set("/rtx/post/lensFlares/flareScale", 0.075)
carb.settings.get_settings().set("/rtx/sceneDb/ambientLightIntensity", 0)
# get up axis
usd_context = omni.usd.get_context(usd_context_name)
stage = usd_context.get_stage()
up_axis = UsdGeom.GetStageUpAxis(stage)
with Usd.EditContext(stage, stage.GetRootLayer()):
# create Environment
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment",
prim_type="Xform",
select_new_prim=False,
create_default_xform=True,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath("/Environment")
prim.CreateAttribute("ground:size", Sdf.ValueTypeNames.Int, False).Set(1400)
prim.CreateAttribute("ground:type", Sdf.ValueTypeNames.String, False).Set("On")
# create Sky
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment/Sky",
prim_type="DomeLight",
select_new_prim=False,
attributes={
UsdLux.Tokens.inputsIntensity: 1,
UsdLux.Tokens.inputsColorTemperature: 6250,
UsdLux.Tokens.inputsEnableColorTemperature: True,
UsdLux.Tokens.inputsExposure: 9,
UsdLux.Tokens.inputsTextureFile: carlight_hdr,
UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong,
UsdGeom.Tokens.visibility: "inherited",
} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \
{
UsdLux.Tokens.intensity: 1,
UsdLux.Tokens.colorTemperature: 6250,
UsdLux.Tokens.enableColorTemperature: True,
UsdLux.Tokens.exposure: 9,
UsdLux.Tokens.textureFile: carlight_hdr,
UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong,
UsdGeom.Tokens.visibility: "inherited",
},
create_default_xform=True,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath("/Environment/Sky")
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1))
if up_axis == "Y":
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 305, 0))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, -90, -90))
else:
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 305))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
# create DistantLight
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment/DistantLight",
prim_type="DistantLight",
select_new_prim=False,
attributes={UsdLux.Tokens.inputsAngle: 2.5,
UsdLux.Tokens.inputsIntensity: 1,
UsdLux.Tokens.inputsColorTemperature: 7250,
UsdLux.Tokens.inputsEnableColorTemperature: True,
UsdLux.Tokens.inputsExposure: 10,
UsdGeom.Tokens.visibility: "inherited",
} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \
{
UsdLux.Tokens.angle: 2.5,
UsdLux.Tokens.intensity: 1,
UsdLux.Tokens.colorTemperature: 7250,
UsdLux.Tokens.enableColorTemperature: True,
UsdLux.Tokens.exposure: 10,
UsdGeom.Tokens.visibility: "inherited",
},
create_default_xform=True,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath("/Environment/DistantLight")
if up_axis == "Y":
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 305, 0))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(-105, 0, 0))
else:
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 305))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(-15, 0, 0))
prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
# Material "Grid"
mtl_path = omni.usd.get_stage_next_free_path(stage, "/Environment/Looks/Grid", False)
omni.kit.commands.execute("CreateMdlMaterialPrim", mtl_url="OmniPBR.mdl", mtl_name="Grid", mtl_path=mtl_path, context_name=usd_context_name)
mat_prim = stage.GetPrimAtPath(mtl_path)
shader = UsdShade.Material(mat_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
# set inputs
omni.usd.create_material_input(mat_prim, "albedo_add", 0, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "albedo_brightness", 0.52, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "albedo_desaturation", 1, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "project_uvw", False, Sdf.ValueTypeNames.Bool)
omni.usd.create_material_input(mat_prim, "reflection_roughness_constant", 0.333, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "diffuse_texture", grid_basecolor, Sdf.ValueTypeNames.Asset, def_value=Sdf.AssetPath(""), color_space="sRGB")
omni.usd.create_material_input(mat_prim, "texture_rotate", 0, Sdf.ValueTypeNames.Float, def_value=Vt.Float(0.0))
omni.usd.create_material_input(mat_prim, "texture_scale", Gf.Vec2f(0.5, 0.5), Sdf.ValueTypeNames.Float2, def_value=Gf.Vec2f(1, 1))
omni.usd.create_material_input(mat_prim, "texture_translate", Gf.Vec2f(0, 0), Sdf.ValueTypeNames.Float2, def_value=Gf.Vec2f(0, 0))
omni.usd.create_material_input(mat_prim, "world_or_object", False, Sdf.ValueTypeNames.Bool, def_value=Vt.Bool(False))
# Ground
ground_path = "/Environment/ground"
omni.kit.commands.execute(
"CreateMeshPrimWithDefaultXform",
prim_path=ground_path,
prim_type="Plane",
select_new_prim=False,
prepend_default_prim=False,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath(ground_path)
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1))
prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
if up_axis == "Y":
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, -90, -90))
else:
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
mesh = UsdGeom.Mesh(prim)
mesh.CreateSubdivisionSchemeAttr("none")
mesh.GetFaceVertexCountsAttr().Set([4])
mesh.GetFaceVertexIndicesAttr().Set([0, 1, 3, 2])
mesh.GetPointsAttr().Set(Vt.Vec3fArray([(-50, -50, 0), (50, -50, 0), (-50, 50, 0), (50, 50, 0)]))
mesh.GetNormalsAttr().Set(Vt.Vec3fArray([(0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1)]))
mesh.SetNormalsInterpolation("faceVarying")
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
primvar = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
primvar.Set(Vt.Vec2fArray([(0, 0), (1, 0), (1, 1), (0, 1)]))
# Create a ground plane collider
# NOTE: replace with USD plane prim after the next USD update
try:
from pxr import UsdPhysics
colPlanePath = "/Environment/groundCollider"
planeGeom = UsdGeom.Plane.Define(stage, colPlanePath)
planeGeom.CreatePurposeAttr().Set("guide")
planeGeom.CreateAxisAttr().Set(up_axis)
colPlanePrim = stage.GetPrimAtPath(colPlanePath)
UsdPhysics.CollisionAPI.Apply(colPlanePrim)
except ImportError:
carb.log_warn("Failed to create a ground plane collider. Please load the omni.physx.bundle extension and create a new stage from this template if you need it.")
# bind "Grid" to "Ground"
omni.kit.commands.execute("BindMaterialCommand", prim_path=ground_path, material_path=mtl_path, strength=None, context_name=usd_context_name)
# update extent
attr = prim.GetAttribute(UsdGeom.Tokens.extent)
if attr:
bounds = UsdGeom.Boundable.ComputeExtentFromPlugins(UsdGeom.Boundable(prim), Usd.TimeCode.Default())
if bounds:
attr.Set(bounds)
| 11,151 | Python | 57.694737 | 185 | 0.59896 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/templates/sunlight.py | import carb
import omni.ext
import omni.kit.commands
from pxr import UsdLux
from ..new_stage import *
class SunlightStage:
def __init__(self):
register_template("sunlight", self.new_stage)
def __del__(self):
unregister_template("sunlight")
def new_stage(self, rootname, usd_context_name):
# Create basic DistantLight
usd_context = omni.usd.get_context(usd_context_name)
stage = usd_context.get_stage()
with Usd.EditContext(stage, stage.GetRootLayer()):
# create Environment
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment",
prim_type="Xform",
select_new_prim=False,
create_default_xform=True,
context_name=usd_context_name
)
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment/defaultLight",
prim_type="DistantLight",
select_new_prim=False,
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
attributes={UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsIntensity: 3000} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \
{UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000},
create_default_xform=True,
context_name=usd_context_name
)
| 1,486 | Python | 35.268292 | 148 | 0.588156 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/templates/__init__.py | from .sunlight import SunlightStage
from .default_stage import DefaultStage
new_stage_template_list = None
def load_templates():
global new_stage_template_list
new_stage_template_list = [SunlightStage(), DefaultStage()]
def unload_templates():
global new_stage_template_list
new_stage_template_list = None
| 327 | Python | 20.866665 | 63 | 0.746177 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_new_stage_menu.py | import omni.kit.test
import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
class TestMenuFile(omni.kit.test.AsyncTestCase):
async def setUp(self):
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file")
async def tearDown(self):
pass
def _on_stage_event(self, event):
if self._future_test and int(self._required_stage_event) == int(event.type):
self._future_test.set_result(event.type)
async def reset_stage_event(self, stage_event):
self._required_stage_event = stage_event
self._future_test = asyncio.Future()
async def wait_for_stage_event(self):
async def wait_for_event():
await self._future_test
try:
await asyncio.wait_for(wait_for_event(), timeout=30.0)
except asyncio.TimeoutError:
carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}")
self._future_test = None
self._required_stage_event = -1
async def test_file_new_from_stage_template_empty(self):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await self.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select empty and wait for stage open
await menu_widget.find_menu("Empty").click()
await self.wait_for_stage_event()
# verify Empty stage
stage = omni.usd.get_context().get_stage()
self.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World'])
async def test_file_new_from_stage_template_sunlight(self):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await self.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select Sunlight and wait for stage open
await menu_widget.find_menu("Sunlight").click()
await self.wait_for_stage_event()
# verify Sunlight stage
stage = omni.usd.get_context().get_stage()
self.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight'])
| 3,227 | Python | 38.851851 | 155 | 0.657577 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/__init__.py | from .test_commands import *
from .test_new_stage import *
from .test_new_stage_menu import *
from .test_templates import *
from .test_preferences import *
| 156 | Python | 25.166662 | 34 | 0.75641 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_new_stage.py | import unittest
import carb.settings
import omni.kit.app
import omni.kit.test
import omni.kit.stage_templates
from pxr import UsdGeom
class TestNewStage(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._staged_called = 0
self._stage_name = "$$_test_stage_$$"
async def tearDown(self):
pass
def new_stage_test(self, rootname):
self._staged_called += 1
async def test_dirty_status_after_new_stage(self):
await omni.kit.stage_templates.new_stage_async(template="sunflowers")
self.assertFalse(omni.usd.get_context().has_pending_edit())
# Puts some delay to make sure no pending events to handle.
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertFalse(omni.usd.get_context().has_pending_edit())
async def test_command_new_stage(self):
# check template already exists
item = omni.kit.stage_templates.get_stage_template(self._stage_name)
self.assertTrue(item == None)
# add new template
omni.kit.stage_templates.register_template(self._stage_name, self.new_stage_test, 0)
# check new template exists
item = omni.kit.stage_templates.get_stage_template(self._stage_name)
self.assertTrue(item != None)
self.assertTrue(item[0] == self._stage_name)
self.assertTrue(item[1] == self.new_stage_test)
# run template & check was called once
await omni.kit.stage_templates.new_stage_async(self._stage_name)
self.assertTrue(self._staged_called == 1)
stage = omni.usd.get_context().get_stage()
settings = carb.settings.get_settings()
default_prim_name = settings.get("/persistent/app/stage/defaultPrimName")
rootname = f"/{default_prim_name}"
# create cube
cube_path = omni.usd.get_stage_next_free_path(stage, "{}/Cube".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim",
prim_path=cube_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
prim = stage.GetPrimAtPath(cube_path)
self.assertTrue(prim, "Cube Prim exists")
# create sphere
sphere_path = omni.usd.get_stage_next_free_path(stage, "{}/Sphere".format(rootname), False)
omni.kit.commands.execute("CreatePrim", prim_path=sphere_path, prim_type="Sphere", select_new_prim=False)
prim = stage.GetPrimAtPath(sphere_path)
self.assertTrue(prim, "Sphere Prim exists")
# delete template
omni.kit.stage_templates.unregister_template(self._stage_name)
item = omni.kit.stage_templates.get_stage_template(self._stage_name)
self.assertTrue(item == None)
| 2,881 | Python | 38.479452 | 113 | 0.646303 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_preferences.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 carb
import omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
# duplicate of kit\source\extensions\omni.kit.window.preferences\python\omni\kit\window\preferences\tests\test_pages.py
# added here for coverage
class PreferencesTestPages(AsyncTestCase):
# Before running each test
async def setUp(self):
omni.kit.window.preferences.show_preferences_window()
async def test_show_pages(self):
pages = omni.kit.window.preferences.get_page_list()
page_names = [page._title for page in pages]
# is list alpha sorted. Don't compare with fixed list as members can change
self.assertEqual(page_names, sorted(page_names))
for page in pages:
omni.kit.window.preferences.select_page(page)
await ui_test.human_delay(50)
| 1,319 | Python | 40.249999 | 119 | 0.745262 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_templates.py | import asyncio
import unittest
import carb.settings
import omni.kit.app
import omni.kit.test
import omni.kit.stage_templates
# also see kit\source\extensions\omni.kit.menu.file\python\omni\kit\menu\file\tests\test_func_templates.py as simular test
# added here for coverage
class TestNewStageTemplates(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_stage_template_empty(self):
await omni.kit.stage_templates.new_stage_async(template="empty")
# verify Empty stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World'])
async def test_stage_template_sunlight(self):
await omni.kit.stage_templates.new_stage_async(template="sunlight")
# verify Sunlight stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight'])
async def test_stage_template_default_stage(self):
await omni.kit.stage_templates.new_stage_async(template="default stage")
# verify Default stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(set(prim_list) == set([
'/World', '/Environment', '/Environment/Sky',
'/Environment/DistantLight', '/Environment/Looks',
'/Environment/Looks/Grid', '/Environment/Looks/Grid/Shader',
'/Environment/ground', '/Environment/groundCollider']), prim_list)
async def test_stage_template_noname(self):
await omni.kit.stage_templates.new_stage_async()
# verify Empty stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World'])
| 2,077 | Python | 36.781818 | 122 | 0.666346 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/__init__.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
"""
InspectorWidget
------
InspectorWidget provides a way to display Widget Internals
:class:`.InspectorWidget`
"""
# Import the ICef bindings right away
from ._inspector_widget import *
from .scripts.extension import *
| 664 | Python | 30.666665 | 77 | 0.778614 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/scripts/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
import omni.ui
import omni.kit.app
import omni.kit.widget.inspector
class InspectorWidgetExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
pass
def on_startup(self, ext_id):
pass
# extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
# omni.kit.widget.inspector.startup(extension_path)
def on_shutdown(self):
pass
# omni.kit.widget.inspector.shutdown()
| 939 | Python | 31.413792 | 100 | 0.724175 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/tests/test_widget.py | import omni.kit.test
from omni.kit.widget.inspector import PreviewMode, InspectorWidget
import functools
class TestInspectorWidget(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._widget = InspectorWidget()
def test_widget_init(self):
self.assertTrue(self._widget)
def test_widget_get_set_widget(self):
widget = self._widget.widget
self.assertEqual(widget, None) # Check default
label = omni.ui.Label("Blah")
self._widget.widget = label
self.assertEqual(self._widget.widget, label)
def test_widget_get_set_preview(self):
preview_mode = self._widget.preview_mode
self.assertEqual(preview_mode, PreviewMode.WIREFRAME_AND_COLOR) # Check default
self._widget.preview_mode = PreviewMode.WIRE_ONLY
self.assertEqual(self._widget.preview_mode, PreviewMode.WIRE_ONLY)
def test_widget_get_set_selected_widget(self):
self.assertEqual(self._widget.selected_widget, None) # Check default
label = omni.ui.Label("Blah")
self._widget.selected_widget = label
self.assertEqual(self._widget.selected_widget, label)
def test_widget_get_set_start_depth(self):
start_depth = self._widget.start_depth
self.assertEqual(start_depth, 0) # Check default
self._widget.start_depth = 25
self.assertEqual(self._widget.start_depth, 25)
def test_widget_get_set_end_depth(self):
end_depth = self._widget.end_depth
self.assertEqual(end_depth, 65535) # Check default
self._widget.end_depth = 25
self.assertEqual(self._widget.end_depth, 25)
def test_widget_set_widget_changed_fn(self):
def selection_changed(the_list, widget):
the_list.append(widget)
the_list = []
self._widget.set_selected_widget_changed_fn(functools.partial(selection_changed, the_list))
label = omni.ui.Label("Blah")
self.assertTrue(len(the_list) == 0)
self._widget.selected_widget = label
self.assertTrue(len(the_list) == 1)
self.assertEqual(the_list[0], label)
def test_widget_set_preview_mode_changed_fn(self):
def preview_mode_value_changed(the_list, value):
the_list.append(value)
the_list = []
self._widget.set_preview_mode_change_fn(functools.partial(preview_mode_value_changed, the_list))
self.assertTrue(len(the_list) == 0)
self._widget.preview_mode = PreviewMode.WIRE_ONLY
self.assertTrue(len(the_list) == 1)
self.assertTrue(the_list[0] == PreviewMode.WIRE_ONLY)
| 2,603 | Python | 34.671232 | 104 | 0.659624 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/tests/__init__.py | from .test_widget import *
| 27 | Python | 12.999994 | 26 | 0.740741 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_model_base.py | # Copyright (c) 2020-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 typing import List
import carb
import copy
import carb.profiler
import omni.kit.commands
import omni.kit.undo
import omni.timeline
import omni.usd
import omni.kit.notification_manager as nm
from omni.kit.usd.layers import get_layers, LayerEventType, get_layer_event_payload
from pxr import Ar, Gf, Sdf, Tf, Trace, Usd, UsdShade
from .control_state_manager import ControlStateManager
from .placeholder_attribute import PlaceholderAttribute
class UsdBase:
def __init__(
self,
stage: Usd.Stage,
object_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict = {},
change_on_edit_end: bool = False,
treat_array_entry_as_comp: bool = False,
**kwargs,
):
self._control_state_mgr = ControlStateManager.get_instance()
self._stage = stage
self._usd_context = None
self._object_paths = object_paths
self._object_paths_set = set(object_paths)
self._metadata = metadata
self._change_on_edit_end = change_on_edit_end
# Whether each array entry should be treated as a comp, if this property is of an array type.
# If set to True, each array entry will have ambiguous and different from default state checked. It may have
# huge perf impact if the array size is big.
# It is useful if you need to build each array entry as a single widget with mixed/non-default indicator
# an example would SdfAssetPathAttributeModel and _sdf_asset_path_array_builder
self._treat_array_entry_as_comp = treat_array_entry_as_comp
self._dirty = True
self._value = None # The value to be displayed on widget
self._has_default_value = False
self._default_value = None
self._real_values = [] # The actual values in usd, might be different from self._value if ambiguous.
self._connections = []
self._is_big_array = False
self._prev_value = None
self._prev_real_values = []
self._editing = 0
self._ignore_notice = False
self._ambiguous = False
# "comp" is the first dimension of an array (when treat_array_entry_as_comp is enabled) or vector attribute.
# - If attribute is non-array vector type, comp indexes into the vector itself. e.g. for vec3 type, comp=1 means
# the 2nd channel of the vector vec3[1].
# - If attribute is an array type:
# - When treat_array_entry_as_comp is enabled) is enabled:
# - If the attribute is an array of scalar (i.e. float[]), `comp`` is the entry index. e.g. for
# SdfAssetArray type, comp=1 means the 2nd path in the path array.
# - If the attribute is an array of vector (i.e. vec3f[]), `comp` only indexes the array entry, it does
# not support indexing into the channel of the vector within the array entry. i.e a "2D" comp is not
# supported yet.
# - When treat_array_entry_as_comp is enabled) is disabled:
# - comp is 0 and the entire array is treated as one scalar value.
#
# This applies to all `comp` related functionality in this model base.
self._comp_ambiguous = []
self._might_be_time_varying = False # Inaccurate named. It really means if timesamples > 0
self._timeline = omni.timeline.get_timeline_interface()
self._current_time = self._timeline.get_current_time()
self._timeline_sub = None
self._on_set_default_fn = None
self._soft_range_min = None
self._soft_range_max = None
# get soft_range userdata settings
attributes = self._get_attributes()
if attributes:
attribute = attributes[-1]
if isinstance(attribute, Usd.Attribute):
soft_range = attribute.GetCustomDataByKey("omni:kit:property:usd:soft_range_ui")
if soft_range:
self._soft_range_min = soft_range[0]
self._soft_range_max = soft_range[1]
# Hard range for the value. For vector type, range value is a float/int that compares against each component individually
self._min = kwargs.get("min", None)
self._max = kwargs.get("max", None)
# Invalid range
if self._min is not None and self._max is not None and self._min >= self._max:
self._min = self._max = None
# The state of the icon on the right side of the line with widgets
self._control_state = 0
# Callback when the control state is changing. We use it to redraw UI
self._on_control_state_changed_fn = None
# Callback when the value is reset. We use it to redraw UI
self._on_set_default_fn = None
# True if the attribute has the default value and the current value is not default
self._different_from_default = False
# Per component different from default
self._comp_different_from_default = []
# Whether the UsdModel should self register Tf.Notice or let UsdPropertiesWidget inform a property change
if self_refresh:
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, self._stage)
else:
self._listener = None
# Notification handler to throttle notifications.
self._notification = None
usd_context = self._get_usd_context()
layers = get_layers(usd_context)
self._spec_locks_subscription = layers.get_event_stream().create_subscription_to_pop(
self._on_spec_locks_changed, name="Property USD"
)
@property
def control_state(self):
"""Returns the current control state, it's the icon on the right side of the line with widgets"""
return self._control_state
@property
def stage(self):
return self._stage
@property
def metadata(self):
return self._metadata
def update_control_state(self):
control_state, force_refresh = self._control_state_mgr.update_control_state(self)
# Redraw control state icon when the control state is changed
if self._control_state != control_state or force_refresh:
self._control_state = control_state
if self._on_control_state_changed_fn:
self._on_control_state_changed_fn()
def set_on_control_state_changed_fn(self, fn):
"""Callback that is called when control state is changed"""
self._on_control_state_changed_fn = fn
def set_on_set_default_fn(self, fn):
"""Callback that is called when value is reset"""
self._on_set_default_fn = fn
def clean(self):
self._notification = None
self._timeline_sub = None
self._stage = None
self._spec_locks_subscription = None
if self._listener:
self._listener.Revoke()
self._listener = None
def is_different_from_default(self) -> bool:
"""Returns True if the attribute has the default value and the current value is not default"""
self._update_value()
# soft_range has been overridden
if self._soft_range_min != None and self._soft_range_max != None:
return True
return self._different_from_default
def might_be_time_varying(self) -> bool:
self._update_value()
return self._might_be_time_varying
def is_ambiguous(self) -> bool:
self._update_value()
return self._ambiguous
def is_comp_ambiguous(self, index: int) -> bool:
self._update_value()
comp_len = len(self._comp_ambiguous)
if comp_len == 0 or index < 0:
return self.is_ambiguous()
if index < comp_len:
return self._comp_ambiguous[index]
return False
def is_array_type(self) -> bool:
return self._is_array_type()
def get_all_comp_ambiguous(self) -> List[bool]:
"""Empty array if attribute value is a scalar, check is_ambiguous instead"""
self._update_value()
return self._comp_ambiguous
def get_attribute_paths(self) -> List[Sdf.Path]:
return self._object_paths
def get_property_paths(self) -> List[Sdf.Path]:
return self.get_attribute_paths()
def get_connections(self):
return self._connections
def set_default(self, comp=-1):
"""Set the UsdAttribute default value if it exists in metadata"""
self.set_soft_range_userdata(None, None)
if self.is_different_from_default() is False or self._has_default_value is False:
if self._soft_range_min != None and self._soft_range_max != None:
if self._on_set_default_fn:
self._on_set_default_fn()
self.update_control_state()
return
current_time_code = self.get_current_time_code()
with omni.kit.undo.group():
# TODO clear timesample
# However, when a value is timesampled, the "default" button is overridden by timesampled button,
# so there's no way to invoke this function
for attribute in self._get_attributes():
if isinstance(attribute, Usd.Attribute):
current_value = attribute.Get(current_time_code)
if comp >= 0:
# OM-46294: Make a value copy to avoid changing with reference.
default_value = copy.copy(current_value)
default_value[comp] = self._default_value[comp]
else:
default_value = self._default_value
self._change_property(attribute.GetPath(), default_value, current_value)
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
self._different_from_default = False
self._comp_different_from_default.clear()
if self._on_set_default_fn:
self._on_set_default_fn()
def _create_placeholder_attributes(self, attributes):
# NOTE: PlaceholderAttribute.CreateAttribute cannot throw exceptions
for index, attribute in enumerate(attributes):
if isinstance(attribute, PlaceholderAttribute):
self._editing += 1
attributes[index] = attribute.CreateAttribute()
self._editing -= 1
def set_value(self, value, comp: int = -1):
if self._min is not None:
if hasattr(value, "__len__"):
for i in range(len(value)):
if value[i] < self._min:
value[i] = self._min
else:
if value < self._min:
value = self._min
if self._max is not None:
if hasattr(value, "__len__"):
for i in range(len(value)):
if value[i] > self._max:
value[i] = self._max
else:
if value > self._max:
value = self._max
if not self._ambiguous and not any(self._comp_ambiguous) and value == self._value:
return False
if self.is_instance_proxy():
self._post_notification("Cannot edit attributes of instance proxy.")
self._update_value(True) # reset value
return False
if self.is_locked():
self._post_notification("Cannot edit locked attributes.")
self._update_value(True) # reset value
return False
if self._might_be_time_varying:
self._post_notification("Setting time varying attribute is not supported yet")
return False
self._value = value if comp == -1 else UsdBase.update_value_by_comp(value, self._value, comp)
attributes = self._get_attributes()
if len(attributes) == 0:
return False
self._create_placeholder_attributes(attributes)
if self._editing:
for i, attribute in enumerate(attributes):
self._ignore_notice = True
if comp == -1:
self._real_values[i] = self._value
if not self._change_on_edit_end:
attribute.Set(self._value)
else:
# Only update a single component of the value (for vector type)
value = self._real_values[i]
self._real_values[i] = self._update_value_by_comp(value, comp)
if not self._change_on_edit_end:
attribute.Set(value)
self._ignore_notice = False
else:
with omni.kit.undo.group():
for i, attribute in enumerate(attributes):
self._ignore_notice = True
# begin_edit is not called for certain widget (like Checkbox), issue the command directly
if comp == -1:
self._change_property(attribute.GetPath(), self._value, None)
else:
# Only update a single component of the value (for vector type)
value = self._real_values[i]
self._real_values[i] = self._update_value_by_comp(value, comp)
self._change_property(attribute.GetPath(), value, None)
self._ignore_notice = False
if comp == -1:
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
else:
self._comp_ambiguous[comp] = False
self._ambiguous = any(self._comp_ambiguous)
if self._has_default_value:
self._comp_different_from_default = [False] * self._get_comp_num()
if comp == -1:
self._different_from_default = value != self._default_value
if self._different_from_default:
for comp in range(len(self._comp_different_from_default)):
self._comp_different_from_default[comp] = not self._compare_value_by_comp(
value, self._default_value, comp
)
else:
self._comp_different_from_default[comp] = not self._compare_value_by_comp(
value, self._default_value, comp
)
self._different_from_default = any(self._comp_different_from_default)
else:
self._different_from_default = False
self._comp_different_from_default.clear()
self.update_control_state()
return True
def _is_prev_same(self):
return self._prev_real_values == self._real_values
def begin_edit(self):
self._editing = self._editing + 1
self._prev_value = self._value
self._save_real_values_as_prev()
def end_edit(self):
self._editing = self._editing - 1
if self._is_prev_same():
return
attributes = self._get_attributes()
self._create_placeholder_attributes(attributes)
with omni.kit.undo.group():
self._ignore_notice = True
for i in range(len(attributes)):
attribute = attributes[i]
self._change_property(attribute.GetPath(), self._real_values[i], self._prev_real_values[i])
self._ignore_notice = False
# Set flags. It calls _on_control_state_changed_fn when the user finished editing
self._update_value(True)
def _post_notification(self, message):
if not self._notification or self._notification.dismissed:
status = nm.NotificationStatus.WARNING
self._notification = nm.post_notification(message, status=status)
carb.log_warn(message)
def _change_property(self, path: Sdf.Path, new_value, old_value):
# OM-75480: For props inside sesison layer, it will always change specs
# in the session layer to avoid shadowing. Why it needs to be def is that
# session layer is used for several runtime data for now as built-in cameras,
# MDL material params, and etc. Not all of them create runtime prims inside
# session layer. For those that are not defined inside session layer, we should
# avoid leaving delta inside other sublayers as they are shadowed and useless after
# stage close.
target_layer, _ = omni.usd.find_spec_on_session_or_its_sublayers(
self._stage, path.GetPrimPath(), lambda spec: spec.specifier == Sdf.SpecifierDef
)
if not target_layer:
target_layer = self._stage.GetEditTarget().GetLayer()
omni.kit.commands.execute(
"ChangeProperty", prop_path=path,
value=new_value, prev=old_value,
target_layer=target_layer,
usd_context_name=self._stage
)
def get_value_by_comp(self, comp: int):
self._update_value()
if comp == -1:
return self._value
return self._get_value_by_comp(self._value, comp)
def _save_real_values_as_prev(self):
# It's like copy.deepcopy but not all USD types support pickling (e.g. Gf.Quat*)
self._prev_real_values = [type(value)(value) for value in self._real_values]
def _get_value_by_comp(self, value, comp: int):
if value.__class__.__module__ == "pxr.Gf":
if value.__class__.__name__.startswith("Quat"):
if comp == 0:
return value.real
else:
return value.imaginary[comp - 1]
elif value.__class__.__name__.startswith("Matrix"):
dimension = len(value)
row = comp // dimension
col = comp % dimension
return value[row, col]
elif value.__class__.__name__.startswith("Vec"):
return value[comp]
else:
if comp < len(value):
return value[comp]
return None
def _update_value_by_comp(self, value, comp: int):
"""update value from self._value"""
return UsdBase.update_value_by_comp(self._value, value, comp)
@staticmethod
def update_value_by_comp(from_value, to_value, comp: int):
"""update value from from_value to to_value"""
if from_value.__class__.__module__ == "pxr.Gf":
if from_value.__class__.__name__.startswith("Quat"):
if comp == 0:
to_value.real = from_value.real
else:
imaginary = from_value.imaginary
imaginary[comp - 1] = from_value.imaginary[comp - 1]
to_value.SetImaginary(imaginary)
elif from_value.__class__.__name__.startswith("Matrix"):
dimension = len(from_value)
row = comp // dimension
col = comp % dimension
to_value[row, col] = from_value[row, col]
elif from_value.__class__.__name__.startswith("Vec"):
to_value[comp] = from_value[comp]
else:
to_value[comp] = from_value[comp]
return to_value
def _compare_value_by_comp(self, val1, val2, comp: int):
return self._get_value_by_comp(val1, comp) == self._get_value_by_comp(val2, comp)
def _get_comp_num(self):
# TODO any better wan than this??
# Checks if the value type is a vector type
if self._value.__class__.__module__ == "pxr.Gf":
if self._value.__class__.__name__.startswith("Quat"):
return 4
elif self._value.__class__.__name__.startswith("Matrix"):
mat_dimension = len(self._value)
return mat_dimension * mat_dimension
elif hasattr(self._value, "__len__"):
return len(self._value)
elif self._is_array_type() and self._treat_array_entry_as_comp:
return len(self._value)
return 0
@Trace.TraceFunction
def _on_usd_changed(self, notice, stage):
if stage != self._stage:
return
if self._editing > 0:
return
if self._ignore_notice:
return
for path in notice.GetResyncedPaths():
if path in self._object_paths_set:
self._set_dirty()
return
for path in notice.GetChangedInfoOnlyPaths():
if path in self._object_paths_set:
self._set_dirty()
return
def _on_dirty(self):
pass
def _set_dirty(self):
if self._editing > 0:
return
self._dirty = True
self._on_dirty()
def _get_type_name(self, obj=None):
if obj:
if hasattr(obj, "GetTypeName"):
return obj.GetTypeName()
elif hasattr(obj, "typeName"):
return obj.typeName
else:
return None
else:
type_name = self._metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")
return Sdf.ValueTypeNames.Find(type_name)
def _is_array_type(self, obj=None):
type_name = self._get_type_name(obj)
if isinstance(type_name, Sdf.ValueTypeName):
return type_name.isArray
else:
return False
def _get_obj_type_default_value(self, obj):
type_name = self._get_type_name(obj)
if isinstance(type_name, Sdf.ValueTypeName):
return type_name.defaultValue
else:
return None
def _update_value(self, force=False):
return self._update_value_objects(force, self._get_attributes())
def _update_value_objects(self, force: bool, objects: list):
if (self._dirty or force) and self._stage:
with Ar.ResolverContextBinder(self._stage.GetPathResolverContext()):
with Ar.ResolverScopedCache():
carb.profiler.begin(1, "UsdBase._update_value_objects")
current_time_code = self.get_current_time_code()
self._might_be_time_varying = False
self._value = None
self._has_default_value = False
self._default_value = None
self._real_values.clear()
self._connections.clear()
self._ambiguous = False
self._comp_ambiguous.clear()
self._different_from_default = False
self._comp_different_from_default.clear()
for index, object in enumerate(objects):
value = self._read_value(object, current_time_code)
self._real_values.append(value)
if isinstance(object, Usd.Attribute):
self._might_be_time_varying = self._might_be_time_varying or object.GetNumTimeSamples() > 0
self._connections.append(
[conn for conn in object.GetConnections()] if object.HasAuthoredConnections() else []
)
# only need to check the first prim. All other prims are supposedly to be the same
if index == 0:
self._value = value
if self._value and self._is_array_type(object) and len(self._value) > 16:
self._is_big_array = True
comp_num = self._get_comp_num()
self._comp_ambiguous = [False] * comp_num
self._comp_different_from_default = [False] * comp_num
# Loads the default value
self._has_default_value, self._default_value = self._get_default_value(object)
elif self._value != value:
self._value = value
self._ambiguous = True
comp_num = len(self._comp_ambiguous)
if comp_num > 0:
for i in range(comp_num):
if not self._comp_ambiguous[i]:
self._comp_ambiguous[i] = not self._compare_value_by_comp(
value, self._real_values[0], i
)
if self._has_default_value:
comp_num = len(self._comp_different_from_default)
if comp_num > 0:
for i in range(comp_num):
if not self._comp_different_from_default[i]:
self._comp_different_from_default[i] = not self._compare_value_by_comp(
value, self._default_value, i
)
self._different_from_default |= any(self._comp_different_from_default)
else:
self._different_from_default |= value != self._default_value
self._dirty = False
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self.update_control_state()
carb.profiler.end(1)
return True
return False
def _get_default_value(self, property):
default_values = {"xformOp:scale": (1.0, 1.0, 1.0), "visibleInPrimaryRay": True, "primvars:multimatte_id": -1}
if isinstance(property, Usd.Attribute):
prim = property.GetPrim()
if prim:
custom = property.GetCustomData()
if "default" in custom:
# This is not the standard USD way to get default.
return True, custom["default"]
elif "customData" in self._metadata:
# This is to fetch default value for custom property.
default_value = self._metadata["customData"].get("default", None)
if default_value:
return True, default_value
else:
prim_definition = prim.GetPrimDefinition()
prop_spec = prim_definition.GetSchemaPropertySpec(property.GetPath().name)
if prop_spec and prop_spec.default != None:
return True, prop_spec.default
if property.GetName() in default_values:
return True, default_values[property.GetName()]
# If we still don't find default value, use type's default value
value_type = property.GetTypeName()
default_value = value_type.defaultValue
return True, default_value
elif isinstance(property, PlaceholderAttribute):
return True, property.Get()
return False, None
def _get_attributes(self):
if not self._stage:
return []
attributes = []
if not self._stage:
return attributes
for path in self._object_paths:
prim = self._stage.GetPrimAtPath(path.GetPrimPath())
if prim:
attr = prim.GetAttribute(path.name)
if attr:
if not attr.IsHidden():
attributes.append(attr)
else:
attr = PlaceholderAttribute(name=path.name, prim=prim, metadata=self._metadata)
attributes.append(attr)
return attributes
def _get_objects(self):
objects = []
if not self._stage:
return objects
for path in self._object_paths:
obj = self._stage.GetObjectAtPath(path)
if obj and not obj.IsHidden():
objects.append(obj)
return objects
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED) or e.type == int(
omni.timeline.TimelineEventType.CURRENT_TIME_CHANGED
):
current_time = e.payload["currentTime"]
if current_time != self._current_time:
self._current_time = current_time
if self._might_be_time_varying:
self._set_dirty()
elif e.type == int(omni.timeline.TimelineEventType.TENTATIVE_TIME_CHANGED):
tentative_time = e.payload["tentativeTime"]
if tentative_time != self._current_time:
self._current_time = tentative_time
if self._might_be_time_varying:
self._set_dirty()
def _read_value(self, object: Usd.Object, time_code: Usd.TimeCode):
carb.profiler.begin(1, "UsdBase._read_value")
val = object.Get(time_code)
if val is None:
result, val = self._get_default_value(object)
if not result:
val = self._get_obj_type_default_value(object)
carb.profiler.end(1)
return val
def _on_spec_locks_changed(self, event: carb.events.IEvent):
payload = get_layer_event_payload(event)
if payload and payload.event_type == LayerEventType.SPECS_LOCKING_CHANGED:
self.update_control_state()
def _get_usd_context(self):
if not self._usd_context:
self._usd_context = omni.usd.get_context_from_stage(self._stage)
return self._usd_context
def set_locked(self, locked):
usd_context = self._get_usd_context()
if not usd_context:
carb.log_warn(f"Current stage is not attached to any usd context.")
return
if locked:
omni.kit.usd.layers.lock_specs(usd_context, self._object_paths, False)
else:
omni.kit.usd.layers.unlock_specs(usd_context, self._object_paths, False)
def is_instance_proxy(self):
if not self._object_paths:
return False
path = Sdf.Path(self._object_paths[0]).GetPrimPath()
prim = self._stage.GetPrimAtPath(path)
return prim and prim.IsInstanceProxy()
def is_locked(self):
usd_context = self._get_usd_context()
if not usd_context:
carb.log_warn(f"Current stage is not attached to any usd context.")
return
for path in self._object_paths:
if not omni.kit.usd.layers.is_spec_locked(usd_context, path):
return False
return True
def has_connections(self):
return bool(len(self._connections[-1]) > 0)
def get_value(self):
self._update_value()
return self._value
def get_current_time_code(self):
return Usd.TimeCode(omni.usd.get_frame_time_code(self._current_time, self._stage.GetTimeCodesPerSecond()))
def set_soft_range_userdata(self, soft_range_min, soft_range_max):
# set soft_range userdata settings
for attribute in self._get_attributes():
if isinstance(attribute, Usd.Attribute):
if soft_range_min == None and soft_range_max == None:
attribute.SetCustomDataByKey("omni:kit:property:usd:soft_range_ui", None)
else:
attribute.SetCustomDataByKey(
"omni:kit:property:usd:soft_range_ui", Gf.Vec2f(soft_range_min, soft_range_max)
)
self._soft_range_min = soft_range_min
self._soft_range_max = soft_range_max
| 32,333 | Python | 40.667526 | 129 | 0.561408 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/relationship.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 weakref
from functools import partial
from typing import Callable, List, Optional
import omni.kit.commands
import omni.ui as ui
from omni.kit.widget.stage import StageWidget
from pxr import Sdf
class SelectionWatch(object):
def __init__(self, stage, on_selection_changed_fn, filter_type_list, filter_lambda, tree_view=None):
self._stage = weakref.ref(stage)
self._last_selected_prim_paths = None
self._filter_type_list = filter_type_list
self._filter_lambda = filter_lambda
self._on_selection_changed_fn = on_selection_changed_fn
self._targets_limit = 0
if tree_view:
self.set_tree_view(tree_view)
def reset(self, targets_limit):
self._targets_limit = targets_limit
self.clear_selection()
def set_tree_view(self, tree_view):
self._tree_view = tree_view
self._tree_view.set_selection_changed_fn(self._on_widget_selection_changed)
self._last_selected_prim_paths = None
def clear_selection(self):
if not self._tree_view:
return
self._tree_view.model.update_dirty()
self._tree_view.selection = []
if self._on_selection_changed_fn:
self._on_selection_changed_fn([])
def _on_widget_selection_changed(self, selection):
stage = self._stage()
if not stage:
return
prim_paths = [str(item.path) for item in selection if item]
# Deselect instance proxy items if they were selected
selection = [item for item in selection if item and not item.instance_proxy]
# Although the stage view has filter, you can still select the ancestor of filtered prims, which might not match the type.
if len(self._filter_type_list) != 0:
filtered_selection = []
for item in selection:
prim = stage.GetPrimAtPath(item.path)
if prim:
for type in self._filter_type_list:
if prim.IsA(type):
filtered_selection.append(item)
break
if filtered_selection != selection:
selection = filtered_selection
# or the ancestor might not match the lambda filter
if self._filter_lambda is not None:
selection = [item for item in selection if self._filter_lambda(stage.GetPrimAtPath(item.path))]
# Deselect if over the limit
if self._targets_limit > 0 and len(selection) > self._targets_limit:
selection = selection[: self._targets_limit]
if self._tree_view.selection != selection:
self._tree_view.selection = selection
prim_paths = [str(item.path) for item in selection]
if prim_paths == self._last_selected_prim_paths:
return
self._last_selected_prim_paths = prim_paths
if self._on_selection_changed_fn:
self._on_selection_changed_fn(self._last_selected_prim_paths)
def enable_filtering_checking(self, enable: bool):
"""
It is used to prevent selecting the prims that are filtered out but
still displayed when such prims have filtered children. When `enable`
is True, SelectionWatch should consider filtering when changing Kit's
selection.
"""
pass
def set_filtering(self, filter_string: Optional[str]):
pass
class RelationshipTargetPicker:
def __init__(
self, stage, relationship_widget, filter_type_list, filter_lambda, on_add_targets: Optional[Callable] = None
):
self._weak_stage = weakref.ref(stage)
self._relationship_widget = relationship_widget
self._filter_lambda = filter_lambda
self._selected_paths = []
self._filter_type_list = filter_type_list
self._on_add_targets = on_add_targets
def on_window_visibility_changed(visible):
if not visible:
self._stage_widget.open_stage(None)
else:
# Only attach the stage when picker is open. Otherwise the Tf notice listener in StageWidget kills perf
self._stage_widget.open_stage(self._weak_stage())
self._window = ui.Window(
"Select Target(s)",
width=400,
height=400,
visible=False,
flags=0,
visibility_changed_fn=on_window_visibility_changed,
)
with self._window.frame:
with ui.VStack():
with ui.Frame():
self._stage_widget = StageWidget(None, columns_enabled=["Type"])
self._selection_watch = SelectionWatch(
stage=stage,
on_selection_changed_fn=self._on_selection_changed,
filter_type_list=filter_type_list,
filter_lambda=filter_lambda,
)
self._stage_widget.set_selection_watch(self._selection_watch)
def on_select(weak_self):
weak_self = weak_self()
if not weakref:
return
pending_add = []
for relationship in weak_self._relationship_widget._relationships:
if relationship:
existing_targets = relationship.GetTargets()
for selected_path in weak_self._selected_paths:
selected_path = Sdf.Path(selected_path)
if selected_path not in existing_targets:
pending_add.append((relationship, selected_path))
if len(pending_add):
omni.kit.undo.begin_group()
for add in pending_add:
omni.kit.commands.execute("AddRelationshipTarget", relationship=add[0], target=add[1])
omni.kit.undo.end_group()
if self._on_add_targets:
self._on_add_targets(pending_add)
weak_self._window.visible = False
with ui.VStack(
height=0, style={"Button.Label:disabled": {"color": 0xFF606060}}
): # TODO consolidate all styles
self._label = ui.Label("Selected Path(s):\n\tNone")
self._button = ui.Button(
"Add",
height=10,
clicked_fn=partial(on_select, weak_self=weakref.ref(self)),
enabled=False,
identifier="add_button"
)
def clean(self):
self._window.set_visibility_changed_fn(None)
self._window = None
self._selection_watch = None
self._stage_widget.open_stage(None)
self._stage_widget.destroy()
self._stage_widget = None
self._filter_type_list = None
self._filter_lambda = None
self._on_add_targets = None
def show(self, targets_limit):
self._targets_limit = targets_limit
self._selection_watch.reset(targets_limit)
self._window.visible = True
if self._filter_lambda is not None:
self._stage_widget._filter_by_lambda({"relpicker_filter": self._filter_lambda}, True)
if self._filter_type_list:
self._stage_widget._filter_by_type(self._filter_type_list, True)
self._stage_widget.update_filter_menu_state(self._filter_type_list)
def _on_selection_changed(self, paths):
self._selected_paths = paths
if self._button:
self._button.enabled = len(self._selected_paths) > 0
if self._label:
text = "\n\t".join(self._selected_paths)
label_text = "Selected Path(s)"
if self._targets_limit > 0:
label_text += f" ({len(self._selected_paths)}/{self._targets_limit})"
label_text += f":\n\t{text if len(text) else 'None'}"
self._label.text = label_text
class RelationshipEditWidget:
def __init__(self, stage, attr_name, prim_paths, additional_widget_kwargs=None):
self._id_name = f"{prim_paths[-1]}_{attr_name}".replace('/', '_')
self._relationships = [stage.GetPrimAtPath(path).GetRelationship(attr_name) for path in prim_paths]
self._additional_widget_kwargs = additional_widget_kwargs if additional_widget_kwargs else {}
self._targets_limit = self._additional_widget_kwargs.get("targets_limit", 0)
self._button = None
self._target_picker = RelationshipTargetPicker(
stage,
self,
self._additional_widget_kwargs.get("target_picker_filter_type_list", []),
self._additional_widget_kwargs.get("target_picker_filter_lambda", None),
self._additional_widget_kwargs.get("target_picker_on_add_targets", None),
)
self._frame = ui.Frame()
self._frame.set_build_fn(self._build)
self._on_remove_target = self._additional_widget_kwargs.get("on_remove_target", None)
self._enabled = self._additional_widget_kwargs.get("enabled", True)
self._shared_targets = None
def clean(self):
self._target_picker.clean()
self._target_picker = None
self._frame = None
self._button = None
self._label = None
self._on_remove_target = None
self._enabled = True
def is_ambiguous(self) -> bool:
return self._shared_targets is None
def get_all_comp_ambiguous(self) -> List[bool]:
return []
def get_relationship_paths(self) -> List[Sdf.Path]:
return [rel.GetPath() for rel in self._relationships]
def get_property_paths(self) -> List[Sdf.Path]:
return self.get_relationship_paths()
def get_targets(self) -> List[Sdf.Path]:
return self._shared_targets
def set_targets(self, targets: List[Sdf.Path]):
with omni.kit.undo.group():
for relationship in self._relationships:
if relationship:
omni.kit.commands.execute("SetRelationshipTargets", relationship=relationship, targets=targets)
def set_value(self, targets: List[Sdf.Path]):
self.set_targets(targets)
def _build(self):
self._shared_targets = None
for relationship in self._relationships:
targets = relationship.GetTargets()
if self._shared_targets is None:
self._shared_targets = targets
elif self._shared_targets != targets:
self._shared_targets = None
break
with ui.VStack(spacing=2):
if self._shared_targets is not None:
for target in self._shared_targets:
with ui.HStack(spacing=2):
ui.StringField(name="models", read_only=True).model.set_value(target.pathString)
def on_remove_target(weak_self, target):
weak_self = weak_self()
if weak_self:
with omni.kit.undo.group():
for relationship in weak_self._relationships:
if relationship:
omni.kit.commands.execute(
"RemoveRelationshipTarget", relationship=relationship, target=target
)
if self._on_remove_target:
self._on_remove_target(target)
ui.Button(
"-",
enabled=self._enabled,
width=ui.Pixel(14),
clicked_fn=partial(on_remove_target, weak_self=weakref.ref(self), target=target),
identifier=f"remove_relationship{target.pathString.replace('/', '_')}"
)
def on_add_target(weak_self):
weak_self = weak_self()
if weak_self:
weak_self._target_picker.show(weak_self._targets_limit - len(weak_self._shared_targets))
within_target_limit = self._targets_limit == 0 or len(self._shared_targets) < self._targets_limit
button = ui.Button(
"Add Target(s)",
width=ui.Pixel(30),
clicked_fn=partial(on_add_target, weak_self=weakref.ref(self)),
enabled=within_target_limit and self._enabled,
identifier=f"add_relationship{self._id_name}"
)
if not within_target_limit:
button.set_tooltip(
f"Targets limit of {self._targets_limit} has been reached. To add more target(s), remove current one(s) first."
)
else:
ui.StringField(name="models", read_only=True).model.set_value("Mixed")
def _set_dirty(self):
self._frame.rebuild()
| 13,672 | Python | 41.070769 | 135 | 0.559611 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_property_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import traceback
from collections import defaultdict
from typing import Any, DefaultDict, Dict, List, Sequence, Set, Tuple
import carb
import carb.events
import carb.profiler
import omni.kit.app
import omni.kit.context_menu
import omni.ui as ui
import omni.usd
from omni.kit.window.property.templates import SimplePropertyWidget, build_frame_header
from pxr import Sdf, Tf, Trace, Usd
from .usd_model_base import UsdBase
from .usd_property_widget_builder import *
from .message_bus_events import ADDITIONAL_CHANGED_PATH_EVENT_TYPE
# Clipboard to store copied group properties
__properties_to_copy: Dict[Sdf.Path, Any] = {}
def get_group_properties_clipboard():
return __properties_to_copy
def set_group_properties_clipboard(properties_to_copy: Dict[Sdf.Path, Any]):
global __properties_to_copy
__properties_to_copy = properties_to_copy
class UsdPropertyUiEntry:
def __init__(
self,
prop_name: str,
display_group: str,
metadata,
property_type,
build_fn=None,
display_group_collapsed: bool = False,
prim_paths: List[Sdf.Path] = None,
):
"""
Constructor.
Args:
prop_name: name of the Usd Property. This is not the display name.
display_group: group of the Usd Property when displayed on UI.
metadata: metadata associated with the Usd Property.
property_type: type of the property. Either Usd.Property or Usd.Relationship.
build_fn: a custom build function to build the UI. If not None the default builder will not be used.
display_group_collapsed: if the display group should be collapsed. Group only collapses when ALL its contents request such.
prim_paths: to override what prim paths this property will be built upon. Leave it to None to use default (currently selected paths, or last selected path if multi-edit is off).
"""
self.prop_name = prop_name
self.display_group = display_group
self.display_group_collapsed = display_group_collapsed
self.metadata = metadata
self.property_type = property_type
self.prim_paths = prim_paths
self.build_fn = build_fn
def add_custom_metadata(self, key: str, value):
"""
If value is not None, add it to the custom data of the metadata using the specified key. Otherwise, remove that
key from the custom data.
Args:
key: the key that should containt the custom metadata value
value: the value that should be added to the custom metadata if not None
"""
custom_data = self.metadata.get(Sdf.PrimSpec.CustomDataKey, {})
if value is not None:
custom_data[key] = value
elif key in custom_data:
del custom_data[key]
self.metadata[Sdf.PrimSpec.CustomDataKey] = custom_data
def override_display_group(self, display_group: str, collapsed: bool = False):
"""
Overrides the display group of the property. It only affects UI and DOES NOT write back DisplayGroup metadata to USD.
Args:
display_group: new display group to override to.
collapsed: if the display group should be collapsed. Group only collapses when ALL its contents request such.
"""
self.display_group = display_group
self.display_group_collapsed = collapsed
def override_display_name(self, display_name: str):
"""
Overrides the display name of the property. It only affects UI and DOES NOT write back DisplayName metadata to USD.
Args:
display_group: new display group to override to.
"""
self.metadata[Sdf.PropertySpec.DisplayNameKey] = display_name
# for backward compatibility
def __getitem__(self, key):
if key == 0:
return self.prop_name
elif key == 1:
return self.display_group
elif key == 2:
return self.metadata
return None
@property
def attr_name(self):
return self.prop_name
@attr_name.setter
def attr_name(self, value):
self.prop_name = value
def get_nested_display_groups(self):
if len(self.display_group) == 0:
return []
# Per USD documentation nested display groups are separated by colon
return self.display_group.split(":")
def __eq__(self, other):
return (
type(self) == type(other)
and self.prop_name == other.prop_name
and self.display_group == other.display_group
and self._compare_metadata(self.metadata, other.metadata)
and self.property_type == other.property_type
and self.prim_paths == other.prim_paths
)
def _compare_metadata(self, meta1, meta2) -> bool:
ignored_metadata = {"default", "colorSpace"}
for key, value in meta1.items():
if key not in ignored_metadata and (key not in meta2 or meta2[key] != value):
return False
for key, value in meta2.items():
if key not in ignored_metadata and (key not in meta1 or meta1[key] != value):
return False
return True
class UiDisplayGroup:
def __init__(self, name):
self.name = name
self.sub_groups = DefaultDict()
self.props = []
class UsdPropertiesWidget(SimplePropertyWidget):
"""
UsdPropertiesWidget provides functionalities to automatically populates UsdProperties on given prim(s). The UI will
and models be generated according to UsdProperties's value type. Multi-prim editing works for shared Properties
between all selected prims if instantiated with multi_edit = True.
"""
def __init__(self, title: str, collapsed: bool, multi_edit: bool = True):
"""
Constructor.
Args:
title: title of the widget.
collapsed: whether the collapsable frame should be collapsed for this widget.
multi_edit: whether multi-editing is supported.
If False, properties will only be collected from the last selected prim.
If True, shared properties among all selected prims will be collected.
"""
super().__init__(title=title, collapsed=collapsed)
self._multi_edit = multi_edit
self._models = defaultdict(list)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self._bus_sub = None
self._listener = None
self._pending_dirty_task = None
self._pending_dirty_paths = set()
self._group_menu_entries = []
def clean(self):
"""
See PropertyWidget.clean
"""
self.reset_models()
super().clean()
def reset(self):
"""
See PropertyWidget.reset
"""
self.reset_models()
super().reset()
def reset_models(self):
# models can be shared among multiple prims. Only clean once!
unique_models = set()
if self._models is not None:
for models in self._models.values():
for model in models:
unique_models.add(model)
for model in unique_models:
model.clean()
self._models = defaultdict(list)
if self._listener:
self._listener.Revoke()
self._listener = None
self._bus_sub = None
if self._pending_dirty_task is not None:
self._pending_dirty_task.cancel()
self._pending_dirty_task = None
self._pending_dirty_paths.clear()
for entry in self._group_menu_entries:
entry.release()
self._group_menu_entries.clear()
def get_additional_kwargs(self, ui_prop: UsdPropertyUiEntry):
"""
Override this function if you want to supply additional arguments when building the label or ui widget.
"""
additional_label_kwargs = None
additional_widget_kwargs = None
return additional_label_kwargs, additional_widget_kwargs
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
"""
Override this function to customize property building.
"""
# override prim paths to build if UsdPropertyUiEntry specifies one
if ui_prop.prim_paths:
prim_paths = ui_prop.prim_paths
build_fn = ui_prop.build_fn if ui_prop.build_fn else UsdPropertiesWidgetBuilder.build
additional_label_kwargs, additional_widget_kwargs = self.get_additional_kwargs(ui_prop)
models = build_fn(
stage,
ui_prop.prop_name,
ui_prop.metadata,
ui_prop.property_type,
prim_paths,
additional_label_kwargs,
additional_widget_kwargs,
)
if models:
if not isinstance(models, list):
models = [models]
for model in models:
for prim_path in prim_paths:
self._models[prim_path.AppendProperty(ui_prop.prop_name)].append(model)
def build_nested_group_frames(self, stage, display_group: UiDisplayGroup):
"""
Override this function to build group frames differently.
"""
if self._multi_edit:
prim_paths = self._payload.get_paths()
else:
prim_paths = self._payload[-1:]
def build_props(props):
collapse_frame = len(props) > 0
# we need to build those property in 2 different possible locations
for prop in props:
self.build_property_item(stage, prop, prim_paths)
collapse_frame &= prop.display_group_collapsed
return collapse_frame
def get_sub_props(group: UiDisplayGroup, sub_prop_list: list):
if len(group.sub_groups) > 0:
for name, sub_group in group.sub_groups.items():
for sub_prop in sub_group.props:
sub_prop_list.append(sub_prop)
get_sub_props(sub_group, sub_prop_list)
def build_nested(display_group: UiDisplayGroup, level: int, prefix: str):
# Only create a collapsable frame if the group is not "" (for root level group)
if len(display_group.name) > 0:
id = prefix + ":" + display_group.name
frame = ui.CollapsableFrame(
title=display_group.name,
build_header_fn=lambda collapsed, text, id=id: self._build_frame_header(collapsed, text, id),
name="subFrame",
)
else:
id = prefix
frame = ui.Frame(name="subFrame")
prop_list = []
sub_props = get_sub_props(display_group, prop_list)
with frame:
with ui.VStack(height=0, spacing=5, name="frame_v_stack"):
for name, sub_group in display_group.sub_groups.items():
build_nested(sub_group, level + 1, id)
# Only do "Extra Properties" for root level group
if len(display_group.sub_groups) > 0 and len(display_group.props) > 0 and level == 0:
extra_group_name = "Extra Properties"
extra_group_id = prefix + ":" + extra_group_name
with ui.CollapsableFrame(
title=extra_group_name,
build_header_fn=lambda collapsed, text, id=extra_group_id: self._build_frame_header(
collapsed, text, id
),
name="subFrame",
):
with ui.VStack(height=0, spacing=5, name="frame_v_stack"):
build_props(display_group.props)
self._build_header_context_menu(
group_name=extra_group_name, group_id=extra_group_id, props=sub_props
)
else:
collapse = build_props(display_group.props)
if collapse and isinstance(frame, ui.CollapsableFrame):
frame.collapsed = collapse
# if level is 0, this is the root level group, and we use the self._title for its name
self._build_header_context_menu(
group_name=display_group.name if level > 0 else self._title, group_id=id, props=sub_props
)
build_nested(display_group, 0, self._title)
# if we have subFrame we need the main frame to assume the groupFrame styling
if len(display_group.sub_groups) > 0:
# here we reach into the Parent class frame
self._collapsable_frame.name = "groupFrame"
def build_items(self):
"""
See SimplePropertyWidget.build_items
"""
self.reset()
if len(self._payload) == 0:
return
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
stage = last_prim.GetStage()
if not stage:
return
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
self._bus_sub = self._message_bus.create_subscription_to_pop_by_type(
ADDITIONAL_CHANGED_PATH_EVENT_TYPE, self._on_bus_event
)
shared_props = self._get_shared_properties_from_selected_prims(last_prim)
if not shared_props:
return
shared_props = self._customize_props_layout(shared_props)
grouped_props = UiDisplayGroup("")
for prop in shared_props:
nested_groups = prop.get_nested_display_groups()
sub_group = grouped_props
for sub_group_name in nested_groups:
sub_group = sub_group.sub_groups.setdefault(sub_group_name, UiDisplayGroup(sub_group_name))
sub_group.props.append(prop)
self.build_nested_group_frames(stage, grouped_props)
def _build_header_context_menu(self, group_name: str, group_id: str, props: List[UsdPropertyUiEntry] = None):
"""
Override this function to build the context menu when right click on a Collapsable group header
Args:
group_name: Display name of the group. If it's not a subgroup, it's the title of the widget.
group_id: A unique identifier for group context menu.
props: Properties under this group. It contains all properties in its subgroups as well.
"""
self._build_group_builtin_header_context_menu(group_name, group_id, props)
self._build_group_additional_header_context_menu(group_name, group_id, props)
def _build_group_builtin_header_context_menu(
self, group_name: str, group_id: str, props: List[UsdPropertyUiEntry] = None
):
from .usd_attribute_model import GfVecAttributeSingleChannelModel
prop_names: Set[str] = set()
if props:
for prop in props:
prop_names.add(prop.prop_name)
def can_copy(object):
# Only support single selection copy oer OM-20206
return len(self._payload) == 1
def on_copy(object):
visited_models = set()
properties_to_copy: Dict[Sdf.Path, Any] = dict()
for models in self._models.values():
for model in models:
if model in visited_models:
continue
visited_models.add(model)
# Skip "Mixed"
if model.is_ambiguous():
continue
paths = model.get_property_paths()
if paths:
# Copy from the last path
# In theory if the value is not mixed all paths should have same value, so which one to pick doesn't matter
last_path = paths[-1]
# Only copy from the properties from this group
if props is not None and last_path.name not in prop_names:
continue
if issubclass(type(model), UsdBase):
# No need to copy single channel model. Each vector attribute also has a GfVecAttributeModel
if isinstance(model, GfVecAttributeSingleChannelModel):
continue
properties_to_copy[paths[-1]] = model.get_value()
elif isinstance(model, RelationshipEditWidget):
properties_to_copy[paths[-1]] = model.get_targets().copy()
if properties_to_copy:
set_group_properties_clipboard(properties_to_copy)
menu = {
"name": f'Copy All Property Values in "{group_name}"',
"show_fn": lambda object: True,
"enabled_fn": can_copy,
"onclick_fn": on_copy,
}
self._group_menu_entries.append(self._register_header_context_menu_entry(menu, group_id))
def on_paste(object):
properties_to_copy = get_group_properties_clipboard()
if not properties_to_copy:
return
unique_model_prim_paths: Set[Sdf.Path] = set()
for prop_path in self._models:
unique_model_prim_paths.add(prop_path.GetPrimPath())
with omni.kit.undo.group():
try:
for path, value in properties_to_copy.items():
for prim_path in unique_model_prim_paths:
# Only paste to the properties in this group
if props is not None and path.name not in prop_names:
continue
paste_to_model_path = prim_path.AppendProperty(path.name)
models = self._models.get(paste_to_model_path, [])
for model in models:
if isinstance(model, GfVecAttributeSingleChannelModel):
continue
else:
model.set_value(value)
except Exception as e:
carb.log_warn(traceback.format_exc())
menu = {
"name": f'Paste All Property Values to "{group_name}"',
"show_fn": lambda object: True,
"enabled_fn": lambda object: get_group_properties_clipboard(),
"onclick_fn": on_paste,
}
self._group_menu_entries.append(self._register_header_context_menu_entry(menu, group_id))
def can_reset(object):
visited_models = set()
for models in self._models.values():
for model in models:
if model in visited_models:
continue
visited_models.add(model)
paths = model.get_property_paths()
if paths:
last_path = paths[-1]
# Only reset from the properties from this group
if props is not None and last_path.name not in prop_names:
continue
if issubclass(type(model), UsdBase):
if model.is_different_from_default():
return True
return False
def on_reset(object):
visited_models = set()
for models in self._models.values():
for model in models:
if model in visited_models:
continue
visited_models.add(model)
paths = model.get_property_paths()
if paths:
last_path = paths[-1]
# Only reset from the properties from this group
if props is not None and last_path.name not in prop_names:
continue
if issubclass(type(model), UsdBase):
model.set_default()
menu = {
"name": f'Reset All Property Values in "{group_name}"',
"show_fn": lambda object: True,
"enabled_fn": can_reset,
"onclick_fn": on_reset,
}
self._group_menu_entries.append(self._register_header_context_menu_entry(menu, group_id))
def _build_group_additional_header_context_menu(
self, group_name: str, group_id: str, props: List[UsdPropertyUiEntry] = None
):
"""
Override this function to build the additional context menu to Kit's built-in ones when right click on a Collapsable group header
Args:
group_name: Display name of the group. If it's not a subgroup, it's the title of the widget.
group_id: A unique identifier for group context menu.
props: Properties under this group. It contains all properties in its subgroups as well.
"""
...
def _register_header_context_menu_entry(self, menu: Dict, group_id: str):
"""
Registers a menu entry to Collapsable group header
Args:
menu: The menu entry to be registered.
group_id: A unique identifier for group context menu.
Return:
The subscription object of the menu entry to be kept alive during menu's life span.
"""
return omni.kit.context_menu.add_menu(menu, "group_context_menu." + group_id, "omni.kit.window.property")
def _filter_props_to_build(self, props):
"""
When deriving from UsdPropertiesWidget, override this function to filter properties to build.
Args:
props: List of Usd.Property on a selected prim.
"""
return [prop for prop in props if not prop.IsHidden()]
def _customize_props_layout(self, props):
"""
When deriving from UsdPropertiesWidget, override this function to reorder/regroup properties to build.
To reorder the properties display order, reorder entries in props list.
To override display group or name, call prop.override_display_group or prop.override_display_name respectively.
If you want to hide/add certain property, remove/add them to the list.
NOTE: All above changes won't go back to USD, they're pure UI overrides.
Args:
props: List of Tuple(property_name, property_group, metadata)
Example:
for prop in props:
# Change display group:
prop.override_display_group("New Display Group")
# Change display name (you can change other metadata, it won't be write back to USD, only affect UI):
prop.override_display_name("New Display Name")
# add additional "property" that doesn't exist.
props.append(UsdPropertyUiEntry("PlaceHolder", "Group", { Sdf.PrimSpec.TypeNameKey: "bool"}, Usd.Property))
"""
return props
@Trace.TraceFunction
def _on_usd_changed(self, notice, stage):
carb.profiler.begin(1, "UsdPropertyWidget._on_usd_changed")
try:
if stage != self._payload.get_stage():
return
if not self._collapsable_frame:
return
if len(self._payload) == 0:
return
# Widget is pending rebuild, no need to check for dirty
if self._pending_rebuild_task is not None:
return
dirty_paths = set()
for path in notice.GetResyncedPaths():
if path in self._payload:
self.request_rebuild()
return
elif path.GetPrimPath() in self._payload:
prop = stage.GetPropertyAtPath(path)
# If prop is added or removed, rebuild frame
# TODO only check against the properties this widget cares about
if (not prop.IsValid()) != (self._models.get(path) is None):
self.request_rebuild()
return
# else trigger existing model to reload the value
else:
dirty_paths.add(path)
for path in notice.GetChangedInfoOnlyPaths():
dirty_paths.add(path)
self._pending_dirty_paths.update(dirty_paths)
if self._pending_dirty_task is None:
self._pending_dirty_task = asyncio.ensure_future(self._delayed_dirty_handler())
finally:
carb.profiler.end(1)
def _on_bus_event(self, event: carb.events.IEvent):
# TODO from C++?
# stage = event.payload["stage"]
# if stage != self._payload.get_stage():
# return
if not self._collapsable_frame:
return
if len(self._payload) == 0:
return
# Widget is pending rebuild, no need to check for dirty
if self._pending_rebuild_task is not None:
return
path = event.payload["path"]
self._pending_dirty_paths.add(Sdf.Path(path))
if self._pending_dirty_task is None:
self._pending_dirty_task = asyncio.ensure_future(self._delayed_dirty_handler())
def _get_prim(self, prim_path):
if prim_path:
stage = self._payload.get_stage()
if stage:
return stage.GetPrimAtPath(prim_path)
return None
def _get_shared_properties_from_selected_prims(self, anchor_prim):
shared_props_dict = None
if self._multi_edit:
prim_paths = self._payload.get_paths()
else:
prim_paths = self._payload[-1:]
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
props = self._filter_props_to_build(prim.GetProperties())
prop_dict = {}
for prop in props:
if prop.IsHidden():
continue
prop_dict[prop.GetName()] = UsdPropertyUiEntry(
prop.GetName(), prop.GetDisplayGroup(), prop.GetAllMetadata(), type(prop)
)
if shared_props_dict is None:
shared_props_dict = prop_dict
else:
# Find intersection of the dicts
intersect_shared_props = {}
for prop_name, prop_info in shared_props_dict.items():
if prop_dict.get(prop_name) == prop_info:
intersect_shared_props[prop_name] = prop_info
if len(intersect_shared_props) == 0:
# No intersection, nothing to build
# early return
return
shared_props_dict = intersect_shared_props
shared_props = list(shared_props_dict.values())
# Sort properties to PropertyOrder using the last selected object
order = anchor_prim.GetPropertyOrder()
shared_prop_order = []
shared_prop_unordered = []
for prop in shared_props:
if prop[0] in order:
shared_prop_order.append(prop[0])
else:
shared_prop_unordered.append(prop[0])
shared_prop_order.extend(shared_prop_unordered)
sorted(shared_props, key=lambda x: shared_prop_order.index(x[0]))
return shared_props
def request_rebuild(self):
# If widget is going to be rebuilt, _pending_dirty_task does not need to run.
if self._pending_dirty_task is not None:
self._pending_dirty_task.cancel()
self._pending_dirty_task = None
self._pending_dirty_paths.clear()
super().request_rebuild()
async def _delayed_dirty_handler(self):
while True:
# Do not refresh UI until visible/uncollapsed
if not self._collapsed:
break
await omni.kit.app.get_app().next_update_async()
# clear the pending dirty tasks BEFORE dirting model.
# dirtied model may trigger additional USD notice that needs to be scheduled.
self._pending_dirty_task = None
if self._pending_dirty_paths:
# Make a copy of the paths. It may change if USD edits are made during iteration
pending_dirty_paths = self._pending_dirty_paths.copy()
self._pending_dirty_paths.clear()
carb.profiler.begin(1, "UsdPropertyWidget._delayed_dirty_handler")
# multiple path can share the same model. Only dirty once!
dirtied_models = set()
for path in pending_dirty_paths:
models = self._models.get(path)
if models:
for model in models:
if model not in dirtied_models:
model._set_dirty()
dirtied_models.add(model)
carb.profiler.end(1)
class SchemaPropertiesWidget(UsdPropertiesWidget):
"""
SchemaPropertiesWidget only filters properties and only show the onces from a given IsA schema or applied API schema.
"""
def __init__(self, title: str, schema, include_inherited: bool):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter properties.
include_inherited (bool): Whether the filter should include inherited properties.
"""
super().__init__(title, collapsed=False)
self._title = title
self._schema = schema
self._include_inherited = include_inherited
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim:
return False
is_api_schema = Usd.SchemaRegistry().IsAppliedAPISchema(self._schema)
if not (is_api_schema and prim.HasAPI(self._schema) or not is_api_schema and prim.IsA(self._schema)):
return False
return True
def _filter_props_to_build(self, props):
"""
See UsdPropertiesWidget._filter_props_to_build
"""
if len(props) == 0:
return props
if Usd.SchemaRegistry().IsMultipleApplyAPISchema(self._schema):
prim = props[0].GetPrim()
schema_instances = set()
schema_type_name = Usd.SchemaRegistry().GetSchemaTypeName(self._schema)
for schema in prim.GetAppliedSchemas():
if schema.startswith(schema_type_name):
schema_instances.add(schema[len(schema_type_name) + 1 :])
filtered_props = []
api_path_func_name = f"Is{schema_type_name}Path"
api_path_func = getattr(self._schema, api_path_func_name)
# self._schema.GetSchemaAttributeNames caches the query result in a static variable and any new instance
# token passed into it won't change the cached property names. This can potentially cause problems as other
# code calling same function with different instance name will get wrong result.
#
# There's any other function IsSchemaPropertyBaseName but it's not implemented on all applied schemas. (not
# implemented in a few PhysicsSchema, for example.
#
# if include_inherited is True, it returns SchemaTypeName:BaseName for properties, otherwise it only returns
# BaseName.
schema_attr_names = self._schema.GetSchemaAttributeNames(self._include_inherited, "")
for prop in props:
if prop.IsHidden():
continue
prop_path = prop.GetPath().pathString
for instance_name in schema_instances:
instance_seg = prop_path.find(":" + instance_name + ":")
if instance_seg != -1:
api_path = prop_path[0 : instance_seg + 1 + len(instance_name)]
if api_path_func(api_path):
base_name = prop_path[instance_seg + 1 + len(instance_name) + 1 :]
if base_name in schema_attr_names:
filtered_props.append(prop)
break
return filtered_props
else:
schema_attr_names = self._schema.GetSchemaAttributeNames(self._include_inherited)
return [prop for prop in props if prop.GetName() in schema_attr_names]
class MultiSchemaPropertiesWidget(UsdPropertiesWidget):
"""
MultiSchemaPropertiesWidget filters properties and only show the onces from a given IsA schema or schema subclass list.
"""
__known_api_schemas = set()
def __init__(
self,
title: str,
schema,
schema_subclasses: list,
include_list: list = [],
exclude_list: list = [],
api_schemas: Sequence[str] = None,
group_api_schemas: bool = False,
):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter properties.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
api_schemas (sequence): a sequence of AppliedAPI schema names that this widget handles
group_api_schemas (bool): whether to create default groupings for any AppliedSchemas on the Usd.Prim
"""
super().__init__(title=title, collapsed=False)
self._title = title
self._schema = schema
# create schema_attr_names
self._schema_attr_base = schema.GetSchemaAttributeNames(False)
for subclass in schema_subclasses:
self._schema_attr_base += subclass.GetSchemaAttributeNames(False)
self._schema_attr_base += include_list
self._schema_attr_base = set(self._schema_attr_base) - set(exclude_list)
# Setup the defaults for handling applied API schemas
self._applied_schemas = {}
self._schema_attr_names = None
self._group_api_schemas = group_api_schemas
# Save any custom Applied Schemas and mark them to be ignored when building default widget
self._custom_api_schemas = api_schemas
if self._custom_api_schemas:
MultiSchemaPropertiesWidget.__known_api_schemas.update(self._custom_api_schemas)
def __del__(self):
# Mark any custom Applied Schemas to start being handled by the defaut widget
if self._custom_api_schemas:
MultiSchemaPropertiesWidget.__known_api_schemas.difference_update(self._custom_api_schemas)
def clean(self):
"""
See PropertyWidget.clean
"""
self._applied_schemas = {}
self._schema_attr_names = None
super().clean()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
schema_reg = Usd.SchemaRegistry()
self._applied_schemas = {}
# Build out our _schema_attr_names variable to include properties from the base schema and any applied schemas
self._schema_attr_names = self._schema_attr_base
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
# If the base-schema has requested auto-grouping of all Applied Schemas, handle that grouping now
if self._group_api_schemas:
# XXX: Should this be delayed until _customize_props_layout ?
for api_schema in prim.GetAppliedSchemas():
# Ignore any API schemas that are already registered as custom widgets
if api_schema in MultiSchemaPropertiesWidget.__known_api_schemas:
continue
# Skip over any API schemas that USD doesn't actually know about
prim_def = schema_reg.FindAppliedAPIPrimDefinition(api_schema)
if not prim_def:
continue
api_prop_names = prim_def.GetPropertyNames()
self._schema_attr_names = self._schema_attr_names.union(api_prop_names)
for api_prop in api_prop_names:
display_group = prim_def.GetPropertyMetadata(api_prop, "displayGroup")
prop_grouping = self._applied_schemas.setdefault(api_schema, {}).setdefault(display_group, [])
prop_grouping.append((api_prop, prim_def.GetPropertyMetadata(api_prop, "displayName")))
used += self._filter_props_to_build(prim.GetProperties())
return used
def _filter_props_to_build(self, props):
"""
See UsdPropertiesWidget._filter_props_to_build
"""
return [prop for prop in props if prop.GetName() in self._schema_attr_names and not prop.IsHidden()]
def _customize_props_layout(self, attrs):
# If no applied schemas, just use the base class' layout.
if not self._applied_schemas:
return super()._customize_props_layout(attrs)
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
# We can't really escape the parent group, so all default/base and applied-schemas will be common to a group
frame = CustomLayoutFrame(hide_extra=False)
with frame:
# Add all base properties at the top
base_attrs = [attr for attr in attrs if attr.prop_name in self._schema_attr_base]
if base_attrs:
with CustomLayoutGroup(self._title):
for attr in base_attrs:
CustomLayoutProperty(attr.prop_name, attr.display_group)
attr.override_display_group(self._title)
# Now create a master-group for each applied schema, and possibly sub-groups for it's properties
# Here's where we may want to actually escape the parent and create a totally new group
with frame:
for api_schema, api_schema_groups in self._applied_schemas.items():
with CustomLayoutGroup(api_schema):
for prop_group, props in api_schema_groups.items():
with CustomLayoutGroup(prop_group):
for prop in props:
CustomLayoutProperty(*prop)
return frame.apply(attrs)
class RawUsdPropertiesWidget(UsdPropertiesWidget):
MULTI_SELECTION_LIMIT_SETTING_PATH = "/persistent/exts/omni.kit.property.usd/raw_widget_multi_selection_limit"
MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH = (
"/exts/omni.kit.property.usd/multi_selection_limit_do_not_ask" # session only, not persistent!
)
def __init__(self, title: str, collapsed: bool, multi_edit: bool = True):
super().__init__(title=title, collapsed=collapsed, multi_edit=multi_edit)
self._settings = carb.settings.get_settings()
self._settings.set_default(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH, False)
self._skip_multi_selection_protection = False
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
for prim_path in self._payload:
if not prim_path.IsPrimPath():
return False
self._skip_multi_selection_protection = False
return bool(self._payload and len(self._payload) > 0)
def build_impl(self):
# rebuild frame when frame is opened
super().build_impl()
self._collapsable_frame.set_collapsed_changed_fn(self._on_collapsed_changed)
def build_items(self):
# only show raw items if frame is open
if self._collapsable_frame and not self._collapsable_frame.collapsed:
if not self._multi_selection_protected():
super().build_items()
def _on_collapsed_changed(self, collapsed):
if not collapsed:
self.request_rebuild()
def _multi_selection_protected(self):
if self._no_multi_selection_protection_this_session():
return False
def show_all(do_not_ask: bool):
self._settings.set(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH, do_not_ask)
self._skip_multi_selection_protection = True
self.request_rebuild()
multi_select_limit = self._settings.get(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_SETTING_PATH)
if multi_select_limit and len(self._payload) > multi_select_limit and not self._skip_multi_selection_protection:
ui.Separator()
ui.Label(
f"You have selected {len(self._payload)} Prims, to preserve fast performance the Raw Usd Properties Widget is not showing above the current limit of {multi_select_limit} Prims. Press the button below to show it anyway but expect potential performance penalty.",
width=omni.ui.Percent(100),
alignment=ui.Alignment.CENTER,
name="label",
word_wrap=True,
)
button = ui.Button("Skip Multi Selection Protection")
with ui.HStack(width=0):
checkbox = ui.CheckBox()
ui.Spacer(width=5)
ui.Label("Do not ask again for current session.", name="label")
button.set_clicked_fn(lambda: show_all(checkbox.model.get_value_as_bool()))
return True
return False
def _no_multi_selection_protection_this_session(self):
return self._settings.get(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH)
| 43,336 | Python | 39.38863 | 277 | 0.581595 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/property_preferences_page.py | import carb.settings
import omni.ui as ui
from omni.kit.window.preferences import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX
class PropertyUsdPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Property Widgets")
def build(self):
with ui.VStack(height=0):
with self.add_frame("Property Window"):
with ui.VStack():
w = self.create_setting_widget(
"Large selections threshold. This prevents slowdown/stalls on large selections, after this number of prims is selected most of the property window will be hidden.\n\nSet to zero to disable this feature\n\n",
PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/large_selection",
SettingType.INT,
height=20
)
w.identifier = "large_selection"
w = self.create_setting_widget(
"Raw Usd Properties Widget multi-selection limit. This prevents slowdown/stalls on large selections, after this number of prims is selected content of Raw Usd Properties Widget will be hidden.\n\nSet to zero to disable this feature\n\n",
PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/raw_widget_multi_selection_limit",
SettingType.INT,
height=20
)
w.identifier = "raw_widget_multi_selection_limit"
| 1,536 | Python | 51.999998 | 261 | 0.599609 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/placeholder_attribute.py | import carb
from pxr import Sdf, Usd, UsdGeom, UsdShade
## this is a placeholder for Usd.Attribute as that class cannot be created unless attached to a prim
class PlaceholderAttribute:
def __init__(self, name, prim: Usd.Prim = None, metadata=None):
self._name = name
self._prim = prim
self._metadata = metadata if metadata else {}
def Get(self, time_code=0):
if self._metadata:
custom_data = self._metadata.get("customData")
if custom_data is not None and "default" in custom_data:
return custom_data["default"]
default = self._metadata.get("default")
if default is not None:
return default
carb.log_warn(f"PlaceholderAttribute.Get() customData.default or default not found in metadata")
return None
def GetPath(self):
if self._prim:
return self._prim.GetPath()
return None
def ValueMightBeTimeVarying(self):
return False
def GetMetadata(self, token):
if token in self._metadata:
return self._metadata[token]
return False
def GetAllMetadata(self):
return self._metadata
def GetPrim(self):
return self._prim
def CreateAttribute(self):
try:
if not self._name:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error no attribute name")
return None
if not self._prim:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error no target prim")
return None
type_name_key = self._metadata.get(Sdf.PrimSpec.TypeNameKey)
if not type_name_key:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error TypeNameKey")
return None
type_name = Sdf.ValueTypeNames.Find(type_name_key)
if self._name.startswith("primvars:"):
pv = UsdGeom.PrimvarsAPI(self._prim)
attribute = UsdGeom.PrimvarsAPI(self._prim).CreatePrimvar(self._name[9:], type_name).GetAttr()
elif self._name.startswith("inputs:"):
shader = UsdShade.Shader(self._prim)
attribute = shader.CreateInput(self._name[7:], type_name).GetAttr()
else:
attribute = self._prim.CreateAttribute(self._name, type_name, custom=False)
filter = {"customData", "displayName", "displayGroup", "documentation"}
if attribute:
for key in self._metadata:
if key not in filter:
attribute.SetMetadata(key, self._metadata[key])
attribute.Set(self.Get())
return attribute
except Exception as exc:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error {exc}")
return None
def HasAuthoredConnections(self):
return False
| 2,948 | Python | 33.694117 | 110 | 0.591927 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/widgets.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 weakref
from pathlib import Path
from typing import List
import carb
import omni.ext
import omni.kit.app
import omni.ui as ui
import omni.usd
from pxr import Sdf, UsdGeom
from .attribute_context_menu import AttributeContextMenu
from .control_state_manager import ControlStateManager
from .prim_path_widget import PrimPathWidget
from .prim_selection_payload import PrimSelectionPayload
ICON_PATH = ""
TEST_DATA_PATH = ""
class UsdPropertyWidgets(omni.ext.IExt):
def __init__(self):
self._registered = False
self._examples = None
self._selection_notifiers = []
def on_startup(self, ext_id):
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global ICON_PATH
ICON_PATH = Path(extension_path).joinpath("data").joinpath("icons")
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
self._selection_notifiers.append(SelectionNotifier()) # default context
self._usd_preferences = None
self._hooks = []
self._attribute_context_menu = AttributeContextMenu()
self._control_state_manager = ControlStateManager(ICON_PATH)
self._hooks.append(
manager.subscribe_to_extension_enable(
lambda _: self._register_widget(),
lambda _: self._unregister_widget(),
ext_name="omni.kit.window.property",
hook_name="omni.usd listener",
)
)
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder
UsdPropertiesWidgetBuilder.startup()
manager = omni.kit.app.get_app().get_extension_manager()
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_preferences(),
on_disable_fn=lambda _: self._unregister_preferences(),
ext_name="omni.kit.window.preferences",
hook_name="omni.kit.property.usd omni.kit.window.preferences listener",
)
)
def on_shutdown(self):
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder
UsdPropertiesWidgetBuilder.shutdown()
self._control_state_manager.destory()
self._control_state_manager = None
self._attribute_context_menu.destroy()
self._attribute_context_menu = None
for notifier in self._selection_notifiers:
notifier.stop()
self._selection_notifiers.clear()
self._hooks = None
if self._registered:
self._unregister_widget()
self._unregister_preferences()
def _register_preferences(self):
from omni.kit.window.preferences import register_page
from .property_preferences_page import PropertyUsdPreferences
self._usd_preferences = omni.kit.window.preferences.register_page(PropertyUsdPreferences())
def _unregister_preferences(self):
if self._usd_preferences:
import omni.kit.window.preferences
omni.kit.window.preferences.unregister_page(self._usd_preferences)
self._usd_preferences = None
def _register_widget(self):
try:
import omni.kit.window.property as p
from .references_widget import PayloadReferenceWidget
from .usd_property_widget import RawUsdPropertiesWidget, UsdPropertiesWidget
from .variants_widget import VariantsWidget
w = p.get_window()
if w:
w.register_widget("prim", "path", PrimPathWidget())
w.register_widget("prim", "references", PayloadReferenceWidget())
w.register_widget("prim", "payloads", PayloadReferenceWidget(use_payloads=True))
w.register_widget("prim", "variants", VariantsWidget())
w.register_widget(
"prim", "attribute", RawUsdPropertiesWidget(title="Raw USD Properties", collapsed=True), False
)
# A few examples. Expected to be removed at some point.
# self._examples = Examples(w)
for notifier in self._selection_notifiers:
notifier.start()
notifier._notify_property_window() # force a refresh
self._registered = True
except Exception as exc:
carb.log_warn(f"error {exc}")
def _unregister_widget(self):
try:
import omni.kit.window.property as p
w = p.get_window()
if w:
for notifier in self._selection_notifiers:
notifier.stop()
w.unregister_widget("prim", "attribute")
w.unregister_widget("prim", "variants")
w.unregister_widget("prim", "references")
w.unregister_widget("prim", "payloads")
w.unregister_widget("prim", "path")
if self._examples:
self._examples.clean(w)
self._examples = None
self._registered = False
except Exception as e:
carb.log_warn(f"Unable to unregister omni.usd.widget: {e}")
class SelectionNotifier:
def __init__(self, usd_context_id="", property_window_context_id=""):
self._usd_context = omni.usd.get_context(usd_context_id)
self._selection = self._usd_context.get_selection()
self._property_window_context_id = property_window_context_id
def start(self):
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.usd.widget"
)
def stop(self):
self._stage_event_sub = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED) or event.type == int(
omni.usd.StageEventType.CLOSING
):
self._notify_property_window()
def _notify_property_window(self):
import omni.kit.window.property as p
# TODO _property_window_context_id
w = p.get_window()
if w and self._usd_context:
stage = None
selected_paths = []
if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED:
stage = weakref.ref(self._usd_context.get_stage())
selected_paths = [Sdf.Path(path) for path in self._selection.get_selected_prim_paths()]
payload = PrimSelectionPayload(stage, selected_paths)
w.notify("prim", payload)
class Examples: # pragma: no cover
"""
Examples of showing how to use PropertyWindow APIs.
"""
def __init__(self, w):
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from .usd_property_widget import SchemaPropertiesWidget, UsdPropertiesWidget
# Example of PropertySchemeDelegate
class MeshWidget(SchemaPropertiesWidget):
def __init__(self):
super().__init__("Mesh", UsdGeom.Mesh, False)
def _group_helper(self, attr, group_prefix):
if attr.attr_name.startswith(group_prefix):
import re
attr.override_display_group(group_prefix.capitalize())
attr.override_display_name(re.sub(r"(\w)([A-Z])", r"\1 \2", attr.attr_name[len(group_prefix) :]))
return True
return False
def _filter_props_to_build(self, attrs):
schema_attr_names = self._schema.GetSchemaAttributeNames(self._include_inherited)
schema_attr_names.append("material:binding")
return [attr for attr in attrs if attr.GetName() in schema_attr_names]
# Example of how to use _customize_props_layout
def _customize_props_layout(self, attrs):
auto_arrange = False
if auto_arrange:
for attr in attrs:
if not self._group_helper(attr, "crease"):
if not self._group_helper(attr, "corner"):
if not self._group_helper(attr, "face"):
attr.override_display_group("Other")
return attrs
else:
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import (HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH,
SimplePropertyWidget)
from .custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
frame = CustomLayoutFrame(hide_extra=False)
with frame:
with CustomLayoutGroup("Face"):
CustomLayoutProperty("faceVertexCounts", "Vertex Counts")
CustomLayoutProperty("faceVertexIndices", "Vertex Indices")
with CustomLayoutGroup("Corner"):
CustomLayoutProperty("cornerIndices", "Indices")
CustomLayoutProperty("cornerSharpnesses", "Sharpnesses")
with CustomLayoutGroup("Crease"):
CustomLayoutProperty("creaseIndices", "Indices")
CustomLayoutProperty("creaseLengths", "Lengths")
with CustomLayoutGroup("CustomItems"):
with CustomLayoutGroup("Nested"):
def build_fn(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs={},
additional_widget_kwarg={},
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label(
"Cool Label", additional_label_kwargs={"tooltip": "Cool Tooltip"}
)
ui.Button("Cool Button")
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label("Very Cool Label")
ui.Button("Super Cool Button")
CustomLayoutProperty(None, None, build_fn=build_fn)
return frame.apply(attrs)
def get_additional_kwargs(self, ui_attr):
if ui_attr[0] == "material:binding":
from pxr import UsdShade
return None, {"target_picker_filter_type_list": [UsdShade.Material], "targets_limit": 1}
return None, None
w.register_widget("prim", "mesh", MeshWidget())
def clean(self, w):
pass
| 11,778 | Python | 40.769503 | 117 | 0.569282 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/asset_filepicker.py | # Copyright (c) 2020-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 os
import omni.usd
from typing import Tuple, Any, Callable
from functools import partial
from pxr import Sdf
import carb.settings
import omni.client
import omni.ui as ui
from omni.kit.window.file_importer import get_file_importer
from .usd_attribute_model import SdfAssetPathAttributeModel
DEFAULT_FILE_EXTS = ("*.*", "All Files")
def show_asset_file_picker(
title: str,
assign_value_fn: Callable[[Any, str], None],
model_weak,
stage_weak,
layer_weak=None,
file_exts: Tuple[Tuple[str, str]] = None,
frame=None,
multi_selection: bool = False,
on_selected_fn=None,
):
model = model_weak()
if not model:
return
navigate_to = None
fallback = None
if isinstance(model, SdfAssetPathAttributeModel):
navigate_to = model.get_resolved_path()
if navigate_to:
navigate_to = f"{omni.usd.correct_filename_case(os.path.dirname(navigate_to))}/{os.path.basename(navigate_to)}"
elif isinstance(model, ui.AbstractValueModel):
if not hasattr(model, "is_array_type") or not model.is_array_type():
navigate_to = model.get_value_as_string()
if navigate_to is None:
stage = stage_weak()
if stage and not stage.GetRootLayer().anonymous:
# If asset path is empty, open the USD rootlayer folder
# But only if filepicker didn't already have a folder remembered (thus fallback)
fallback = stage.GetRootLayer().identifier
if layer_weak:
layer = layer_weak()
if layer:
navigate_to = layer.ComputeAbsolutePath(navigate_to)
if navigate_to:
navigate_to = replace_query(navigate_to, None)
file_importer = get_file_importer()
if file_importer:
file_exts = None
if isinstance(model, SdfAssetPathAttributeModel):
custom_data = model.metadata.get(Sdf.PrimSpec.CustomDataKey, {})
file_exts_dict = custom_data.get("fileExts", {})
file_exts = tuple((key, value) for (key, value) in file_exts_dict.items())
if not file_exts:
file_exts = (DEFAULT_FILE_EXTS,)
def on_import(model_weak, stage_weak, filename, dirname, selections=[]):
paths = selections.copy()
if not paths:
# fallback to filename
paths.append(omni.client.combine_urls(dirname, filename))
# get_current_selections comes in random (?) order, it does not follow selection order. sort it so
# at least the result is ordered alphabetically.
paths.sort()
if not multi_selection:
paths = paths[-1:]
async def check_paths(paths):
for path in paths:
result, entry = await omni.client.stat_async(path)
if result == omni.client.Result.OK:
if (
file_exts
and file_exts != (DEFAULT_FILE_EXTS,)
and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN
):
carb.log_warn("Please select a file, not a folder!")
return
else:
carb.log_warn(f"Selected file {path} does not exist!")
return
asyncio.ensure_future(check_paths(paths))
if on_selected_fn:
on_selected_fn(stage_weak, model_weak, "\n".join(paths), assign_value_fn, frame)
file_importer.show_window(
title=title,
import_button_label="Select",
import_handler=partial(on_import, model_weak, stage_weak),
file_extension_types=file_exts,
filename_url=navigate_to,
)
# fallback to a fallback directory if the filepicker dialog didn't have saved history
if fallback and not file_importer._dialog.get_current_directory():
file_importer._dialog.show(fallback)
def replace_query(url, new_query):
client_url = omni.client.break_url(url)
return omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
query=new_query,
fragment=client_url.fragment,
)
| 4,854 | Python | 34.181159 | 123 | 0.61166 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/variants_model.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.
#
from typing import List
import omni.kit.commands
import omni.ui as ui
from .usd_model_base import UsdBase
from pxr import Sdf, Usd
class VariantSetModel(ui.AbstractItemModel, UsdBase):
def __init__(self, stage: Usd.Stage, object_paths: List[Sdf.Path], variant_set_name: str, self_refresh: bool):
UsdBase.__init__(self, stage, object_paths, self_refresh, {})
ui.AbstractItemModel.__init__(self)
self._variant_set_name = variant_set_name
self._variant_names = []
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._variant_names
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self, item):
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
def set_value(self, value, comp=-1):
# if one than one item selected then don't early exit as
# anchor might be same but others may not
if value == self._value and len(self._variant_names) == 1:
return
omni.kit.commands.execute(
"SelectVariantPrim",
prim_path=self._object_paths,
vset_name=self._variant_set_name,
var_name=value,
)
def _current_index_changed(self, model):
if not self._has_index:
return
index = model.as_int
if self.set_value(self._variant_names[index].model.get_value_as_string()):
self._item_changed(None)
def _update_variant_names(self):
self._variant_names = []
vset = self._get_variant_set()
if vset:
vnames = vset.GetVariantNames()
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, name):
super().__init__()
self.model = ui.SimpleStringModel(name)
self._variant_names.append(AllowedTokenItem("")) # Empty variant
for name in vnames:
self._variant_names.append(AllowedTokenItem(name))
def _update_value(self, force=False):
if self._update_value_objects(force, self._get_objects()):
# TODO don't have to do this every time. Just needed when "VariantNames" actually changed
self._update_variant_names()
index = -1
for i in range(0, len(self._variant_names)):
if self._variant_names[i].model.get_value_as_string() == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._current_index.set_value(index)
self._item_changed(None)
def _on_dirty(self):
self._item_changed(None)
def _read_value(self, object: Usd.Object, time_code: Usd.TimeCode):
vsets = object.GetVariantSets()
vset = vsets.GetVariantSet(self._variant_set_name)
return vset.GetVariantSelection()
def _get_variant_set(self):
prims = self._get_objects()
prim = prims[0] if len(prims) > 0 else None
if prim:
vsets = prim.GetVariantSets()
return vsets.GetVariantSet(self._variant_set_name)
return None
# Temporary commands. Expected to be moved when we have better support for variants
class SelectVariantPrimCommand(omni.kit.commands.Command):
def __init__(self, prim_path: str, vset_name: str, var_name: str, usd_context_name: str = ""):
self._usd_context = omni.usd.get_context(usd_context_name)
self._prim_path = prim_path if isinstance(prim_path, list) else [prim_path]
self._vset_name = vset_name
self._var_name = var_name
def do(self):
stage = self._usd_context.get_stage()
self._previous_selection = {}
for prim_path in self._prim_path:
prim = stage.GetPrimAtPath(prim_path)
vset = prim.GetVariantSets().GetVariantSet(self._vset_name)
self._previous_selection[prim_path] = vset.GetVariantSelection()
if self._var_name:
vset.SetVariantSelection(self._var_name)
else:
vset.ClearVariantSelection()
def undo(self):
stage = self._usd_context.get_stage()
for prim_path in self._prim_path:
prim = stage.GetPrimAtPath(prim_path)
vset = prim.GetVariantSets().GetVariantSet(self._vset_name)
if prim_path in self._previous_selection:
vset.SetVariantSelection(self._previous_selection[prim_path])
else:
vset.ClearVariantSelection()
self._previous_selection = {}
omni.kit.commands.register_all_commands_in_module(__name__)
| 5,447 | Python | 34.148387 | 115 | 0.615385 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/prim_selection_payload.py | import weakref
from typing import List
from pxr import Sdf, Usd
class PrimSelectionPayload:
def __init__(self, stage: weakref.ReferenceType(Usd.Stage), paths: List[Sdf.Path]):
self._stage = stage # weakref
self._payload = paths
self._ignore_large_selection_override = False
import omni.kit.property.usd
self._large_selection_count = omni.kit.property.usd.get_large_selection_count()
def __len__(self):
# Ignore payload if stage is not valid anymore
if self._stage is None or self._stage() is None:
return 0
return len(self._payload)
# Forward calls to list to keep backward compatibility/easy access
def __iter__(self):
return self._payload.__iter__()
def __getitem__(self, key):
return self._payload.__getitem__(key)
def __setitem__(self, key, value):
return self._payload.__setitem__(key, value)
def __delitem__(self, key):
return self._payload.__delitem__(key)
def __bool__(self):
return self._stage is not None and self._stage() is not None and len(self._payload) > 0
def get_stage(self):
return self._stage() if self._stage else None # weakref -> ref
def get_paths(self) -> List[Sdf.Path]:
return self._payload
def set_large_selection_override(self, state: bool):
self._ignore_large_selection_override = state
def get_large_selection_count(self):
return self._large_selection_count
def is_large_selection(self) -> bool:
if not self._ignore_large_selection_override:
return bool(self._large_selection_count and len(self._payload) > self._large_selection_count)
return False
| 1,724 | Python | 30.363636 | 105 | 0.635151 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/variants_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from .usd_property_widget import UsdPropertiesWidget
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder
from .variants_model import VariantSetModel
from pxr import Tf, Usd
class VariantsWidget(UsdPropertiesWidget):
def __init__(self):
super().__init__(title="Variants", collapsed=False, multi_edit=False)
def reset(self):
if self._listener:
self._listener.Revoke()
self._listener = None
super().reset()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload:
return False
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim:
return False
if not prim.HasVariantSets():
return False
return True
def build_items(self):
self.reset()
if len(self._payload) == 0:
return
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
stage = last_prim.GetStage()
if not stage:
return
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
vsets = last_prim.GetVariantSets()
set_names = set(vsets.GetNames())
# remove any lists elements that are not common
for prim_path in self._payload:
prim = self._get_prim(prim_path)
set_names = set_names & set(prim.GetVariantSets().GetNames())
with ui.VStack():
for name in set_names:
self._build_variant_set(stage, last_prim.GetPath(), name)
def _build_variant_set(self, stage, prim_path, name):
with ui.HStack():
UsdPropertiesWidgetBuilder._create_label(name)
model = VariantSetModel(stage, self._payload.get_paths(), name, False)
with ui.ZStack(alignment=ui.Alignment.CENTER):
combo_widget = ui.ComboBox(model)
combo_widget.identifier = f"combo_variant_{name.lower()}"
mixed_widget = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
mixed_widget.identifier = f"mixed_variant_{name.lower()}"
if model.is_ambiguous():
mixed_widget.visible = True
| 2,875 | Python | 31.314606 | 99 | 0.619478 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/prim_path_widget.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 weakref
from functools import lru_cache
from typing import Callable
import carb
import omni.ui as ui
import omni.usd
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH, SimplePropertyWidget
from .add_attribute_popup import AddAttributePopup
from .context_menu import ContextMenu, ContextMenuEvent
from .prim_selection_payload import PrimSelectionPayload
g_singleton = None
@lru_cache()
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
class Constant:
def __setattr__(self, name, value):
raise Exception(f"Can't change Constant.{name}")
MIXED = "Mixed"
MIXED_COLOR = 0xFFCC9E61
LABEL_COLOR = 0xFF9E9E9E
LABEL_FONT_SIZE = 14
LABEL_WIDTH = 80
ADD_BUTTON_SIZE = 52
class ButtonMenuEntry:
def __init__(
self,
path: str,
glyph: str = None,
name_fn: Callable = None,
show_fn: Callable = None,
enabled_fn: Callable = None,
onclick_fn: Callable = None,
add_to_context_menu: bool = False,
):
self.path = path
self.glyph = glyph
self.name_fn = name_fn
self.show_fn = show_fn
self.enabled_fn = enabled_fn
self.onclick_fn = onclick_fn
if add_to_context_menu:
self.context_menu = omni.kit.context_menu.add_menu(self.get_context_menu(), "ADD", "")
else:
self.context_menu = None
def clean(self):
self.context_menu = None
def get_dict(self, payload, name=None):
data = {}
if name:
data = {"name": name}
else:
data = {"name": self.path}
data["glyph"] = self.glyph
if self.name_fn:
data["name_fn"] = self.name_fn
if self.show_fn:
data["show_fn"] = self.show_fn
if self.enabled_fn:
data["enabled_fn"] = self.enabled_fn
if self.onclick_fn:
data["onclick_fn"] = lambda o, p=payload: self.onclick_fn(payload=p)
return data
def get_context_menu(self):
menu_sublist = []
sublist = menu_sublist
parts = self.path.split("/")
if len(parts) > 1:
last_name = parts.pop()
first_name = parts.pop(0)
context_root = {'name': { first_name: []}}
context_item = context_root["name"][first_name]
while parts:
name = parts.pop(0)
context_item.append({'name': {name: []}})
context_item = context_item[0]["name"][name]
context_item.append({
"name": last_name,
"glyph": self.glyph,
"name_fn": self.name_fn,
"show_fn": self.show_fn,
"enabled_fn": self.enabled_fn,
"onclick_fn": lambda o, f=weakref.ref(
self.onclick_fn
) if self.onclick_fn else None: PrimPathWidget.payload_wrapper(
objects=o, onclick_fn_weak=f
),
})
return context_root
else:
context_item = {
"name": self.path,
"glyph": self.glyph,
"name_fn": self.name_fn,
"show_fn": self.show_fn,
"enabled_fn": self.enabled_fn,
"onclick_fn": lambda o, f=weakref.ref(
self.onclick_fn
) if self.onclick_fn else None: PrimPathWidget.payload_wrapper(objects=o, onclick_fn_weak=f),
}
return context_item
class PrimPathWidget(SimplePropertyWidget):
def __init__(self):
super().__init__(title="Path", collapsable=False)
self._context_menu = ContextMenu()
self._path_draw_items = []
self._button_menu_items = []
self._path_item_padding = 0.0
global g_singleton
g_singleton = self
self.add_path_item(self._build_prim_name_widget)
self.add_path_item(self._build_prim_path_widget)
# self.add_path_item(self._build_prim_stage_widget)
self.add_path_item(self._build_prim_instanceable_widget)
self.add_path_item(self._build_prim_large_selection_widget)
self._add_create_attribute_menu()
def __del__(self):
global g_singleton
g_singleton = None
def clean(self):
self._path_draw_items = []
if self._add_attribute_popup:
self._add_attribute_popup.destroy()
self._add_attribute_popup = None
super().clean()
def on_new_payload(self, payload):
if not super().on_new_payload(payload, ignore_large_selection=True):
return False
self._anchor_prim = None
stage = payload.get_stage()
instance = []
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
self._anchor_prim = prim
instance.append(prim.IsInstanceable())
self._show_instance = len(set(instance)) == 1
return payload and len(payload) > 0
@staticmethod
def payload_wrapper(objects, onclick_fn_weak):
onclick_fn = onclick_fn_weak()
if onclick_fn:
prim_paths = []
if "prim_list" in objects:
prim_paths = [prim.GetPath() for prim in objects["prim_list"]]
payload = PrimSelectionPayload(weakref.ref(objects["stage"]), prim_paths)
onclick_fn(payload=payload)
def build_items(self):
for item in self._path_draw_items:
item()
def _build_prim_name_widget(self):
from omni.kit.property.usd.usd_property_widget import get_ui_style
def get_names_as_string(prim_paths):
paths = ""
for index, path in enumerate(prim_paths):
paths += f"{path.name}\n"
return paths
prim_paths = self._payload
selected_info_name = "(nothing selected)"
stage = self._payload.get_stage()
tooltip = ""
if len(prim_paths) > 1:
selected_info_name = f"({len(prim_paths)} models selected) common attributes shown"
for index, path in enumerate(prim_paths):
tooltip += f"{path.name}\n"
if index > 9:
tooltip += f"...."
break
elif len(prim_paths) == 1:
selected_info_name = f"{prim_paths[0].name}"
with ui.HStack(height=0):
weakref_menu = weakref.ref(self._context_menu)
ui.Spacer(width=8)
button_width = Constant.ADD_BUTTON_SIZE
if get_ui_style() == "NvidiaLight":
button_width = Constant.ADD_BUTTON_SIZE + 25
add_button = ui.Button(f"{_get_plus_glyph()} Add", width=button_width, height=LABEL_HEIGHT, name="add")
add_button.set_mouse_pressed_fn(
lambda x, y, b, m, widget=add_button: self._on_mouse_pressed(b, weakref_menu, widget)
)
ui.Spacer(width=(Constant.LABEL_WIDTH + self._path_item_padding) - button_width)
ui.Spacer(width=8)
if get_ui_style() == "NvidiaLight":
ui.Spacer(width=10)
widget = ui.StringField(
name="prims_name", height=LABEL_HEIGHT, tooltip=tooltip, tooltip_offset_y=22, enabled=False
)
widget.model.set_value(selected_info_name)
widget.set_mouse_pressed_fn(
lambda x, y, b, m, model=widget.model: self._build_copy_menu(
buttons=b,
context_menu=weakref_menu,
copy_fn=lambda _: self._copy_to_clipboard(to_copy=get_names_as_string(prim_paths=prim_paths)),
)
)
def _build_prim_path_widget(self):
from omni.kit.property.usd.usd_property_widget import get_ui_style
def get_paths_as_string(prim_paths):
paths = ""
for index, path in enumerate(prim_paths):
paths += f"{path}\n"
return paths
prim_paths = self._payload
weakref_menu = weakref.ref(self._context_menu)
selected_info_name = ""
tooltip = ""
style = {}
if len(prim_paths) == 1:
selected_info_name = f"{prim_paths[0]}"
elif len(prim_paths) > 1:
selected_info_name = Constant.MIXED
style = {"Field": {"color": Constant.MIXED_COLOR}, "Tooltip": {"color": 0xFF333333}}
for index, path in enumerate(prim_paths):
tooltip += f"{path}\n"
if index > 9:
tooltip += f"...."
break
with ui.HStack(height=0):
ui.Spacer(width=8)
ui.Label(
"Prim Path",
name="path_label",
width=Constant.LABEL_WIDTH + self._path_item_padding,
height=LABEL_HEIGHT,
style={"font_size": Constant.LABEL_FONT_SIZE},
)
ui.Spacer(width=8)
if get_ui_style() == "NvidiaLight":
ui.Spacer(width=10)
widget = ui.StringField(
name="prims_path", height=LABEL_HEIGHT, enabled=False, tooltip=tooltip, tooltip_offset_y=22, style=style
)
widget.model.set_value(selected_info_name)
widget.set_mouse_pressed_fn(
lambda x, y, b, m: self._build_copy_menu(
buttons=b,
context_menu=weakref_menu,
copy_fn=lambda _: self._copy_to_clipboard(to_copy=get_paths_as_string(prim_paths=prim_paths)),
)
)
def _build_prim_stage_widget(self):
from omni.kit.property.usd.usd_property_widget import get_ui_style
stage_path = "unsaved"
stage = self._payload.get_stage()
weakref_menu = weakref.ref(self._context_menu)
if stage and stage.GetRootLayer() and stage.GetRootLayer().realPath:
stage_path = stage.GetRootLayer().realPath
with ui.HStack(height=0):
ui.Spacer(width=8)
ui.Label(
"Stage Path",
name="stage_label",
width=Constant.LABEL_WIDTH + self._path_item_padding,
height=LABEL_HEIGHT,
style={"font_size": Constant.LABEL_FONT_SIZE},
)
ui.Spacer(width=8)
widget = ui.StringField(name="prims_stage", height=LABEL_HEIGHT, enabled=False)
widget.model.set_value(stage_path)
widget.set_mouse_pressed_fn(
lambda x, y, b, m, model=widget.model: self._build_copy_menu(
buttons=b,
context_menu=weakref_menu,
copy_fn=lambda _: self._copy_to_clipboard(to_copy=model.as_string),
)
)
def _build_prim_instanceable_widget(self):
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder, get_ui_style
if not self._anchor_prim or not self._show_instance:
return
def on_instanceable_changed(model):
index = model.as_bool
stage = self._payload.get_stage()
for path in self._payload:
prim = stage.GetPrimAtPath(path)
if prim:
prim.SetInstanceable(model.as_bool)
self._collapsable_frame.rebuild()
additional_label_kwargs = {}
with ui.HStack(spacing=HORIZONTAL_SPACING):
settings = carb.settings.get_settings()
left_aligned = settings.get("ext/omni.kit.window.property/checkboxAlignment") == "left"
if not left_aligned:
additional_label_kwargs["width"] = 0
else:
additional_label_kwargs["width"] = (Constant.LABEL_WIDTH + self._path_item_padding) - 8
if get_ui_style() == "NvidiaLight":
additional_label_kwargs["word_wrap"] = False
ui.Spacer(width=3)
UsdPropertiesWidgetBuilder._create_label("Instanceable", {}, additional_label_kwargs)
if not left_aligned:
ui.Spacer(width=15)
else:
ui.Spacer(width=0)
with ui.VStack(width=10):
ui.Spacer()
check_box = ui.CheckBox(width=10, height=0, name="greenCheck")
check_box.model.set_value(self._anchor_prim.IsInstanceable())
check_box.model.add_value_changed_fn(on_instanceable_changed)
ui.Spacer()
if left_aligned:
ui.Spacer(width=5)
def _build_prim_large_selection_widget(self):
def show_all():
if self._payload:
self._payload.set_large_selection_override(True)
property_window = omni.kit.window.property.get_window()
if property_window:
property_window.request_rebuild()
if self._payload.is_large_selection():
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
ui.Separator()
UsdPropertiesWidgetBuilder._create_label(
f"You have selected {len(self._payload)} Prims, to preserve fast performance the Property Widget is not showing above the current limit of {self._payload.get_large_selection_count()} Prims. Press the button below to show it anyway but expect it to take some time",
{},
additional_label_kwargs={"width": omni.ui.Percent(100), "alignment": ui.Alignment.CENTER},
)
ui.Button("Skip Large Selection Protection", clicked_fn=lambda: show_all())
def _add_create_attribute_menu(self):
self._add_attribute_popup = AddAttributePopup()
self.add_button_menu_entry(
"Attribute",
show_fn=lambda objects, weak_self=weakref.ref(self): weak_self()._add_attribute_popup.show_fn(objects)
if weak_self()
else None,
onclick_fn=lambda payload, weak_self=weakref.ref(self): weak_self()._add_attribute_popup.click_fn(payload)
if weak_self()
else None,
)
def _on_mouse_pressed(self, button, context_menu, widget):
"""Called when the user press the mouse button on the item"""
if button != 0:
# It's for LMB menu only
return
if not context_menu():
return
# Show the menu
xpos = (int)(widget.screen_position_x)
ypos = (int)(widget.screen_position_y + widget.computed_content_height)
context_menu().on_mouse_event(ContextMenuEvent(self._payload, self._button_menu_items, xpos, ypos))
def _build_copy_menu(self, buttons, context_menu, copy_fn):
if buttons != 1:
# It's for right mouse button for menu only
return
if not context_menu():
return
# setup menu
menu_list = [{"name": "Copy to clipboard", "glyph": "menu_link.svg", "onclick_fn": copy_fn}]
# show menu
context_menu().show_context_menu(menu_list=menu_list)
def _copy_to_clipboard(self, to_copy):
omni.kit.clipboard.copy(to_copy)
@staticmethod
def add_button_menu_entry(
path: str,
glyph: str = None,
name_fn=None,
show_fn: Callable = None,
enabled_fn: Callable = None,
onclick_fn: Callable = None,
add_to_context_menu: bool = True,
):
item = None
if g_singleton:
item = ButtonMenuEntry(path, glyph, name_fn, show_fn, enabled_fn, onclick_fn, add_to_context_menu)
g_singleton._button_menu_items.append(item)
else:
carb.log_error(f"PrimPathWidget not initalized")
return item
@staticmethod
def remove_button_menu_entry(item: ButtonMenuEntry):
if g_singleton:
g_singleton._button_menu_items.remove(item)
item.clean()
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def get_button_menu_entries():
if g_singleton:
return g_singleton._button_menu_items
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def add_path_item(draw_fn: Callable):
if g_singleton:
g_singleton._path_draw_items.append(draw_fn)
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def remove_path_item(draw_fn: Callable):
if g_singleton:
g_singleton._path_draw_items.remove(draw_fn)
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def get_path_items():
if g_singleton:
return g_singleton._path_draw_items
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def rebuild():
if g_singleton:
if g_singleton._collapsable_frame:
g_singleton._collapsable_frame.rebuild()
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def set_path_item_padding(padding: float):
if g_singleton:
g_singleton._path_item_padding = padding
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def get_path_item_padding(padding: float):
if g_singleton:
return g_singleton._path_item_padding
else:
carb.log_error(f"PrimPathWidget not initalized")
return 0.0
| 18,264 | Python | 35.53 | 280 | 0.559735 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/__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 .widgets import *
from .message_bus_events import *
def get_large_selection_count():
import carb.settings
return carb.settings.get_settings().get("/persistent/exts/omni.kit.property.usd/large_selection")
| 653 | Python | 37.470586 | 101 | 0.787136 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_attribute_widget.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.
#
from omni.kit.window.property.templates import SimplePropertyWidget, build_frame_header
from .usd_property_widget_builder import *
from collections import defaultdict, OrderedDict
from .usd_property_widget import *
import asyncio
import carb
import omni.ui as ui
import omni.usd
from typing import List, Dict
from pxr import Usd, Tf, Sdf
class UsdAttributeUiEntry(UsdPropertyUiEntry):
def __init__(
self,
attr_name: str,
display_group: str,
metadata,
property_type,
build_fn=None,
display_group_collapsed: bool = False,
prim_paths: List[Sdf.Path] = None,
):
super().__init__(
attr_name, display_group, metadata, property_type, build_fn, display_group_collapsed, prim_paths
)
class UsdAttributesWidget(UsdPropertiesWidget):
"""
DEPRECATED! KEEP FOR BACKWARD COMPATIBILITY. Use UsdPropertiesWidget instead.
UsdAttributesWidget provides functionalities to automatically populates UsdAttributes on given prim(s). The UI will
and models be generated according to UsdAttributes's value type. Multi-prim editing works for shared Attributes
between all selected prims if instantiated with multi_edit = True.
"""
def __init__(self, title: str, collapsed: bool, multi_edit: bool = True):
"""
Constructor.
Args:
title: title of the widget.
collapsed: whether the collapsable frame should be collapsed for this widget.
multi_edit: whether multi-editing is supported.
If False, properties will only be collected from the last selected prim.
If True, shared properties among all selected prims will be collected.
"""
super().__init__(title, collapsed, multi_edit)
def build_attribute_item(self, stage, ui_attr: UsdAttributeUiEntry, prim_paths: List[Sdf.Path]):
return super().build_property_item(stage, ui_attr, prim_paths)
def _filter_attrs_to_build(self, attrs):
return super()._filter_props_to_build(attrs)
def _customize_attrs_layout(self, attrs):
return super()._customize_props_layout(attrs)
def _get_shared_attributes_from_selected_prims(self, anchor_prim):
return super()._get_shared_properties_from_selected_prims(anchor_prim)
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
return self.build_attribute_item(stage, ui_prop, prim_paths)
def _filter_props_to_build(self, props):
return self._filter_attrs_to_build(props)
def _customize_props_layout(self, props):
return self._customize_attrs_layout(props)
def _get_shared_properties_from_selected_prims(self, anchor_prim):
return self._get_shared_attributes_from_selected_prims(anchor_prim)
class SchemaAttributesWidget(SchemaPropertiesWidget):
"""
DEPRECATED! KEEP FOR BACKWARD COMPATIBILITY. Use SchemaPropertiesWidget instead.
SchemaAttributesWidget only filters attributes and only show the onces from a given IsA schema or applied API schema.
"""
def __init__(self, title: str, schema, include_inherited: bool):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
include_inherited (bool): Whether the filter should include inherited attributes.
"""
super().__init__(title, schema, include_inherited)
def build_attribute_item(self, stage, ui_attr: UsdAttributeUiEntry, prim_paths: List[Sdf.Path]):
return super().build_property_item(stage, ui_attr, prim_paths)
def _filter_attrs_to_build(self, attrs):
return super()._filter_props_to_build(attrs)
def _customize_attrs_layout(self, attrs):
return super()._customize_props_layout(attrs)
def _get_shared_attributes_from_selected_prims(self, anchor_prim):
return super()._get_shared_properties_from_selected_prims(anchor_prim)
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
return self.build_attribute_item(stage, ui_prop, prim_paths)
def _filter_props_to_build(self, props):
return self._filter_attrs_to_build(props)
def _customize_props_layout(self, props):
return self._customize_attrs_layout(props)
def _get_shared_properties_from_selected_prims(self, anchor_prim):
return self._get_shared_attributes_from_selected_prims(anchor_prim)
class MultiSchemaAttributesWidget(MultiSchemaPropertiesWidget):
"""
DEPRECATED! KEEP FOR BACKWARD COMPATIBILITY. Use MultiSchemaPropertiesWidget instead.
MultiSchemaAttributesWidget filters attributes and only show the onces from a given IsA schema or schema subclass list.
"""
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
def build_attribute_item(self, stage, ui_attr: UsdAttributeUiEntry, prim_paths: List[Sdf.Path]):
return super().build_property_item(stage, ui_attr, prim_paths)
def _filter_attrs_to_build(self, attrs):
return super()._filter_props_to_build(attrs)
def _customize_attrs_layout(self, attrs):
return super()._customize_props_layout(attrs)
def _get_shared_attributes_from_selected_prims(self, anchor_prim):
return super()._get_shared_properties_from_selected_prims(anchor_prim)
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
return self.build_attribute_item(stage, ui_prop, prim_paths)
def _filter_props_to_build(self, props):
return self._filter_attrs_to_build(props)
def _customize_props_layout(self, props):
return self._customize_attrs_layout(props)
def _get_shared_properties_from_selected_prims(self, anchor_prim):
return self._get_shared_attributes_from_selected_prims(anchor_prim)
| 6,973 | Python | 39.08046 | 123 | 0.695397 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_property_widget_builder.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import fnmatch
import weakref
from functools import lru_cache
from typing import Any, Callable, List
import carb
import carb.settings
import omni.client
import omni.kit.ui
import omni.ui as ui
import omni.usd
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH, LABEL_WIDTH_LIGHT
from omni.kit.window.file_importer import get_file_importer
from pxr import Ar, Sdf, Usd
from .asset_filepicker import show_asset_file_picker
from .attribute_context_menu import AttributeContextMenu, AttributeContextMenuEvent
from .control_state_manager import ControlStateManager
from .relationship import RelationshipEditWidget
from .usd_attribute_model import (
GfVecAttributeModel,
GfVecAttributeSingleChannelModel,
MdlEnumAttributeModel,
SdfAssetPathArrayAttributeItemModel,
SdfAssetPathAttributeModel,
SdfTimeCodeModel,
TfTokenAttributeModel,
UsdAttributeModel,
)
from .usd_object_model import MetadataObjectModel
from .widgets import ICON_PATH
@lru_cache()
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
def get_ui_style():
return carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
def get_model_cls(cls, args, key="model_cls"):
if args:
return args.get(key, cls)
return cls
def get_model_kwargs(args, key="model_kwargs"):
if args:
return args.get(key, {})
return {}
class UsdPropertiesWidgetBuilder:
# We don't use Tf.Type.FindByName(name) directly because the name depends
# on the compiler. For example the line `Sdf.ValueTypeNames.Int64.type`
# resolves to `Tf.Type.FindByName('long')` on Linux and on Windows it's
# `Tf.Type.FindByName('__int64')`.
tf_half = Sdf.ValueTypeNames.Half.type
tf_float = Sdf.ValueTypeNames.Float.type
tf_double = Sdf.ValueTypeNames.Double.type
tf_uchar = Sdf.ValueTypeNames.UChar.type
tf_uint = Sdf.ValueTypeNames.UInt.type
tf_int = Sdf.ValueTypeNames.Int.type
tf_int64 = Sdf.ValueTypeNames.Int64.type
tf_uint64 = Sdf.ValueTypeNames.UInt64.type
tf_bool = Sdf.ValueTypeNames.Bool.type
tf_string = Sdf.ValueTypeNames.String.type
tf_gf_vec2i = Sdf.ValueTypeNames.Int2.type
tf_gf_vec2h = Sdf.ValueTypeNames.Half2.type
tf_gf_vec2f = Sdf.ValueTypeNames.Float2.type
tf_gf_vec2d = Sdf.ValueTypeNames.Double2.type
tf_gf_vec3i = Sdf.ValueTypeNames.Int3.type
tf_gf_vec3h = Sdf.ValueTypeNames.Half3.type
tf_gf_vec3f = Sdf.ValueTypeNames.Float3.type
tf_gf_vec3d = Sdf.ValueTypeNames.Double3.type
tf_gf_vec4i = Sdf.ValueTypeNames.Int4.type
tf_gf_vec4h = Sdf.ValueTypeNames.Half4.type
tf_gf_vec4f = Sdf.ValueTypeNames.Float4.type
tf_gf_vec4d = Sdf.ValueTypeNames.Double4.type
tf_tf_token = Sdf.ValueTypeNames.Token.type
tf_sdf_asset_path = Sdf.ValueTypeNames.Asset.type
tf_sdf_time_code = Sdf.ValueTypeNames.TimeCode.type
# array type builders
tf_sdf_asset_array_path = Sdf.ValueTypeNames.AssetArray.type
@classmethod
def init_builder_table(cls):
cls.widget_builder_table = {
cls.tf_half: cls._floating_point_builder,
cls.tf_float: cls._floating_point_builder,
cls.tf_double: cls._floating_point_builder,
cls.tf_uchar: cls._integer_builder,
cls.tf_uint: cls._integer_builder,
cls.tf_int: cls._integer_builder,
cls.tf_int64: cls._integer_builder,
cls.tf_uint64: cls._integer_builder,
cls.tf_bool: cls._bool_builder,
cls.tf_string: cls._string_builder,
cls.tf_gf_vec2i: cls._vec2_per_channel_builder,
cls.tf_gf_vec2h: cls._vec2_per_channel_builder,
cls.tf_gf_vec2f: cls._vec2_per_channel_builder,
cls.tf_gf_vec2d: cls._vec2_per_channel_builder,
cls.tf_gf_vec3i: cls._vec3_per_channel_builder,
cls.tf_gf_vec3h: cls._vec3_per_channel_builder,
cls.tf_gf_vec3f: cls._vec3_per_channel_builder,
cls.tf_gf_vec3d: cls._vec3_per_channel_builder,
cls.tf_gf_vec4i: cls._vec4_per_channel_builder,
cls.tf_gf_vec4h: cls._vec4_per_channel_builder,
cls.tf_gf_vec4f: cls._vec4_per_channel_builder,
cls.tf_gf_vec4d: cls._vec4_per_channel_builder,
cls.tf_tf_token: cls._tftoken_builder,
cls.tf_sdf_asset_path: cls._sdf_asset_path_builder,
cls.tf_sdf_time_code: cls._time_code_builder,
# array type builders
cls.tf_sdf_asset_array_path: cls._sdf_asset_path_array_builder,
}
cls.reset_builder_coverage_table()
@classmethod
def reset_builder_coverage_table(cls):
cls.widget_builder_coverage_table = {
cls.tf_half: False,
cls.tf_float: False,
cls.tf_double: False,
cls.tf_uchar: False,
cls.tf_uint: False,
cls.tf_int: False,
cls.tf_int64: False,
cls.tf_uint64: False,
cls.tf_bool: False,
cls.tf_string: False,
cls.tf_gf_vec2i: False,
cls.tf_gf_vec2h: False,
cls.tf_gf_vec2f: False,
cls.tf_gf_vec2d: False,
cls.tf_gf_vec3i: False,
cls.tf_gf_vec3h: False,
cls.tf_gf_vec3f: False,
cls.tf_gf_vec3d: False,
cls.tf_gf_vec4i: False,
cls.tf_gf_vec4h: False,
cls.tf_gf_vec4f: False,
cls.tf_gf_vec4d: False,
cls.tf_tf_token: False,
cls.tf_sdf_asset_path: False,
cls.tf_sdf_time_code: False,
cls.tf_sdf_asset_array_path: False,
}
@classmethod
def startup(cls):
cls.init_builder_table()
cls.default_range_steps = {}
@classmethod
def shutdown(cls):
pass
@classmethod
def build(
cls,
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
if property_type == Usd.Attribute:
type_name = cls._get_type_name(metadata)
tf_type = type_name.type
build_func = cls.widget_builder_table.get(tf_type, cls._fallback_builder)
cls.widget_builder_coverage_table[tf_type] = True
return build_func(
stage, attr_name, type_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
elif property_type == Usd.Relationship:
return cls._relationship_builder(
stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
###### builder funcs ######
@classmethod
def _relationship_builder(
cls,
stage,
attr_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
cls._create_label(attr_name, metadata, additional_label_kwargs)
return RelationshipEditWidget(stage, attr_name, prim_paths, additional_widget_kwargs)
@classmethod
def _fallback_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
kwargs = {
"name": "models_readonly",
"model": model,
"enabled": False,
"tooltip": model.get_value_as_string(),
}
if additional_widget_kwargs:
kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(**kwargs)
value_widget.identifier = f"fallback_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **kwargs, label=label)
return model
@classmethod
def _floating_point_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs
)
# insert hard-range min/max before soft-range
widget_kwargs = {"model": model}
widget_kwargs.update(model_kwargs)
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
if soft_range_min < soft_range_max:
value_widget = cls._create_drag_or_slider(ui.FloatDrag, ui.FloatDrag, **widget_kwargs)
cls._setup_soft_float_dynamic_range(attr_name, metadata, value_widget.step, model, value_widget)
else:
value_widget = cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
value_widget.identifier = f"float_slider_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _integer_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
is_mdl_enum = False
if metadata.get("renderType", None):
sdr_metadata = metadata.get("sdrMetadata", None)
if sdr_metadata and sdr_metadata.get("options", None):
is_mdl_enum = True
if is_mdl_enum:
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(MdlEnumAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "choices", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
else:
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
if type_name.type == cls.tf_uint:
model_kwargs["min"] = 0
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs
)
# insert hard-range min/max before soft-range
widget_kwargs = {"model": model}
widget_kwargs.update(model_kwargs)
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = cls._create_drag_or_slider(ui.IntDrag, ui.IntSlider, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
value_widget.identifier = f"integer_slider_{attr_name}"
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _bool_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
settings = carb.settings.get_settings()
left_aligned = settings.get("ext/omni.kit.window.property/checkboxAlignment") == "left"
if not left_aligned:
if not additional_label_kwargs:
additional_label_kwargs = {}
additional_label_kwargs["width"] = 0
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if not left_aligned:
ui.Spacer(width=10)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=5)
with ui.VStack(width=10):
ui.Spacer()
widget_kwargs = {"width": 10, "height": 0, "name": "greenCheck", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=-2):
value_widget = ui.CheckBox(**widget_kwargs)
value_widget.identifier = f"bool_{attr_name}"
with ui.Placer(offset_x=1, offset_y=-1):
mixed_overlay = ui.Rectangle(
height=8, width=8, name="mixed_overlay", alignment=ui.Alignment.CENTER, visible=False
)
ui.Spacer()
if left_aligned:
ui.Spacer(width=5)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _string_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
model = cls._create_filepath_for_ui_type(
stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
if model:
return model
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "string"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(model, **widget_kwargs)
value_widget.identifier = f"string_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _vec2_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
): # pragma: no cover
"""
The entire vector is built as one multi-drag field
"""
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
model_cls = get_model_cls(GfVecAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
2,
type_name.type,
False,
metadata,
**model_kwargs,
)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
create_drag_fn = (
cls._create_multi_int_drag_with_labels
if type_name.type.typeName.endswith("i")
else cls._create_multi_float_drag_with_labels
)
value_widget, mixed_overlay = create_drag_fn(
labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371)], comp_count=2, **widget_kwargs
)
value_widget.identifier = f"vec2_{attr_name}"
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _vec2_per_channel_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""
The vector is split into components and each one has their own drag field and status control
"""
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if (
custom_data
and "mdl" in custom_data
and "type" in custom_data["mdl"]
and custom_data["mdl"]["type"] == "bool2"
):
return cls._create_bool_per_channel(
stage,
attr_name,
prim_paths,
2,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
else:
return cls._create_color_or_drag_per_channel(
stage,
attr_name,
prim_paths,
2,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
@classmethod
def _vec3_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
): # pragma: no cover
"""
The entire vector is built as one multi-drag field
"""
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
return cls._create_color_or_multidrag(
stage, attr_name, prim_paths, 3, type_name, type_name.type, metadata, label, additional_widget_kwargs
)
@classmethod
def _vec3_per_channel_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""
The vector is split into components and each one has their own drag field and status control
"""
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if (
custom_data
and "mdl" in custom_data
and "type" in custom_data["mdl"]
and custom_data["mdl"]["type"] == "bool3"
):
return cls._create_bool_per_channel(
stage,
attr_name,
prim_paths,
3,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
else:
return cls._create_color_or_drag_per_channel(
stage,
attr_name,
prim_paths,
3,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
@classmethod
def _vec4_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
): # pragma: no cover
"""
The entire vector is built as one multi-drag field
"""
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
return cls._create_color_or_multidrag(
stage, attr_name, prim_paths, 4, type_name, type_name.type, metadata, label, additional_widget_kwargs
)
@classmethod
def _vec4_per_channel_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""
The vector is split into components and each one has their own drag field and status control
"""
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if (
custom_data
and "mdl" in custom_data
and "type" in custom_data["mdl"]
and custom_data["mdl"]["type"] == "bool4"
):
return cls._create_bool_per_channel(
stage,
attr_name,
prim_paths,
4,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
else:
return cls._create_color_or_drag_per_channel(
stage,
attr_name,
prim_paths,
4,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
@classmethod
def _tftoken_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
model = cls._create_filepath_for_ui_type(
stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
if model:
return model
with ui.HStack(spacing=HORIZONTAL_SPACING):
model = None
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
tokens = metadata.get("allowedTokens")
if tokens is not None and len(tokens) > 0:
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(TfTokenAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "choices"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
else:
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(
UsdAttributeModel, additional_widget_kwargs, key="no_allowed_tokens_model_cls"
)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "models"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(model, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
value_widget.identifier = f"token_{attr_name}"
cls._create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _build_asset_checkpoint_ui(cls, model, frame):
try:
from .versioning_helper import VersioningHelper
absolute_asset_path = model.get_resolved_path()
if VersioningHelper.is_versioning_enabled() and absolute_asset_path:
# Use checkpoint widget in the drop down menu for more detailed information
from omni.kit.widget.versioning.checkpoint_combobox import CheckpointCombobox
spacer = ui.Spacer(height=5)
stack = ui.HStack()
with stack:
UsdPropertiesWidgetBuilder._create_label("Checkpoint", additional_label_kwargs={"width": 80})
def on_selection_changed(model_or_item, model):
url = model.get_resolved_path()
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(model_or_item, CheckpointItem):
checkpoint = model_or_item.get_relative_path()
elif model_or_item is None:
checkpoint = ""
except Exception as e:
pass
client_url = omni.client.break_url(url)
new_path = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
query=checkpoint,
fragment=client_url.fragment,
)
if url != new_path:
model.set_value(new_path)
frame.rebuild()
checkpoint_combobox = CheckpointCombobox(
absolute_asset_path, lambda si, m=model: on_selection_changed(si, m)
)
# reset button
def reset_func(model):
on_selection_changed(None, model)
frame.rebuild()
checkpoint = ""
client_url = omni.client.break_url(model.get_resolved_path())
if client_url.query:
_, checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
ui.Spacer(width=4)
ui.Image(
f"{ICON_PATH}/Default value.svg" if checkpoint == "" else f"{ICON_PATH}/Changed value.svg",
mouse_pressed_fn=lambda x, y, b, a, m=model: reset_func(m),
width=12,
height=18,
tooltip="Reset Checkpoint" if checkpoint else "",
)
def on_have_server_info(server: str, support_checkpoint: bool, ui_items: list):
if not support_checkpoint:
for item in ui_items:
item.visible = False
VersioningHelper.check_server_checkpoint_support(
VersioningHelper.extract_server_from_url(absolute_asset_path),
lambda s, c, i=[spacer, stack]: on_have_server_info(s, c, i),
)
return None
except ImportError as e:
# If the widget is not available, create a simple combo box instead
carb.log_warn(f"Checkpoint widget in Asset is not available due to: {e}")
@classmethod
def _sdf_asset_path_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(SdfAssetPathAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
# List of models. It's possible that the path is texture related path, which
# will return colorSpace model also.
return cls._create_path_widget(
model, stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
@classmethod
def _sdf_asset_path_array_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
widget_kwargs = {"name": "models"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
models = []
class SdfAssetPathDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self):
super().__init__()
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
with ui.VStack():
ui.Spacer(height=2)
with ui.ZStack():
ui.Rectangle(name="backdrop")
frame = ui.Frame(
height=0,
spacing=5,
style={
"Frame": {"margin_width": 2, "margin_height": 2},
"Button": {"background_color": 0x0},
},
)
with frame:
(item_value_model, value_model) = model.get_item_value_model(item, column_id)
extra_widgets = []
with ui.HStack(spacing=HORIZONTAL_SPACING, width=ui.Percent(100)):
with ui.VStack(spacing=0, height=ui.Percent(100), width=0):
ui.Spacer()
# Create ||| grab area
grab = ui.HStack(
identifier=f"sdf_asset_array_{attr_name}[{item_value_model.index}].reorder_grab",
height=LABEL_HEIGHT,
)
with grab:
for i in range(3):
ui.Line(
width=3,
alignment=ui.Alignment.H_CENTER,
name="grab",
)
ui.Spacer()
# do a content_clipping for the rest of the widget so only dragging on the grab triggers
# reorder
with ui.HStack(content_clipping=1):
widget_kwargs["model"] = item_value_model
cls._build_path_field(
item_value_model, stage, attr_name, widget_kwargs, frame, extra_widgets
)
def remove_entry(index: int, value_model: UsdAttributeModel):
value = list(value_model.get_value())
new_value = value[:index] + value[index + 1 :]
value_model.set_value(new_value)
remove_style = {
"image_url": str(ICON_PATH.joinpath("remove.svg")),
"margin": 0,
"padding": 0,
}
ui.Spacer(width=HORIZONTAL_SPACING)
ui.Button(
"",
width=12,
height=ui.Percent(100),
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
clicked_fn=lambda index=item_value_model.index, value_model=value_model: remove_entry(
index, value_model
),
name="remove",
style=remove_style,
tooltip="Remove Asset",
identifier=f"sdf_asset_array_{attr_name}[{item_value_model.index}].remove",
)
ui.Spacer(height=2)
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
with ui.VStack():
delegate_cls = get_model_cls(SdfAssetPathDelegate, additional_widget_kwargs, key="delegate_cls")
delegate = delegate_cls()
model_cls = get_model_cls(SdfAssetPathArrayAttributeItemModel, additional_widget_kwargs)
item_model = model_cls(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, delegate
)
# content_clipping so drag n drop in tree view doesn't scroll the outer frame
tree_frame_stack = ui.HStack(spacing=HORIZONTAL_SPACING, content_clipping=1)
with tree_frame_stack:
with ui.Frame(height=0):
tree_view = ui.TreeView(
item_model,
delegate=delegate,
root_visible=False,
header_visible=False,
drop_between_items=True,
style={
"TreeView:selected": {"background_color": 0x00},
"TreeView": {"background_color": 0xFFFFFFFF}, # reorder indicator
},
)
tree_view.identifier = f"sdf_asset_array_{attr_name}"
ui.Spacer(width=12)
with ui.HStack(spacing=HORIZONTAL_SPACING, height=LABEL_HEIGHT):
extra_widgets = []
with ui.ZStack():
def assign_value_fn(model, path):
value = list(model.get_value())
value.append(Sdf.AssetPath(path))
model.set_value(Sdf.AssetPathArray(value))
button = ui.Button(
f"{_get_plus_glyph()} Add Asset...",
clicked_fn=lambda model_weak=weakref.ref(item_model.value_model), stage_weak=weakref.ref(
stage
): show_asset_file_picker(
"Select Asset...",
assign_value_fn,
model_weak,
stage_weak,
multi_selection=True,
on_selected_fn=cls._assign_asset_path_value
),
)
button.identifier = f"sdf_asset_array_{attr_name}.add_asset"
button.set_accept_drop_fn(
lambda url, model_weak=weakref.ref(item_model.value_model): cls.can_accept_file_drop(
url, model_weak, True
)
)
def on_drop_fn(event, model_weak):
model_weak = model_weak()
if not model_weak:
return
paths = event.mime_data.split("\n")
with omni.kit.undo.group():
for path in paths:
path = cls._convert_asset_path(path)
assign_value_fn(model_weak, path)
button.set_drop_fn(
lambda event, model_weak=weakref.ref(item_model.value_model): on_drop_fn(event, model_weak)
)
extra_widgets.append(button)
mixed_overlay = cls._create_mixed_text_overlay(content_clipping=1)
def on_model_value_changed(model: UsdAttributeModel):
value = model.get_value()
# hide treeview if mixed-editing or no node
tree_frame_stack.visible = not model.is_ambiguous() and bool(value)
button.visible = not model.is_ambiguous()
item_model.value_model.add_value_changed_fn(on_model_value_changed)
on_model_value_changed(item_model.value_model)
cls._create_control_state(
item_model.value_model,
value_widget=tree_view,
mixed_overlay=mixed_overlay,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
models.append(item_model)
return models
@classmethod
def _get_alignment(cls):
settings = carb.settings.get_settings()
return (
ui.Alignment.RIGHT
if settings.get("/ext/omni.kit.window.property/labelAlignment") == "right"
else ui.Alignment.LEFT
)
@classmethod
def _create_label(cls, attr_name, metadata=None, additional_label_kwargs=None):
alignment = cls._get_alignment()
label_kwargs = {
"name": "label",
"word_wrap": True,
"width": LABEL_WIDTH,
"height": LABEL_HEIGHT,
"alignment": alignment,
}
if get_ui_style() == "NvidiaLight":
label_kwargs["width"] = LABEL_WIDTH_LIGHT
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
if metadata and "tooltip" not in label_kwargs:
label_kwargs["tooltip"] = cls._generate_tooltip_string(attr_name, metadata)
label = ui.Label(cls._get_display_name(attr_name, metadata), **label_kwargs)
ui.Spacer(width=5)
return label
@classmethod
def _create_text_label(cls, attr_name, metadata=None, additional_label_kwargs=None):
alignment = cls._get_alignment()
label_kwargs = {
"name": "label",
"word_wrap": True,
"width": LABEL_WIDTH,
"height": LABEL_HEIGHT,
"alignment": alignment,
}
def open_url(url):
import webbrowser
webbrowser.open(url)
if get_ui_style() == "NvidiaLight":
label_kwargs["width"] = LABEL_WIDTH_LIGHT
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
if metadata and "tooltip" not in label_kwargs:
label_kwargs["tooltip"] = cls._generate_tooltip_string(attr_name, metadata)
display_name = cls._get_display_name(attr_name, metadata)
if display_name.startswith("http"):
label_kwargs["name"] = "url"
label = ui.StringField(**label_kwargs)
label.model.set_value(display_name)
label.set_mouse_pressed_fn(lambda x, y, b, m, url=display_name: open_url(url))
else:
label = ui.StringField(**label_kwargs)
label.model.set_value(display_name)
ui.Spacer(width=5)
return label
@classmethod
def _generate_tooltip_string(cls, attr_name, metadata):
doc_string = metadata.get(Sdf.PropertySpec.DocumentationKey)
type_name = cls._get_type_name(metadata)
tooltip = f"{attr_name} ({type_name})" if not doc_string else f"{attr_name} ({type_name})\n\t\t{doc_string}"
return tooltip
@classmethod
def _create_attribute_context_menu(cls, widget, model, comp_index=-1):
def show_attribute_context_menu(b, widget_ref, model_ref):
if b != 1:
return
if not model_ref:
return
if not widget_ref:
return
event = AttributeContextMenuEvent(
widget_ref,
model.get_attribute_paths(),
model_ref._stage,
model_ref.get_current_time_code(),
model_ref,
comp_index,
)
AttributeContextMenu.get_instance().on_mouse_event(event)
widget.set_mouse_pressed_fn(
lambda x, y, b, _: show_attribute_context_menu(b, weakref.proxy(widget), weakref.proxy(model))
)
###### helper funcs ######
@staticmethod
def _get_attr_value_range(metadata):
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
range = custom_data.get("range", {})
range_min = range.get("min", 0)
range_max = range.get("max", 0)
# TODO: IMGUI DragScalarN only support scalar range for all vector component.
# Need to change it to support per component range.
if hasattr(range_min, "__getitem__"):
range_min = range_min[0]
if hasattr(range_max, "__getitem__"):
range_max = range_max[0]
return range_min, range_max
@staticmethod
def _get_attr_value_ui_type(metadata):
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
return custom_data.get("uiType")
@classmethod
def _setup_soft_float_dynamic_range(cls, attr_name, metadata, default_step, model, widget):
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model)
if soft_range_min < soft_range_max:
def on_end_edit(model, widget, attr_name, metadata, soft_range_min, soft_range_max):
default_range = True
value = model.get_value()
# TODO: IMGUI DragScalarN only support scalar range for all vector component.
# Need to change it to support per component range.
if hasattr(value, "__getitem__"):
value = value[0]
if model._soft_range_min != None and model._soft_range_min < soft_range_min:
soft_range_min = model._soft_range_min
default_range = False
if model._soft_range_max != None and model._soft_range_max > soft_range_max:
soft_range_max = model._soft_range_max
default_range = False
if value < soft_range_min:
soft_range_min = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
default_range = False
if value > soft_range_max:
soft_range_max = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
default_range = False
widget.min = soft_range_min
widget.max = soft_range_max
if not default_range:
if not attr_name in cls.default_range_steps:
cls.default_range_steps[attr_name] = widget.step
widget.step = max(0.1, (soft_range_max - soft_range_min) / 1000.0)
def on_set_default(model, widget, attr_name, metadata):
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model, False)
widget.min = soft_range_min
widget.max = soft_range_max
if attr_name in cls.default_range_steps:
widget.step = cls.default_range_steps[attr_name]
model.add_end_edit_fn(
lambda m, w=widget, n=attr_name, md=metadata, min=soft_range_min, max=soft_range_max: on_end_edit(
m, w, n, md, min, max
)
)
model.set_on_set_default_fn(lambda m=model, w=widget, n=attr_name, md=metadata: on_set_default(m, w, n, md))
@classmethod
def _get_attr_value_range_kwargs(cls, metadata):
kwargs = {}
min, max = cls._get_attr_value_range(metadata)
# only set range if soft_range is valid (min < max)
if min < max:
kwargs["min"] = min
kwargs["max"] = max
return kwargs
@staticmethod
def _get_attr_value_soft_range(metadata, model=None, use_override=True):
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
soft_range = custom_data.get("soft_range", {})
soft_range_min = soft_range.get("min", 0)
soft_range_max = soft_range.get("max", 0)
# TODO: IMGUI DragScalarN only support scalar range for all vector component.
# Need to change it to support per component range.
if hasattr(soft_range_min, "__getitem__"):
soft_range_min = soft_range_min[0]
if hasattr(soft_range_max, "__getitem__"):
soft_range_max = soft_range_max[0]
if model and use_override:
value = model.get_value()
if hasattr(value, "__getitem__"):
value = value[0]
if model._soft_range_min != None and model._soft_range_min < soft_range_min:
soft_range_min = model._soft_range_min
if model._soft_range_max != None and model._soft_range_max > soft_range_max:
soft_range_max = model._soft_range_max
if soft_range_min < soft_range_max:
if value < soft_range_min:
soft_range_min = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
if value > soft_range_max:
soft_range_max = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
return soft_range_min, soft_range_max
@classmethod
def _get_attr_value_soft_range_kwargs(cls, metadata, model=None):
kwargs = {}
min, max = cls._get_attr_value_soft_range(metadata, model)
# only set soft_range if soft_range is valid (min < max)
if min < max:
kwargs["min"] = min
kwargs["max"] = max
model.update_control_state()
return kwargs
@staticmethod
def _create_drag_or_slider(drag_widget, slider_widget, **kwargs):
if "min" in kwargs and "max" in kwargs:
range_min = kwargs["min"]
range_max = kwargs["max"]
if range_max - range_min < 100:
return slider_widget(name="value", **kwargs)
else:
if "step" not in kwargs:
kwargs["step"] = max(0.1, (range_max - range_min) / 1000.0)
else:
if "step" not in kwargs:
kwargs["step"] = 0.1
# If range is too big or no range, don't use a slider
return drag_widget(name="value", **kwargs)
@classmethod
def _create_multi_float_drag_with_labels(cls, model, labels, comp_count, **kwargs): # pragma: no cover
return cls._create_multi_drag_with_labels(ui.MultiFloatDragField, model, labels, comp_count, **kwargs)
@classmethod
def _create_multi_int_drag_with_labels(cls, model, labels, comp_count, **kwargs): # pragma: no cover
return cls._create_multi_drag_with_labels(ui.MultiIntDragField, model, labels, comp_count, **kwargs)
@classmethod
def _create_multi_drag_with_labels(cls, drag_field_widget, model, labels, comp_count, **kwargs): # pragma: no cover
RECT_WIDTH = 13
SPACING = 4
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING}
widget_kwargs.update(kwargs)
value_widget = drag_field_widget(model, **widget_kwargs)
with ui.HStack():
for i in range(comp_count):
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
mixed_overlay = []
with ui.HStack():
for i in range(comp_count):
ui.Spacer(width=RECT_WIDTH + SPACING)
item_model = model.get_item_value_model(model.get_item_children(None)[i], 0)
mixed_overlay.append(cls._create_mixed_text_overlay(item_model, model, i))
return value_widget, mixed_overlay
@classmethod
def _create_float_drag_per_channel_with_labels_and_control(cls, models, metadata, labels, **kwargs):
return cls._create_drag_per_channel_with_labels_and_control(
ui.FloatDrag, ui.FloatSlider, models, metadata, labels, **kwargs
)
@classmethod
def _create_int_drag_per_channel_with_labels_and_control(cls, models, metadata, labels, **kwargs):
return cls._create_drag_per_channel_with_labels_and_control(
ui.IntDrag, ui.IntSlider, models, metadata, labels, **kwargs
)
@classmethod
def _create_drag_per_channel_with_labels_and_control(
cls, drag_field_widget, slider_field_widget, models, metadata, labels, **kwargs
):
RECT_WIDTH = 13
SPACING = 4
hstack = ui.HStack()
with hstack:
for i, model in enumerate(models):
with ui.HStack():
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
widget_kwargs.update(**kwargs)
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model)
with ui.ZStack():
if soft_range_min < soft_range_max:
value_widget = cls._create_drag_or_slider(
drag_field_widget, drag_field_widget, **widget_kwargs
)
cls._setup_soft_float_dynamic_range(
model._object_paths[-1], metadata, value_widget.step, model, value_widget
)
else:
value_widget = cls._create_drag_or_slider(
drag_field_widget, slider_field_widget, **widget_kwargs
)
mixed_overlay = cls._create_mixed_text_overlay(model, model)
ui.Spacer(width=SPACING)
widget_kwargs["widget_comp_index"] = i
cls._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs)
return hstack
@classmethod
def _create_color_or_multidrag(
cls,
stage,
attr_name,
prim_paths,
comp_count,
type_name,
tf_type,
metadata,
label,
additional_widget_kwargs=None,
): # pragma: no cover
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
extra_widgets = []
model_cls = get_model_cls(GfVecAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
comp_count,
tf_type,
False,
metadata,
**model_kwargs,
)
ui_type = ""
if comp_count == 3 or comp_count == 4:
ui_type = cls._get_attr_value_ui_type(metadata)
if (
type_name == Sdf.ValueTypeNames.Color3h
or type_name == Sdf.ValueTypeNames.Color3f
or type_name == Sdf.ValueTypeNames.Color3d
or type_name == Sdf.ValueTypeNames.Color4h
or type_name == Sdf.ValueTypeNames.Color4f
or type_name == Sdf.ValueTypeNames.Color4d
or ui_type == "color"
):
widget_kwargs = {"min": 0.0, "max": 2.0, "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.HStack(spacing=4):
value_widget, mixed_overlay = cls._create_multi_float_drag_with_labels(
labels=[("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F), ("A", 0xFFFFFFFF)],
comp_count=comp_count,
**widget_kwargs,
)
extra_widgets.append(ui.ColorWidget(model, width=65, height=0))
else:
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
create_drag_fn = (
cls._create_multi_int_drag_with_labels
if type_name.type.typeName.endswith("i")
else cls._create_multi_float_drag_with_labels
)
value_widget, mixed_overlay = create_drag_fn(
labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)],
comp_count=comp_count,
**widget_kwargs,
)
value_widget.identifier = f"color_{attr_name}"
cls._create_control_state(
value_widget=value_widget,
mixed_overlay=mixed_overlay,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
return model
@classmethod
def _create_bool_per_channel(
cls,
stage,
attr_name,
prim_paths,
comp_count,
type_name,
tf_type,
metadata,
label,
additional_widget_kwargs=None,
):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
models = []
# We need a UsdAttributeModel here for context menu and default button:
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
False,
metadata,
False,
**model_kwargs,
)
def on_model_value_changed(model: UsdAttributeModel):
model._update_value()
model.add_value_changed_fn(on_model_value_changed)
single_channel_model_cls = get_model_cls(
GfVecAttributeSingleChannelModel, additional_widget_kwargs, "single_channel_model_cls"
)
for i in range(comp_count):
models.append(
single_channel_model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
i,
False,
metadata,
False,
**model_kwargs,
)
)
widget_kwargs = {}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
mixed_overlay = []
with ui.ZStack():
with ui.HStack(spacing=4, width=32):
with ui.HStack(spacing=HORIZONTAL_SPACING, identifier=f"boolean_per_channel_{attr_name}"):
for i, channel_model in enumerate(models):
with ui.VStack(width=10):
ui.Spacer()
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=-2):
with ui.ZStack():
ui.CheckBox(width=10, height=0, name="greenCheck", model=channel_model)
mixed_overlay.append(
ui.Rectangle(
width=12,
height=12,
name="mixed_overlay",
alignment=ui.Alignment.CENTER,
visible=False,
)
)
ui.Spacer()
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=5)
models.append(model)
cls._create_control_state(model=model, mixed_overlay=mixed_overlay, label=label)
model._update_value() # trigger an initial refresh. Only needed if the model is not assigned to a widget
return models
@classmethod
def _create_color_or_drag_per_channel(
cls,
stage,
attr_name,
prim_paths,
comp_count,
type_name,
tf_type,
metadata,
label,
additional_widget_kwargs=None,
):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
extra_widgets = []
models = []
# We need a GfVecAttributeModel here for:
# If attribute is a color, the color picker widget needs this model type
# When copying value from attribute label, this model is used to fetch value.
model_cls = get_model_cls(GfVecAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
comp_count,
tf_type,
False,
metadata,
**model_kwargs,
)
single_channel_model_cls = get_model_cls(
GfVecAttributeSingleChannelModel, additional_widget_kwargs, "single_channel_model_cls"
)
for i in range(comp_count):
models.append(
single_channel_model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
i,
False,
metadata,
False,
**model_kwargs,
)
)
ui_type = ""
if comp_count == 3 or comp_count == 4:
ui_type = cls._get_attr_value_ui_type(metadata)
if (
type_name == Sdf.ValueTypeNames.Color3h
or type_name == Sdf.ValueTypeNames.Color3f
or type_name == Sdf.ValueTypeNames.Color3d
or type_name == Sdf.ValueTypeNames.Color4h
or type_name == Sdf.ValueTypeNames.Color4f
or type_name == Sdf.ValueTypeNames.Color4d
or ui_type == "color"
):
widget_kwargs = {"min": 0.0, "max": 2.0}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.HStack(spacing=4):
labels = [("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F), ("A", 0xFFFFFFFF)]
value_widget = cls._create_float_drag_per_channel_with_labels_and_control(
models, metadata, labels, **widget_kwargs
)
color_picker = ui.ColorWidget(model, width=LABEL_HEIGHT, height=0)
extra_widgets.append(color_picker)
# append model AFTER _create_float_drag_per_channel_with_labels_and_control call
widget_kwargs["model"] = model
models.append(model)
cls._create_control_state(
value_widget=color_picker,
mixed_overlay=None,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
else:
widget_kwargs = {}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)]
if type_name.type.typeName.endswith("i"):
value_widget = cls._create_int_drag_per_channel_with_labels_and_control(
models, metadata, labels, **widget_kwargs
)
else:
value_widget = cls._create_float_drag_per_channel_with_labels_and_control(
models, metadata, labels, **widget_kwargs
)
# append model AFTER _create_float_drag_per_channel_with_labels_and_control call
models.append(model)
cls._create_attribute_context_menu(label, model)
value_widget.identifier = f"drag_per_channel_{attr_name}"
return models
@staticmethod
def _get_display_name(attr_name, metadata):
if not metadata:
return attr_name
return metadata.get(Sdf.PropertySpec.DisplayNameKey, attr_name)
@staticmethod
def _get_type_name(metadata):
type_name = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")
return Sdf.ValueTypeNames.Find(type_name)
@staticmethod
def _create_mixed_text_overlay(widget_model=None, model=None, comp=-1, content_clipping: bool = False):
with ui.ZStack(alignment=ui.Alignment.CENTER):
stack = ui.ZStack(alignment=ui.Alignment.CENTER, visible=False, content_clipping=content_clipping)
with stack:
ui.Rectangle(alignment=ui.Alignment.CENTER, name="mixed_overlay_text")
ui.Label("Mixed", name="mixed_overlay", alignment=ui.Alignment.CENTER)
if widget_model and model is not None:
hidden_on_edit = False
def begin_edit(_):
nonlocal hidden_on_edit
if stack.visible:
stack.visible = False
hidden_on_edit = True
def end_edit(_):
nonlocal hidden_on_edit
if hidden_on_edit:
if model.is_comp_ambiguous(comp):
stack.visible = True
hidden_on_edit = False
widget_model.add_begin_edit_fn(begin_edit)
widget_model.add_end_edit_fn(end_edit)
return stack
@classmethod
def _create_control_state(cls, model, value_widget=None, mixed_overlay=None, extra_widgets=[], **kwargs):
# Allow widgets to be displayed without the control state
if kwargs.get("no_control_state"):
return
control_state_mgr = ControlStateManager.get_instance()
no_default = kwargs.get("no_default", False)
widget_comp_index = kwargs.get("widget_comp_index", -1)
original_widget_name = value_widget.name if value_widget else ""
original_widget_state = {}
if value_widget:
original_widget_state["value_widget"] = value_widget.enabled
else:
original_widget_state["value_widget"] = True
for index, widget in enumerate(extra_widgets):
original_widget_state[f"extra_widgets_{index}"] = widget.enabled
def build_fn():
state = model.control_state
# no_default is actually no state
if no_default:
state = 0
action, icon_path, tooltip = control_state_mgr.build_control_state(
control_state=state,
model=model,
value_widget=value_widget,
extra_widgets=extra_widgets,
mixed_overlay=mixed_overlay,
original_widget_name=original_widget_name,
**kwargs,
)
with ui.VStack():
ui.Spacer()
button = ui.ImageWithProvider(
icon_path,
mouse_pressed_fn=action,
width=12,
height=5 if state == 0 else 12, # TODO let state decide
tooltip=tooltip,
)
ui.Spacer()
attr_paths = model.get_attribute_paths()
if attr_paths and len(attr_paths) > 0:
button.identifier = f"control_state_{attr_paths[0].elementString[1:]}"
frame = ui.Frame(build_fn=build_fn, width=0)
model.set_on_control_state_changed_fn(frame.rebuild)
if value_widget:
cls._create_attribute_context_menu(value_widget, model, widget_comp_index)
label_widget = kwargs.get("label", None)
if label_widget:
# When right click on label, always copy entire value
cls._create_attribute_context_menu(label_widget, model)
@classmethod
def _time_code_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(SdfTimeCodeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
range_min, range_max = cls._get_attr_value_range(metadata)
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
value_widget.identifier = f"timecode_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@staticmethod
def can_accept_file_drop(payload: str, model_weak, allow_multi_files=False) -> bool:
model_weak = model_weak()
if not model_weak:
return False
urls = payload.split("\n")
if not urls:
return False
if not allow_multi_files and len(urls) > 1:
carb.log_warn(f"sdf_asset_path_builder multifile drag/drop not supported")
return False
custom_data = model_weak.metadata.get(Sdf.PrimSpec.CustomDataKey, {})
file_exts_dict = custom_data.get("fileExts", {})
for url in urls:
accepted = False
if file_exts_dict:
for ext in file_exts_dict:
if fnmatch.fnmatch(url, ext):
accepted = True
break
if not accepted:
carb.log_warn(f"Dropped file {url} does not match allowed extensions {list(file_exts_dict.keys())}")
else:
# TODO support filtering by file extension
if "." in url:
# TODO dragging from stage view also result in a drop, which is a prim path not an asset path
# For now just check if dot presents in the url (indicating file extension).
accepted = True
if not accepted:
return False
return True
@staticmethod
def _convert_asset_path(path: str) -> str:
path_method = carb.settings.get_settings().get("/persistent/app/material/dragDropMaterialPath") or "relative"
if path_method.lower() == "relative":
if not Ar.GetResolver().IsRelativePath(path):
path = omni.usd.make_path_relative_to_current_edit_target(path)
return path
@classmethod
def _build_path_field(cls, model, stage, attr_name, widget_kwargs, frame, extra_widgets):
with ui.HStack():
def clear_name(widget: ui.StringField):
widget.model.set_value("")
def name_changed(model, widget: ui.Button, type):
val = model.get_value()
setattr(widget, type, not bool(val == "" or val == "@@"))
def locate_name_changed(model, widget: ui.Button, type):
# NOTE: changing style makes image dispear
enabled = True
if isinstance(model, SdfAssetPathAttributeModel):
enabled = model.is_valid_path()
# update widget
widget.enabled = enabled
widget.visible = enabled
widget.tooltip = "Locate File" if enabled else ""
def assign_value_fn(model, path: str, resolved_path: str=""):
model.set_value(path, resolved_path)
remove_style = {
"Button.Image::remove": {"image_url": str(ICON_PATH.joinpath("remove-text.svg"))},
"Button.Image::remove:hovered": {"image_url": str(ICON_PATH.joinpath("remove-text-hovered.svg"))},
}
with ui.ZStack():
with ui.ZStack(style=remove_style):
value_widget = ui.StringField(**widget_kwargs)
with ui.HStack():
ui.Spacer()
clear_widget_stack = ui.VStack(width=0, content_clipping=True) # vertically center the button
with clear_widget_stack:
ui.Spacer()
clear_widget = ui.Button(
"",
width=20,
height=20,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
clicked_fn=lambda f=value_widget: clear_name(f),
name="remove",
)
ui.Spacer()
value_widget.model.add_value_changed_fn(
lambda m, w=clear_widget_stack: name_changed(m, w, "visible")
)
value_widget.model._value_changed()
value_widget.set_accept_drop_fn(
lambda url, model_weak=weakref.ref(model): cls.can_accept_file_drop(url, model_weak)
)
value_widget.set_drop_fn(
lambda event, model_weak=weakref.ref(model), stage_weak=weakref.ref(
stage
): cls._assign_asset_path_value(stage_weak, model_weak, event.mime_data, assign_value_fn, frame)
)
value_widget.identifier = f"sdf_asset_{attr_name}" + (
f"[{model.index}]" if hasattr(model, "index") else ""
)
clear_widget.identifier = f"sdf_clear_asset_{attr_name}" + (
f"[{model.index}]" if hasattr(model, "index") else ""
)
mixed_overlay = cls._create_mixed_text_overlay()
ui.Spacer(width=3)
style = {"image_url": str(ICON_PATH.joinpath("small_folder.png"))}
enabled = get_file_importer() is not None
browse_button = ui.Button(
style=style,
width=20,
tooltip="Browse..." if enabled else "File importer not available",
clicked_fn=lambda model_weak=weakref.ref(model), stage_weak=weakref.ref(
stage
): show_asset_file_picker(
"Select Asset...",
assign_value_fn,
model_weak,
stage_weak,
on_selected_fn=cls._assign_asset_resolved_value
),
enabled=enabled,
identifier=f"sdf_browse_asset_{attr_name}" + (f"[{model.index}]" if hasattr(model, "index") else ""),
)
extra_widgets.append(browse_button)
extra_widgets.append(ui.Spacer(width=3))
# Button to jump to the file in Content Window
def locate_file(model):
async def locate_file_async(model):
# omni.kit.window.content_browser is optional dependency
try:
import omni.client
import omni.kit.app
import os
await omni.kit.app.get_app().next_update_async()
url = ""
if isinstance(model, SdfAssetPathAttributeModel):
url = model.get_resolved_path()
if url:
url = f"{omni.usd.correct_filename_case(os.path.dirname(url))}/{os.path.basename(url)}"
elif isinstance(model, ui.AbstractValueModel):
url = model.get_value_as_string()
if not url:
return
client_url = omni.client.break_url(url)
if client_url:
url = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
)
import omni.kit.window.content_browser
instance = omni.kit.window.content_browser.get_instance()
instance.navigate_to(url)
except Exception as e:
carb.log_warn(f"Failed to locate file: {e}")
asyncio.ensure_future(locate_file_async(model))
style["image_url"] = str(ICON_PATH.joinpath("find.png"))
enabled = True
if isinstance(model, SdfAssetPathAttributeModel):
enabled = model.is_valid_path()
locate_widget = ui.Button(
style=style,
width=20,
enabled=enabled,
visible=enabled,
tooltip="Locate File" if enabled else "",
clicked_fn=lambda model=model: locate_file(model),
identifier=f"sdf_locate_asset_{attr_name}" + (f"[{model.index}]" if hasattr(model, "index") else ""),
)
value_widget.model.add_value_changed_fn(lambda m, w=locate_widget: locate_name_changed(m, w, "enabled"))
return value_widget, mixed_overlay
@classmethod
def _assign_asset_path_value(
cls, stage_weak, model_weak, payload: str, assign_value_fn: Callable[[Any, str], None], frame=None
):
stage_weak = stage_weak()
if not stage_weak:
return
model_weak = model_weak()
if not model_weak:
return
urls = payload.split("\n")
with omni.kit.undo.group():
for path in urls:
path = cls._convert_asset_path(path)
assign_value_fn(model_weak, path.replace("\\", "/"))
if frame:
frame.rebuild()
@classmethod
def _assign_asset_resolved_value(
cls, stage_weak, model_weak, payload: str, assign_value_fn: Callable[[Any, str], None], frame=None
):
model = model_weak()
if not model:
return
urls = payload.split("\n")
with omni.kit.undo.group():
for path in urls:
assign_value_fn(model, cls._convert_asset_path(path).replace("\\", "/"), path)
if frame:
frame.rebuild()
@classmethod
def _create_path_widget(
cls, model, stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
):
if "colorSpace" in metadata:
colorspace_model = MetadataObjectModel(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
False,
metadata,
key="colorSpace",
default="auto",
options=["auto", "raw", "sRGB"],
)
else:
colorspace_model = None
def build_frame(
cls, model, colorspace_model, frame, stage, attr_name, metadata, prim_paths,
additional_label_kwargs, additional_widget_kwargs
):
extra_widgets = []
with ui.VStack():
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
widget_kwargs = {"name": "models", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
value_widget, mixed_overlay = cls._build_path_field(
model, stage, attr_name, widget_kwargs, frame, extra_widgets
)
cls._create_control_state(
value_widget=value_widget,
mixed_overlay=mixed_overlay,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
if isinstance(model, SdfAssetPathAttributeModel):
cls._build_asset_checkpoint_ui(model, frame)
if colorspace_model:
ui.Spacer(height=5)
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(
cls._get_display_name(attr_name, metadata) + " Color Space", {}, additional_label_kwargs
)
with ui.ZStack():
value_widget = ui.ComboBox(colorspace_model, name="choices")
value_widget.identifier = f"colorspace_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
widget_kwargs = {"no_default": True}
cls._create_control_state(
colorspace_model, value_widget, mixed_overlay, **widget_kwargs, label=label
)
frame = ui.Frame(width=omni.ui.Percent(100))
frame.set_build_fn(
lambda: build_frame(
cls,
model,
colorspace_model,
frame,
stage,
attr_name,
metadata,
prim_paths,
additional_label_kwargs,
additional_widget_kwargs,
)
)
if colorspace_model:
# Returns colorspace model also so it could receive updates.
return [model, colorspace_model]
else:
return [model]
@classmethod
def _create_filepath_for_ui_type(
cls, stage, attr_name, metadata, prim_paths: List[Sdf.Path], additional_label_kwargs, additional_widget_kwargs
):
model = None
ui_type = cls._get_attr_value_ui_type(metadata)
if ui_type == "filePath":
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs, key="no_allowed_tokens_model_cls")
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "models"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
cls._create_path_widget(
model, stage, attr_name, metadata, prim_paths, additional_label_kwargs, widget_kwargs
)
return model
| 85,426 | Python | 40.65139 | 130 | 0.524735 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/context_menu.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os, sys
import carb
import omni.kit.ui
import weakref
from functools import partial
from pxr import Usd, Sdf, UsdShade, UsdGeom, UsdLux
from .prim_selection_payload import PrimSelectionPayload
class ContextMenuEvent:
"""The object comatible with ContextMenu"""
def __init__(self, payload: PrimSelectionPayload, menu_items: list, xpos: int, ypos: int):
self.menu_items = menu_items
self.payload = payload
self.type = 0
self.xpos = xpos
self.ypos = ypos
class ContextMenu:
def __init__(self):
pass
def on_mouse_event(self, event: ContextMenuEvent):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE):
return
# setup objects, this is passed to all functions
objects = {
"stage": event.payload.get_stage(),
"prim_list": event.payload._payload,
"menu_xpos": event.xpos,
"menu_ypos": event.ypos,
}
menu_list = []
for item in event.menu_items:
name = item.path
parts = item.path.split("/")
if len(parts) < 2:
menu_list.append(item.get_dict(event.payload))
else:
last_name = parts.pop()
first_name = parts.pop(0)
menu_sublist = None
for menu_item in menu_list:
if first_name in menu_item["name"]:
menu_sublist = menu_item["name"][first_name]
break
if menu_sublist is None:
menu_list.append({"glyph": item.glyph, "name": {first_name: []}})
menu_sublist = menu_list[-1]["name"][first_name]
for part in parts:
sublist = None
for menu_item in menu_sublist:
if part in menu_item["name"]:
sublist = menu_item["name"][part]
break
if sublist is None:
menu_sublist.append({"glyph": item.glyph, "name": {part: []}})
menu_sublist = menu_sublist[-1]["name"][part]
else:
menu_sublist = sublist
menu_sublist.append(item.get_dict(event.payload, last_name))
# show menu
self.show_context_menu(objects=objects, menu_list=menu_list)
def show_context_menu(self, objects: dict = {}, menu_list: list = []):
# get context menu core functionality & check its enabled
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
carb.log_warn("context_menu is disabled!")
return None
context_menu.show_context_menu("prim_path_widget", objects, menu_list)
| 3,295 | Python | 34.826087 | 94 | 0.567527 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_attribute_model.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 copy
import weakref
from typing import List
import omni.ui as ui
from pxr import Gf, Sdf, Tf, Usd, UsdShade
from .usd_model_base import *
class FloatModel(ui.SimpleFloatModel):
def __init__(self, parent):
super().__init__()
self._parent = weakref.ref(parent)
def begin_edit(self):
parent = self._parent()
parent.begin_edit(None)
def end_edit(self):
parent = self._parent()
parent.end_edit(None)
class IntModel(ui.SimpleIntModel):
def __init__(self, parent):
super().__init__()
self._parent = weakref.ref(parent)
def begin_edit(self):
parent = self._parent()
parent.begin_edit(None)
def end_edit(self):
parent = self._parent()
parent.end_edit(None)
class UsdAttributeModel(ui.AbstractValueModel, UsdBase):
"""The value model that is reimplemented in Python to watch a USD attribute path"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs)
ui.AbstractValueModel.__init__(self)
def clean(self):
UsdBase.clean(self)
def begin_edit(self):
UsdBase.begin_edit(self)
ui.AbstractValueModel.begin_edit(self)
def end_edit(self):
UsdBase.end_edit(self)
ui.AbstractValueModel.end_edit(self)
def get_value_as_string(self, elide_big_array=True) -> str:
self._update_value()
if self._value is None:
return ""
elif self._is_big_array and elide_big_array:
return "[...]"
else:
return str(self._value)
def get_value_as_float(self) -> float:
self._update_value()
if self._value is None:
return 0.0
else:
if hasattr(self._value, "__len__"):
return float(self._value[self._channel_index])
return float(self._value)
def get_value_as_bool(self) -> bool:
self._update_value()
if self._value is None:
return False
else:
if hasattr(self._value, "__len__"):
return bool(self._value[self._channel_index])
return bool(self._value)
def get_value_as_int(self) -> int:
self._update_value()
if self._value is None:
return 0
else:
if hasattr(self._value, "__len__"):
return int(self._value[self._channel_index])
return int(self._value)
def set_value(self, value):
if UsdBase.set_value(self, value):
self._value_changed()
def _on_dirty(self):
self._value_changed()
class GfVecAttributeSingleChannelModel(UsdAttributeModel):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
channel_index: int,
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
self._channel_index = channel_index
super().__init__(stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs)
def get_value_as_string(self, **kwargs) -> str:
self._update_value()
if self._value is None:
return ""
else:
return str(self._value[self._channel_index])
def get_value_as_float(self) -> float:
self._update_value()
if self._value is None:
return 0.0
else:
if hasattr(self._value, "__len__"):
return float(self._value[self._channel_index])
return float(self._value)
def get_value_as_bool(self) -> bool:
self._update_value()
if self._value is None:
return False
else:
if hasattr(self._value, "__len__"):
return bool(self._value[self._channel_index])
return bool(self._value)
def get_value_as_int(self) -> int:
self._update_value()
if self._value is None:
return 0
else:
if hasattr(self._value, "__len__"):
return int(self._value[self._channel_index])
return int(self._value)
def set_value(self, value):
vec_value = copy.copy(self._value)
vec_value[self._channel_index] = value
if UsdBase.set_value(self, vec_value, self._channel_index):
self._value_changed()
def is_different_from_default(self):
"""Override to only check channel"""
if super().is_different_from_default():
return self._comp_different_from_default[self._channel_index]
return False
class TfTokenAttributeModel(ui.AbstractItemModel, UsdBase):
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item):
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(item)
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._allowed_tokens = []
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._updating_value = False
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._allowed_tokens
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self, item):
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
def _current_index_changed(self, model):
if not self._has_index:
return
# if we're updating from USD notice change to UI, don't call set_value
if self._updating_value:
return
index = model.as_int
if self.set_value(self._get_value_from_index(index)):
self._item_changed(None)
def _get_allowed_tokens(self, attr):
return attr.GetMetadata("allowedTokens")
def _update_allowed_token(self, token_item=AllowedTokenItem):
self._allowed_tokens = []
# For multi prim editing, the allowedTokens should all be the same
attributes = self._get_attributes()
attr = attributes[0] if len(attributes) > 0 else None
if attr:
for t in self._get_allowed_tokens(attr):
self._allowed_tokens.append(token_item(t))
def _update_value(self, force=False):
was_updating_value = self._updating_value
self._updating_value = True
if UsdBase._update_value(self, force):
# TODO don't have to do this every time. Just needed when "allowedTokens" actually changed
self._update_allowed_token()
index = -1
for i in range(0, len(self._allowed_tokens)):
if self._allowed_tokens[i].token == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._current_index.set_value(index)
self._item_changed(None)
self._updating_value = was_updating_value
def _on_dirty(self):
self._item_changed(None)
def get_value_as_token(self):
index = self._current_index.as_int
return self._allowed_tokens[index].token
def is_allowed_token(self, token):
return token in [allowed.token for allowed in self._allowed_tokens]
def _get_value_from_index(self, index):
return self._allowed_tokens[index].token
class MdlEnumAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._options = []
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._updating_value = False
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._options
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self, item):
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
def _current_index_changed(self, model):
if not self._has_index:
return
# if we're updating from USD notice change to UI, don't call set_value
if self._updating_value:
return
index = model.as_int
if self.set_value(self._options[index].value):
self._item_changed(None)
def _update_option(self):
self._options = []
# For multi prim editing, the options should all be the same
attributes = self._get_attributes()
attr = attributes[0] if len(attributes) > 0 else None
if attr and isinstance(attr, Usd.Attribute):
shade_input = UsdShade.Input(attr)
if shade_input and shade_input.HasRenderType() and shade_input.HasSdrMetadataByKey("options"):
options = shade_input.GetSdrMetadataByKey("options").split("|")
class OptionItem(ui.AbstractItem):
def __init__(self, display_name: str, value: int):
super().__init__()
self.model = ui.SimpleStringModel(display_name)
self.value = value
for option in options:
kv = option.split(":")
self._options.append(OptionItem(kv[0], int(kv[1])))
def _update_value(self, force=False):
was_updating_value = self._updating_value
self._updating_value = True
if UsdBase._update_value(self, force):
# TODO don't have to do this every time. Just needed when "option" actually changed
self._update_option()
index = -1
for i in range(0, len(self._options)):
if self._options[i].value == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._current_index.set_value(index)
self._item_changed(None)
self._updating_value = was_updating_value
def _on_dirty(self):
self._item_changed(None)
def get_value_as_string(self):
index = self._current_index.as_int
return self._options[index].model.as_string
def is_allowed_enum_string(self, enum_str):
return enum_str in [allowed.model.as_string for allowed in self._options]
def set_from_enum_string(self, enum_str):
if not self.is_allowed_enum_string(enum_str):
return
new_index = -1
for index, option in enumerate(self._options):
if option.model.as_string == enum_str:
new_index = index
break
if new_index != -1:
self._current_index.set_value(new_index)
class GfVecAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
comp_count: int,
tf_type: Tf.Type,
self_refresh: bool,
metadata: dict,
**kwargs,
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata, **kwargs)
ui.AbstractItemModel.__init__(self)
self._comp_count = comp_count
self._data_type_name = "Vec" + str(self._comp_count) + tf_type.typeName[-1]
self._data_type = getattr(Gf, self._data_type_name)
class UsdVectorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
if self._data_type_name.endswith("i"):
self._items = [UsdVectorItem(IntModel(self)) for i in range(self._comp_count)]
else:
self._items = [UsdVectorItem(FloatModel(self)) for i in range(self._comp_count)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
def _construct_vector_from_item(self):
if self._data_type_name.endswith("i"):
data = [item.model.get_value_as_int() for item in self._items]
else:
data = [item.model.get_value_as_float() for item in self._items]
return self._data_type(data)
def _on_value_changed(self, item):
"""Called when the submodel is changed"""
if self._edit_mode_counter > 0:
vector = self._construct_vector_from_item()
index = self._items.index(item)
if vector and self.set_value(vector, index):
# Read the new value back in case hard range clamped it
item.model.set_value(self._value[index])
self._item_changed(item)
else:
# If failed to update value in model, revert the value in submodel
item.model.set_value(self._value[index])
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
if not self._value:
for i in range(len(self._items)):
self._items[i].model.set_value(0.0)
return
for i in range(len(self._items)):
self._items[i].model.set_value(self._value[i])
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
"""Reimplemented from the base class"""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
class SdfAssetPathAttributeModel(UsdAttributeModel):
"""The value model that is reimplemented in Python to watch a USD attribute path"""
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
super().__init__(stage, attribute_paths, self_refresh, metadata, True, treat_array_entry_as_comp=True)
def get_value_as_string(self, **kwargs):
self._update_value()
return self._get_value_as_string(self._value)
def is_valid_path(self) -> bool:
return self._is_valid_path(self._value)
def get_resolved_path(self):
self._update_value()
return self._get_resolved_path(self._value)
def set_value(self, path, resolved_path: str=""):
value = path
if not isinstance(path, Sdf.AssetPath):
if resolved_path:
value = Sdf.AssetPath(path, resolved_path)
else:
value = Sdf.AssetPath(path)
if UsdBase.set_value(self, value):
self._value_changed()
def _is_prev_same(self):
# Strip the resolvedPath from the AssetPath for the comparison, since the prev values don't have resolvedPath.
return [Sdf.AssetPath(value.path) for value in self._real_values] == self._prev_real_values
def _save_real_values_as_prev(self):
# Strip the resolvedPath from the AssetPath so that it can be recomputed.
self._prev_real_values = [Sdf.AssetPath(value.path) for value in self._real_values]
def _change_property(self, path: Sdf.Path, new_value, old_value):
if path.name == "info:mdl:sourceAsset" and new_value.path:
if isinstance(new_value, Sdf.AssetPath):
# make the path relative to current edit target layer
relative_path = omni.usd.make_path_relative_to_current_edit_target(new_value.path)
new_value = Sdf.AssetPath(relative_path, new_value.resolvedPath)
if path.name == "info:mdl:sourceAsset":
if isinstance(new_value, Sdf.AssetPath):
# "info:mdl:sourceAsset" when is changed update "info:mdl:sourceAsset:subIdentifier"
stage = self._stage
asset_attr = stage.GetAttributeAtPath(path)
subid_attr = stage.GetAttributeAtPath(
path.GetPrimPath().AppendElementString(".info:mdl:sourceAsset:subIdentifier")
)
if asset_attr and subid_attr:
mdl_path = new_value.resolvedPath if new_value.resolvedPath else new_value.path
if mdl_path:
import asyncio
baseclass = super()
def have_subids(id_list: list):
if len(id_list) > 0:
with omni.kit.undo.group():
baseclass._change_property(subid_attr.GetPath(), str(id_list[0]), None)
baseclass._change_property(path, new_value, old_value)
asyncio.ensure_future(
omni.kit.material.library.get_subidentifier_from_mdl(
mdl_file=mdl_path, on_complete_fn=have_subids, use_functions=True, show_alert=True
)
)
return
else:
super()._change_property(subid_attr.GetPath(), "", None)
super()._change_property(path, new_value, old_value)
# private functions to be shared with SdfAssetPathArrayAttributeSingleEntryModel
def _get_value_as_string(self, value, **kwargs):
return value.path if value else ""
def _is_valid_path(self, value) -> bool:
if not value:
return False
path = value.path
if path.lower().startswith("http"):
return False
return bool(path)
def _get_resolved_path(self, value):
if self._ambiguous:
return "Mixed"
else:
return value.resolvedPath.replace("\\", "/") if value else ""
class SdfAssetPathArrayAttributeSingleEntryModel(SdfAssetPathAttributeModel):
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], index: int, self_refresh: bool, metadata: dict
):
self._index = index
super().__init__(stage, attribute_paths, self_refresh, metadata)
@property
def index(self):
return self._index
def get_value_as_string(self, **kwargs):
self._update_value()
return self._get_value_as_string(self._value[self._index])
def get_value(self):
return super().get_value()[self._index]
def is_valid_path(self) -> bool:
self._update_value()
return self._is_valid_path(self._value[self._index])
def get_resolved_path(self):
self._update_value()
return self._get_resolved_path(self._value[self._index])
def set_value(self, path, resolved_path: str=""):
value = path
if not isinstance(path, Sdf.AssetPath):
if resolved_path:
value = Sdf.AssetPath(path, resolved_path)
else:
value = Sdf.AssetPath(path)
vec_value = Sdf.AssetPathArray(self._value)
vec_value[self._index] = value
if UsdBase.set_value(self, vec_value, self._index):
self._value_changed()
def _is_prev_same(self):
# Strip the resolvedPath from the AssetPath for the comparison, since the prev values don't have resolvedPath.
return [
[Sdf.AssetPath(value.path) for value in values] for values in self._real_values
] == self._prev_real_values
def _save_real_values_as_prev(self):
# Strip the resolvedPath from the AssetPath so that it can be recomputed.
self._prev_real_values = [[Sdf.AssetPath(value.path) for value in values] for values in self._real_values]
class SdfAssetPathArrayAttributeItemModel(ui.AbstractItemModel):
class SdfAssetPathItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], index: int, self_refresh: bool, metadata: dict
):
super().__init__()
self.sdf_asset_path_model = SdfAssetPathArrayAttributeSingleEntryModel(
stage, attribute_paths, index, self_refresh, metadata
)
def destroy(self):
self.sdf_asset_path_model.clean()
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, delegate):
super().__init__()
self._delegate = delegate # keep a reference of the delegate os it's not destroyed
self._value_model = UsdAttributeModel(stage, attribute_paths, False, metadata)
value = self._value_model.get_value()
self._entries = []
self._repopulate_entries(value)
def clean(self):
self._delegate = None
for entry in self._entries:
entry.destroy()
self._entries.clear()
if self._value_model:
self._value_model.clean()
self._value_model = None
@property
def value_model(self) -> UsdAttributeModel:
return self._value_model
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._entries
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return (item.sdf_asset_path_model, self._value_model)
def get_drag_mime_data(self, item):
return str(item.sdf_asset_path_model.index)
def drop_accepted(self, target_item, source, drop_location=-1):
try:
source_id = self._entries.index(source)
except ValueError:
# Not in the list. This is the source from another model.
return False
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
try:
source_id = self._entries.index(source)
except ValueError:
# Not in the list. This is the source from another model.
return
if source_id == drop_location:
# Nothing to do
return
value = list(self._value_model.get_value())
moved_entry_value = value[source_id]
del value[source_id]
if drop_location > len(value):
# Drop it to the end
value.append(moved_entry_value)
else:
if source_id < drop_location:
# Because when we removed source, the array became shorter
drop_location = drop_location - 1
value.insert(drop_location, moved_entry_value)
self._value_model.set_value(value)
def _repopulate_entries(self, value: Sdf.AssetPathArray):
for entry in self._entries:
entry.destroy()
self._entries.clear()
stage = self._value_model.stage
metadata = self._value_model.metadata
attribute_paths = self._value_model.get_attribute_paths()
for i in range(len(value)):
model = SdfAssetPathArrayAttributeItemModel.SdfAssetPathItem(stage, attribute_paths, i, False, metadata)
self._entries.append(model)
self._item_changed(None)
def _on_usd_changed(self, *args, **kwargs):
# forward to all sub-models
self._value_model._on_usd_changed(*args, **kwargs)
for entry in self._entries:
entry.sdf_asset_path_model._on_usd_changed(*args, **kwargs)
def _set_dirty(self, *args, **kwargs):
# forward to all sub-models
self._value_model._set_dirty(*args, **kwargs)
new_value = self._value_model.get_value()
if len(new_value) != len(self._entries):
self._repopulate_entries(new_value)
else:
for entry in self._entries:
entry.sdf_asset_path_model._set_dirty(*args, **kwargs)
def get_value(self, *args, **kwargs):
return self._value_model.get_value(*args, **kwargs)
def set_value(self, *args, **kwargs):
return self._value_model.set_value(*args, **kwargs)
class GfQuatAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], tf_type: Tf.Type, self_refresh: bool, metadata: dict
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
data_type_name = "Quat" + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdQuatItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create four models per component
self._items = [UsdQuatItem(FloatModel(self)) for i in range(4)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if self._edit_mode_counter > 0:
quat = self._construct_quat_from_item()
if quat and self.set_value(quat, self._items.index(item)):
self._item_changed(item)
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
for i in range(len(self._items)):
if i == 0:
self._items[i].model.set_value(self._value.real)
else:
self._items[i].model.set_value(self._value.imaginary[i - 1])
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
"""Reimplemented from the base class"""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
def _construct_quat_from_item(self):
data = [item.model.get_value_as_float() for item in self._items]
return self._data_type(data[0], data[1], data[2], data[3])
# A data model for display orient(quaternion) as rotate(Euler)
class GfQuatEulerAttributeModel(ui.AbstractItemModel, UsdBase):
axes = [Gf.Vec3d(1, 0, 0), Gf.Vec3d(0, 1, 0), Gf.Vec3d(0, 0, 1)]
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], tf_type: Tf.Type, self_refresh: bool, metadata: dict
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
# The underline USD data is still a quaternion
data_type_name = "Quat" + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdFloatItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [UsdFloatItem(FloatModel(self)) for _ in range(3)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
# Should be used to set the self._items to USD attribute
def _on_value_changed(self, item):
if self._edit_mode_counter > 0:
quat = self._compose([item.model.as_float for item in self._items])
if quat and self.set_value(quat):
self._item_changed(item)
# Unlike normal Vec3 or Quat, we have to update all four values all together
def update_to_submodels(self):
if self._edit_mode_counter != 0:
return
if self._value is not None:
e = self._decompose(self._value)
for i, item in enumerate(self._items):
item.model.set_value(e[i])
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
self.update_to_submodels()
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
def _compose(self, eulers):
nrs = [Gf.Rotation(axis, eulers[i]) for i, axis in enumerate(self.axes)]
nr = nrs[2] * nrs[1] * nrs[0]
result = self._data_type(nr.GetQuat())
return result
def _decompose(self, value):
rot = Gf.Rotation(value)
eulers = rot.Decompose(*self.axes)
# round epsilons from decompose
eulers = [round(angle + 1e-4, 3) for angle in eulers]
return eulers
def _get_comp_num(self):
return 3
def _get_value_by_comp(self, value, comp: int):
e = self._decompose(value)
return e[comp]
def _update_value_by_comp(self, value, comp: int):
self_e = self._decompose(self._value)
e = self._decompose(value)
e[comp] = self_e[comp]
value = self._compose(e)
return value
def _compare_value_by_comp(self, val1, val2, comp: int):
return Gf.IsClose(self._get_value_by_comp(val1, comp), self._get_value_by_comp(val2, comp), 1e-6)
class GfMatrixAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
comp_count: int,
tf_type: Tf.Type,
self_refresh: bool,
metadata: dict,
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._comp_count = comp_count
data_type_name = "Matrix" + str(self._comp_count) + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdMatrixItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [UsdMatrixItem(FloatModel(self)) for i in range(self._comp_count * self._comp_count)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if self._edit_mode_counter > 0:
matrix = self._construct_matrix_from_item()
if matrix and self.set_value(matrix, self._items.index(item)):
self._item_changed(item)
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
for i in range(len(self._items)):
self._items[i].model.set_value(self._value[i // self._comp_count][i % self._comp_count])
def _on_dirty(self):
self._item_changed(None)
# it's still better to call _value_changed for all child items
for child in self._items:
child.model._value_changed()
def get_item_children(self, item):
"""Reimplemented from the base class."""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class."""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
def _construct_matrix_from_item(self):
data = [item.model.get_value_as_float() for item in self._items]
matrix = []
for i in range(self._comp_count):
matrix_row = []
for j in range(self._comp_count):
matrix_row.append(data[i * self._comp_count + j])
matrix.append(matrix_row)
return self._data_type(matrix)
class UsdAttributeInvertedModel(UsdAttributeModel):
def get_value_as_bool(self) -> bool:
return not super().get_value_as_bool()
def get_value_as_string(self, **kwargs) -> str:
return str(self.get_value_as_bool())
def set_value(self, value):
super().set_value(not value)
def get_value(self):
return not super().get_value()
class SdfTimeCodeModel(UsdAttributeModel):
def _save_real_values_as_prev(self):
# SdfTimeCode cannot be inited from another SdfTimeCode, only from float (double in C++)..
self._prev_real_values = [Sdf.TimeCode(float(value)) for value in self._real_values]
| 36,215 | Python | 33.360531 | 120 | 0.586829 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/message_bus_events.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.events
ADDITIONAL_CHANGED_PATH_EVENT_TYPE = carb.events.type_from_string("omni.usd.property.usd.additional_changed_path")
| 564 | Python | 42.461535 | 114 | 0.806738 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/references_widget.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 weakref
import asyncio
from functools import lru_cache, partial
from typing import Callable, Union, Any
import carb
import omni.client
import omni.client.utils as clientutils
import omni.kit.app
import omni.kit.commands
import omni.kit.ui
import omni.ui as ui
import omni.usd
from omni.kit.window.file_importer import get_file_importer, ImportOptionsDelegate
from pxr import Sdf, Tf, Usd
from .asset_filepicker import show_asset_file_picker, replace_query
from .prim_selection_payload import PrimSelectionPayload
from .usd_property_widget import UsdPropertiesWidget
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder, get_ui_style
from .widgets import ICON_PATH
from .versioning_helper import VersioningHelper
DEFAULT_PRIM_TAG = "<Default Prim>"
REF_LABEL_WIDTH = 80
@lru_cache()
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
def anchor_reference_asset_path_to_layer(ref: Sdf.Reference, intro_layer: Sdf.Layer, anchor_layer: Sdf.Layer):
asset_path = ref.assetPath
if asset_path:
asset_path = intro_layer.ComputeAbsolutePath(asset_path)
asset_url = clientutils.make_relative_url_if_possible(anchor_layer.identifier, asset_path)
# make a copy as Reference is immutable
ref = Sdf.Reference(
assetPath=asset_url,
primPath=ref.primPath,
layerOffset=ref.layerOffset,
customData=ref.customData,
)
return ref
def anchor_payload_asset_path_to_layer(ref: Sdf.Payload, intro_layer: Sdf.Layer, anchor_layer: Sdf.Layer):
asset_path = ref.assetPath
if asset_path:
asset_path = intro_layer.ComputeAbsolutePath(asset_path)
asset_url = clientutils.make_relative_url_if_possible(anchor_layer.identifier, asset_path)
# make a copy as Payload is immutable
ref = Sdf.Payload(
assetPath=asset_url,
primPath=ref.primPath,
layerOffset=ref.layerOffset,
)
return ref
# Model that calls edited_fn when end_edit or set_value (not when typing)
class TrackEditingStringModel(ui.SimpleStringModel):
def __init__(self, value: str = ""):
super().__init__()
self._editing = False
self._edited_fn = []
self.set_value(value)
def begin_edit(self):
super().begin_edit()
self._editing = True
def end_edit(self):
self._editing = False
super().end_edit()
self._call_edited_fn()
def set_value(self, value: str):
super().set_value(value)
if not self._editing:
self._call_edited_fn()
def add_edited_fn(self, fn):
self._edited_fn.append(fn)
def clear_edited_fn(self):
self._edited_fn.clear()
def _call_edited_fn(self):
for fn in self._edited_fn:
fn(self)
class PayloadReferenceInfo:
def __init__(self, asset_path_field, prim_path_field, prim_path_field_model, checkpoint_model):
self.asset_path_field = asset_path_field
self.prim_path_field = prim_path_field
self.prim_path_field_model = prim_path_field_model
self.checkpoint_model = checkpoint_model
def destroy(self):
if self.checkpoint_model:
self.checkpoint_model.destroy()
self.asset_path_field = None
self.prim_path_field = None
self.prim_path_field_model = None
self.checkpoint_model = None
def build_path_field(stage, init_value: str, jump_button: bool, use_payloads: bool, layer: Sdf.Layer = None):
with ui.HStack(style={"Button": {"margin": 0, "padding": 3, "border_radius": 2, "background_color": 0x00000000}}):
def assign_value_fn(model, path):
model.set_value(path)
def assign_reference_value(stage_weak, model_weak, path: str, assign_value_fn: Callable[[Any, str], None], frame=None):
stage = stage_weak()
if not stage:
return
model = model_weak()
if not model:
return
edit_layer = stage.GetEditTarget().GetLayer()
# make the path relative to current edit target layer
relative_url = clientutils.make_relative_url_if_possible(edit_layer.identifier, path)
assign_value_fn(model, relative_url)
def drop_accept(url: str):
if len(url.split('\n')) > 1:
carb.log_warn(f"build_path_field multifile drag/drop not supported")
return False
# TODO support filtering by file extension
if "." not in url:
# TODO dragging from stage view also result in a drop, which is a prim path not an asset path
# For now just check if dot presents in the url (indicating file extension).
return False
return True
with ui.ZStack():
model = TrackEditingStringModel(value=init_value)
string_field = ui.StringField(model=model)
string_field.set_accept_drop_fn(drop_accept)
string_field.set_drop_fn(
lambda event, model_weak=weakref.ref(model), stage_weak=weakref.ref(stage): assign_reference_value(
stage_weak, model_weak, event.mime_data, assign_value_fn=assign_value_fn
)
)
ui.Spacer(width=3)
def on_refresh_layer(model, weak_layer):
intro_layer = weak_layer()
url = model.get_value_as_string()
if url and intro_layer:
layer = Sdf.Find(intro_layer.ComputeAbsolutePath(url))
if layer:
async def reload(layer):
layer.Reload(force=True)
asyncio.ensure_future(reload(layer))
changed = False
ui.Button(
style={
"image_url": str(ICON_PATH.joinpath("refresh.svg")),
"padding": 1,
"margin": 0,
"Button.Image": {
"color": 0xFF9E9E9E if not changed else 0xFF248AE3,
},
"Button:hovered": {
"background_color": 0x00000000
}
},
width=20,
tooltip="Refresh Payload" if use_payloads else "Refresh Reference",
clicked_fn=lambda model=model, layer_weak=weakref.ref(layer) if layer else None: on_refresh_layer(model, layer_weak),
)
style = {
"image_url": str(ICON_PATH.joinpath("small_folder.png")),
"padding": 1,
"margin": 0,
"Button:hovered": {
"background_color": 0x00000000
}
}
ui.Button(
style=style,
width=20,
tooltip="Browse..." if get_file_importer() is not None else "File importer not available",
clicked_fn=lambda model_weak=weakref.ref(model), stage_weak=weakref.ref(stage), layer_weak=weakref.ref(
layer
) if layer else None: show_asset_file_picker(
"Select Payload..." if use_payloads else "Select Reference...",
assign_value_fn,
model_weak,
stage_weak,
layer_weak=layer_weak,
on_selected_fn=assign_reference_value,
),
enabled=get_file_importer() is not None,
)
if jump_button:
ui.Spacer(width=3)
# Button to jump to the file in Content Window
def locate_file(model, weak_layer):
# omni.kit.window.content_browser is optional dependency
try:
url = model.get_value_as_string()
if len(url) == 0:
return
if weak_layer:
weak_layer = weak_layer()
if weak_layer:
url = weak_layer.ComputeAbsolutePath(url)
# Remove the checkpoint and branch so navigate_to works
url = replace_query(url, None)
import omni.kit.window.content_browser
instance = omni.kit.window.content_browser.get_instance()
instance.navigate_to(url)
except Exception as e:
carb.log_warn(f"Failed to locate file: {e}")
style["image_url"] = str(ICON_PATH.joinpath("find.png"))
ui.Button(
style=style,
width=20,
tooltip="Locate File",
clicked_fn=lambda model=model, weak_layer=weakref.ref(layer) if layer else None: locate_file(
model, weak_layer
),
)
return string_field
class AddPayloadReferenceOptionsDelegate(ImportOptionsDelegate):
def __init__(self, prim_path_model):
super().__init__(
build_fn=self._build_ui_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
self._prim_path_model = prim_path_model
def should_load_payload(self):
if self._load_payload_checkbox:
return self._load_payload_checkbox.model.get_value_as_bool()
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.HStack(height=0, spacing=2):
ui.Label("Prim Path", width=0)
ui.StringField().model = self._prim_path_model
def _destroy_impl(self, _):
self._prim_path_model = None
self._widget = None
class AddPayloadReferenceWindow:
def __init__(self, payload: PrimSelectionPayload, on_payref_added_fn: Callable, use_payloads=False):
self._payrefs = None
self._use_payloads = use_payloads
self._prim_path_model = ui.SimpleStringModel()
self._stage = payload.get_stage()
self._payload = payload
self._on_payref_added_fn = on_payref_added_fn
def set_payload(self, payload: PrimSelectionPayload):
self._stage = payload.get_stage()
self._payload = payload
def show(self, payrefs: Union[Sdf.Reference, Sdf.Payload]):
self._payrefs = payrefs
fallback = None
if self._stage and not self._stage.GetRootLayer().anonymous:
# If asset path is empty, open the USD rootlayer folder
# But only if filepicker didn't already have a folder remembered (thus fallback)
fallback = self._stage.GetRootLayer().identifier
self._prim_path_model.set_value(DEFAULT_PRIM_TAG)
def _on_file_selected(weak_self, filename, dirname, selections=[]):
weak_self = weak_self()
if not weak_self:
return
if not selections:
return
asset_path = f"{dirname or ''}/{filename}"
edit_layer = weak_self._stage.GetEditTarget().GetLayer()
# make the path relative to current edit target layer
asset_url = clientutils.make_relative_url_if_possible(edit_layer.identifier, asset_path)
prim_path = self._prim_path_model.get_value_as_string()
if prim_path == DEFAULT_PRIM_TAG:
prim_path = Sdf.Path()
payrefs = weak_self._payrefs
if not payrefs:
stage = weak_self._stage
payload_prim_path = weak_self._payload[-1]
if not stage or not payload_prim_path:
carb.log_warn(f"Cannot create payload/reference as stage/prim {payload_prim_path} is invalid")
return
anchor_prim = stage.GetPrimAtPath(payload_prim_path)
if not anchor_prim:
carb.log_warn(f"Cannot create payload/reference as failed to get prim {payload_prim_path}")
return
if weak_self._use_payloads:
anchor_prim.GetPayloads().SetPayloads([])
payrefs = anchor_prim.GetPayloads()
if not payrefs:
carb.log_warn("Failed to create payload")
return
else:
anchor_prim.GetReferences().SetReferences([])
payrefs = anchor_prim.GetReferences()
if not payrefs:
carb.log_warn("Failed to create reference")
return
command_kwargs = {
'stage': payrefs.GetPrim().GetStage(),
'prim_path': payrefs.GetPrim().GetPath()
}
if weak_self._use_payloads:
if prim_path:
payref = Sdf.Payload(asset_url, prim_path)
else:
payref = Sdf.Payload(asset_url)
command = "AddPayload"
command_kwargs['payload'] = payref
else:
if prim_path:
payref = Sdf.Reference(asset_url, prim_path)
else:
payref = Sdf.Reference(asset_url)
command = "AddReference"
command_kwargs['reference'] = payref
omni.kit.commands.execute(command, **command_kwargs)
weak_self._on_payref_added_fn(payrefs.GetPrim())
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Select Payload..." if self._use_payloads else "Select Reference...",
import_button_label="Select",
import_handler=partial(_on_file_selected, weakref.ref(self)),
)
if fallback and not file_importer._dialog.get_current_directory():
file_importer._dialog.set_current_directory(fallback)
file_importer.add_import_options_frame(
"Payload Options" if self._use_payloads else "Reference Options",
AddPayloadReferenceOptionsDelegate(self._prim_path_model)
)
def destroy(self):
self._payrefs = None
self._prim_path_model = None
class PayloadReferenceWidget(UsdPropertiesWidget):
def __init__(self, use_payloads=False):
super().__init__(title="Payloads" if use_payloads else "References", collapsed=False, multi_edit=False)
self._ref_list_op = None
self._payrefs = None
self._ref_dict = {}
self._add_ref_window = [None, None]
self._ref_and_layers = []
self._checkpoint_combobox = None
self._use_payloads = use_payloads
self._payload_loaded_cb = None
self._stage_event_sub = (
omni.usd.get_context()
.get_stage_event_stream()
.create_subscription_to_pop(self._on_stage_event, name="PayloadReferenceWidget stage update")
)
# +add menu item(s)
from .prim_path_widget import PrimPathWidget
PrimPathWidget.add_button_menu_entry(
"Payload" if use_payloads else "Reference", show_fn=self._prim_is_selected, onclick_fn=lambda payload, u=self._use_payloads: self._on_add_payload_reference(payload, u)
)
def _undo_redo_on_change(self, cmds):
async def update_value(cmds):
if cmds and "SetPayLoadLoadSelectedPrimsCommand" in cmds:
last_prim = self._get_prim(self._payload[-1])
if last_prim:
self._payload_loaded_cb.model.set_value(last_prim.IsLoaded())
if cmds and self._payload_loaded_cb:
asyncio.ensure_future(update_value(cmds))
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSING) or event.type == int(omni.usd.StageEventType.OPENED):
for window in self._add_ref_window:
if window:
window.destroy()
self._add_ref_window = [None, None]
def _on_add_payload_reference(self, payload: PrimSelectionPayload, use_payloads: bool):
ref_window_index = 0 if self._use_payloads else 1
if not self._add_ref_window[ref_window_index]:
self._add_ref_window[ref_window_index] = AddPayloadReferenceWindow(payload, self._on_payload_reference_added, use_payloads=use_payloads)
else:
self._add_ref_window[ref_window_index].set_payload(payload)
self._add_ref_window[ref_window_index].show(self._payrefs)
def _on_payload_reference_added(self, prim: Usd.Prim):
property_window = omni.kit.window.property.get_window()
if property_window:
property_window.request_rebuild()
def _prim_is_selected(self, objects: dict):
if not "prim_list" in objects or not "stage" in objects:
return False
stage = objects["stage"]
if not stage:
return False
return len(objects["prim_list"]) == 1
def clean(self):
self.reset()
for window in self._add_ref_window:
if window:
window.destroy()
self._add_ref_window = [None, None]
self._stage_event_sub = None
super().clean()
def reset(self):
if self._listener:
self._listener.Revoke()
self._listener = None
omni.kit.undo.unsubscribe_on_change(self._undo_redo_on_change)
self._ref_list_op = None
self._payrefs = None
for ref, info in self._ref_dict.items():
info.destroy()
self._ref_dict.clear()
self._ref_and_layers.clear()
if self._checkpoint_combobox:
self._checkpoint_combobox.destroy()
self._checkpoint_combobox = None
super().reset()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) != 1: # single edit for now
return False
anchor_prim = None
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim:
return False
anchor_prim = prim
# only show if prim has payloads/references
if anchor_prim:
if self._use_payloads:
ref_and_layers = omni.usd.get_composed_payloads_from_prim(anchor_prim)
return len(ref_and_layers) > 0
ref_and_layers = omni.usd.get_composed_references_from_prim(anchor_prim)
return len(ref_and_layers) > 0
return False
def build_impl(self):
"""
See PropertyWidget.build_impl
"""
if not self._use_payloads:
super().build_impl()
else:
def on_checkbox_toggle(layer_name, model):
async def set_loaded(layer_name, state):
omni.kit.commands.execute("SetPayLoadLoadSelectedPrimsCommand", selected_paths=[layer_name], value=state)
asyncio.ensure_future(set_loaded(layer_name, model.get_value_as_bool()))
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
self._button_frame = ui.Frame()
with self._button_frame:
with ui.ZStack():
super().build_impl()
with ui.HStack():
ui.Spacer(width=ui.Fraction(0.5))
with ui.VStack(width=0, content_clipping=True):
ui.Spacer(height=5)
self._payload_loaded_cb = ui.CheckBox()
self._payload_loaded_cb.model.set_value(last_prim.IsLoaded())
self._payload_loaded_cb.model.add_value_changed_fn(
partial(on_checkbox_toggle, last_prim.GetPath().pathString))
ui.Spacer(width=5)
def build_items(self):
self.reset()
if len(self._payload) == 0:
return
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
stage = last_prim.GetStage()
if not stage:
return
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
omni.kit.undo.subscribe_on_change(self._undo_redo_on_change)
if self._use_payloads:
self._payrefs = last_prim.GetPayloads()
self._ref_and_layers = omni.usd.get_composed_payloads_from_prim(last_prim, False)
else:
self._payrefs = last_prim.GetReferences()
self._ref_and_layers = omni.usd.get_composed_references_from_prim(last_prim, False)
ref_window_index = 0 if self._use_payloads else 1
self._add_ref_window[ref_window_index] = AddPayloadReferenceWindow(self._payload, self._on_payload_reference_added, use_payloads=self._use_payloads)
with ui.VStack(height=0, spacing=5, name="frame_v_stack"):
if self._payrefs:
for (ref, layer) in self._ref_and_layers:
self._build_payload_reference(ref, layer)
def on_add_payload_reference(weak_self):
weak_self = weak_self()
if not weak_self:
return
weak_self._add_ref_window[ref_window_index].show(weak_self._payrefs)
ui.Button(
f"{_get_plus_glyph()} Add Payload" if self._use_payloads else f"{_get_plus_glyph()} Add Reference",
clicked_fn=lambda weak_self=weakref.ref(self): on_add_payload_reference(weak_self),
)
def _build_payload_reference(self, payref: Sdf.Reference, intro_layer: Sdf.Layer):
with ui.Frame():
with ui.ZStack():
ui.Rectangle(name="backdrop")
with ui.VStack(
name="ref_group", spacing=5, style={"VStack::ref_group": {"margin_width": 2, "margin_height": 2}}
):
with ui.HStack(spacing=5):
ui.Spacer(width=5)
with ui.VStack(spacing=5):
asset_path_field = self._build_asset_path_ui(payref, intro_layer)
prim_path_field, prim_path_field_model = self._build_prim_path_ui(payref, intro_layer)
checkpoint_model = self._build_checkpoint_ui(payref, intro_layer)
self._build_remove_payload_reference_button(payref, intro_layer)
self._ref_dict[payref] = PayloadReferenceInfo(
asset_path_field, prim_path_field, prim_path_field_model, checkpoint_model
)
def _build_asset_path_ui(self, payref: Union[Sdf.Reference, Sdf.Payload], intro_layer: Sdf.Layer):
with ui.HStack():
UsdPropertiesWidgetBuilder._create_label("Asset Path", additional_label_kwargs={"width": REF_LABEL_WIDTH})
asset_path_field = build_path_field(
self._payload.get_stage(),
payref.assetPath,
True,
self._use_payloads,
intro_layer,
)
# If payload/reference is not existed
if payref.assetPath:
absolute_path = intro_layer.ComputeAbsolutePath(payref.assetPath)
status, _ = omni.client.stat(absolute_path)
if status != omni.client.Result.OK:
asset_path_field.set_style({"color": 0xFF6F72FF})
asset_path_field.model.add_edited_fn(
lambda model, stage=self._payrefs.GetPrim().GetStage(), prim_path=self._payrefs.GetPrim().GetPath(), payref=payref: self._on_payload_reference_edited(
model, stage, prim_path, payref, intro_layer
)
)
return asset_path_field
def _build_prim_path_ui(self, payref: Union[Sdf.Reference,Sdf.Payload], intro_layer: Sdf.Layer):
with ui.HStack():
UsdPropertiesWidgetBuilder._create_label("Prim Path", additional_label_kwargs={"width": REF_LABEL_WIDTH})
prim_path = payref.primPath
if not prim_path:
prim_path = DEFAULT_PRIM_TAG
prim_path_field_model = TrackEditingStringModel(str(prim_path))
prim_path_field = ui.StringField(model=prim_path_field_model)
prim_path_field.model.add_edited_fn(
lambda model, stage=self._payrefs.GetPrim().GetStage(), prim_path=self._payrefs.GetPrim().GetPath(), payref=payref: self._on_payload_reference_edited(
model, stage, prim_path, payref, intro_layer
)
)
return prim_path_field, prim_path_field_model
def _build_checkpoint_ui(self, payref: Union[Sdf.Reference,Sdf.Payload], intro_layer: Sdf.Layer):
if VersioningHelper.is_versioning_enabled():
try:
# Use checkpoint widget in the drop down menu for more detailed information
from omni.kit.widget.versioning.checkpoint_combobox import CheckpointCombobox
stack = ui.HStack()
with stack:
UsdPropertiesWidgetBuilder._create_label(
"Checkpoint", additional_label_kwargs={"width": REF_LABEL_WIDTH}
)
absolute_asset_path = payref.assetPath
if len(absolute_asset_path):
absolute_asset_path = omni.client.combine_urls(intro_layer.identifier, absolute_asset_path)
def on_selection_changed(
selection,
stage: Usd.Stage,
prim_path: Sdf.Path,
payref: Union[Sdf.Reference, Sdf.Payload],
intro_layer: Sdf.Layer,
):
self._on_payload_reference_checkpoint_edited(selection, stage, prim_path, payref)
self._checkpoint_combobox = CheckpointCombobox(
absolute_asset_path,
lambda selection, stage=self._payrefs.GetPrim().GetStage(), prim_path=self._payrefs.GetPrim().GetPath(), payref=payref: on_selection_changed(
selection, stage, prim_path, payref, intro_layer
),
)
# reset button
def reset_func(payref, stage, prim_path):
client_url = omni.client.break_url(payref.assetPath)
on_selection_changed(None, stage, prim_path, payref, intro_layer)
checkpoint = ""
client_url = omni.client.break_url(payref.assetPath)
if client_url.query:
_, checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
ui.Spacer(width=4)
ui.Image(
f"{ICON_PATH}/Default value.svg" if checkpoint == "" else f"{ICON_PATH}/Changed value.svg",
mouse_pressed_fn=lambda x, y, b, a, s=self._payrefs.GetPrim().GetStage(), r=payref, p=self._payrefs.GetPrim().GetPath(): reset_func(r, s, p),
width=12,
height=18,
tooltip="Reset Checkpoint" if checkpoint else "",
)
def on_have_server_info(server:str, support_checkpoint: bool, stack: ui.HStack):
if not support_checkpoint:
stack.visible = False
VersioningHelper.check_server_checkpoint_support(
VersioningHelper.extract_server_from_url(absolute_asset_path),
lambda s, c, t=stack: on_have_server_info(s,c, t)
)
return None
except ImportError as e:
# If the widget is not available, create a simple combo box instead
carb.log_warn(f"Checkpoint widget in Payload/Reference is not availble due to: {e}")
def _build_remove_payload_reference_button(self, payref, intro_layer):
def on_remove_payload_reference(ref, layer_weak, payrefs):
if not ref or not payrefs:
return
stage = payrefs.GetPrim().GetStage()
edit_target_layer = stage.GetEditTarget().GetLayer()
intro_layer = layer_weak() if layer_weak else None
if self._use_payloads:
# When removing a payload on a different layer, the deleted assetPath should be relative to edit target layer, not introducing layer
if intro_layer and intro_layer != edit_target_layer:
ref = anchor_payload_asset_path_to_layer(ref, intro_layer, edit_target_layer)
omni.kit.commands.execute(
"RemovePayload",
stage=stage,
prim_path=payrefs.GetPrim().GetPath(),
payload=ref,
),
else:
# When removing a reference on a different layer, the deleted assetPath should be relative to edit target layer, not introducing layer
if intro_layer and intro_layer != edit_target_layer:
ref = anchor_reference_asset_path_to_layer(ref, intro_layer, edit_target_layer)
omni.kit.commands.execute(
"RemoveReference",
stage=stage,
prim_path=payrefs.GetPrim().GetPath(),
reference=ref,
),
style = {"image_url": str(ICON_PATH.joinpath("remove.svg")), "margin": 0, "padding": 0}
ui.Button(
style=style,
clicked_fn=lambda ref=payref, layer_weak=weakref.ref(
intro_layer
) if intro_layer else None, refs=self._payrefs: on_remove_payload_reference(ref, layer_weak, refs),
width=16,
)
def _on_payload_reference_edited(
self, model_or_item, stage: Usd.Stage, prim_path: Sdf.Path, payref: Union[Sdf.Reference, Sdf.Payload], intro_layer: Sdf.Layer
):
ref_prim_path = self._ref_dict[payref].prim_path_field.model.get_value_as_string()
ref_prim_path = Sdf.Path(ref_prim_path) if ref_prim_path and ref_prim_path != DEFAULT_PRIM_TAG else Sdf.Path()
new_asset_path = self._ref_dict[payref].asset_path_field.model.get_value_as_string()
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(model_or_item, CheckpointItem):
new_asset_path = replace_query(new_asset_path, model_or_item.get_relative_path())
elif model_or_item is None:
new_asset_path = replace_query(new_asset_path, None)
except Exception as e:
pass
if self._use_payloads:
new_ref = Sdf.Payload(assetPath=new_asset_path.replace("\\", "/"), primPath=ref_prim_path)
edit_target_layer = stage.GetEditTarget().GetLayer()
# When replacing a payload on a different layer, the replaced assetPath should be relative to edit target layer, not introducing layer
if intro_layer != edit_target_layer:
payref = anchor_payload_asset_path_to_layer(payref, intro_layer, edit_target_layer)
if payref == new_ref:
return False
omni.kit.commands.execute(
"ReplacePayload",
stage=stage,
prim_path=prim_path,
old_payload=payref,
new_payload=new_ref,
)
return True
new_ref = Sdf.Reference(assetPath=new_asset_path.replace("\\", "/"), primPath=ref_prim_path)
edit_target_layer = stage.GetEditTarget().GetLayer()
# When replacing a reference on a different layer, the replaced assetPath should be relative to edit target layer, not introducing layer
if intro_layer != edit_target_layer:
payref = anchor_reference_asset_path_to_layer(payref, intro_layer, edit_target_layer)
if payref == new_ref:
return False
omni.kit.commands.execute(
"ReplaceReference",
stage=stage,
prim_path=prim_path,
old_reference=payref,
new_reference=new_ref,
)
return True
def _on_payload_reference_checkpoint_edited(
self, model_or_item, stage: Usd.Stage, prim_path: Sdf.Path, payref: Union[Sdf.Reference, Sdf.Payload]
):
new_asset_path = self._ref_dict[payref].asset_path_field.model.get_value_as_string()
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(model_or_item, CheckpointItem):
new_asset_path = replace_query(new_asset_path, model_or_item.get_relative_path())
elif model_or_item is None:
new_asset_path = replace_query(new_asset_path, None)
except Exception as e:
pass
if self._use_payloads:
new_ref = Sdf.Payload(assetPath=new_asset_path.replace("\\", "/"), primPath=payref.primPath, layerOffset=payref.layerOffset)
if payref != new_ref:
omni.kit.commands.execute(
"ReplacePayload",
stage=stage,
prim_path=prim_path,
old_payload=payref,
new_payload=new_ref,
)
return
new_ref = Sdf.Reference(assetPath=new_asset_path.replace("\\", "/"), primPath=payref.primPath, layerOffset=payref.layerOffset)
if payref != new_ref:
omni.kit.commands.execute(
"ReplaceReference",
stage=stage,
prim_path=prim_path,
old_reference=payref,
new_reference=new_ref,
)
| 34,439 | Python | 40.048868 | 179 | 0.568106 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/control_state_manager.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import weakref
from typing import Callable
import omni.usd
from pxr import Usd
class ControlStateHandler:
def __init__(self, on_refresh_state: Callable, on_build_state: Callable, icon_path: str):
"""
Args:
on_refresh_state (Callable): function to be called when control state refreshes. Callable should returns a tuple(bool, bool).
The first bool decides if the flag of this state should be set. The second bool descides if a force rebuild should be triggered.
on_build_state (Callable): function to be called when build control state UI. Callable should returns a tuple(bool, Callable, str).
If first bool is True, subsequent states with lower (larger value) priority will be skipped.
Second Callable is the action to perform when click on the icon.
Third str is tooltip when hovering over icon.
icon_path (str): path to an SVG file to show next to attribute when this state wins.
"""
self.on_refresh_state = on_refresh_state
self.on_build_state = on_build_state
self.icon_path = icon_path
class ControlStateManager:
_instance = None
@classmethod
def get_instance(cls):
return weakref.proxy(cls._instance)
def __init__(self, icon_path):
self._icon_path = icon_path
self._next_flag = 1
self._control_state_handlers = {}
ControlStateManager._instance = self
self._builtin_handles = []
self._default_icon_path = f"{self._icon_path}/Default value.svg"
self._register_builtin_handlers()
def __del__(self):
self.destory()
def destory(self):
for handle_flag in self._builtin_handles:
self.unregister_control_state(handle_flag)
ControlStateManager.instance = None
def register_control_state(
self, on_refresh_state: Callable, on_build_state: Callable, icon_path: str, priority: float = 0.0
) -> int:
entry = ControlStateHandler(on_refresh_state, on_build_state, icon_path)
flag = self._next_flag
self._next_flag <<= 1
self._add_entry(flag, priority, entry)
return flag
def unregister_control_state(self, flag):
self._control_state_handlers.pop(flag)
def update_control_state(self, usd_model_base):
control_state = 0
force_refresh = False
for flag, (_, handler) in self._control_state_handlers.items():
set_flag, f_refresh = handler.on_refresh_state(usd_model_base)
force_refresh |= f_refresh
if set_flag:
control_state |= flag
return control_state, force_refresh
def build_control_state(self, control_state, **kwargs):
for flag, (_, handler) in self._control_state_handlers.items():
handled, action, tooltip = handler.on_build_state(flag & control_state, **kwargs)
if handled:
return action, handler.icon_path, tooltip
return None, self._default_icon_path, ""
def _add_entry(self, flag: int, priority: float, entry: ControlStateHandler):
self._control_state_handlers[flag] = (priority, entry)
# sort by priority
self._control_state_handlers = {
k: v for k, v in sorted(self._control_state_handlers.items(), key=lambda item: item[1][0])
}
def _register_builtin_handlers(self):
self._builtin_handles.append(self._register_mixed())
self._builtin_handles.append(self._register_connected())
self._builtin_handles.append(self._register_keyed())
self._builtin_handles.append(self._register_sampled())
self._builtin_handles.append(self._register_not_default())
self._builtin_handles.append(self._register_locked())
def _register_mixed(self):
def on_refresh(usd_model_base):
return usd_model_base._ambiguous, True
def on_build(has_state_flag, **kwargs):
model = kwargs.get("model")
widget_comp_index = kwargs.get("widget_comp_index", -1)
mixed_overlay = kwargs.get("mixed_overlay", None)
if mixed_overlay and not isinstance(mixed_overlay, list):
mixed_overlay = [mixed_overlay]
no_mixed = kwargs.get("no_mixed", False)
if not has_state_flag or no_mixed or not model.is_comp_ambiguous(widget_comp_index):
if mixed_overlay:
for overlay in mixed_overlay:
overlay.visible = False
return False, None, None
else:
if mixed_overlay:
# for array only one mixed overlay
if model.is_array_type() and len(mixed_overlay) == 1:
mixed_overlay[0].visible = model.is_ambiguous()
else:
for i, overlay in enumerate(mixed_overlay):
comp_index = max(widget_comp_index, i)
overlay.visible = model.is_comp_ambiguous(comp_index)
return True, None, "Mixed value among selected prims"
icon_path = f"{self._icon_path}/mixed properties.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 0)
def _register_connected(self):
def on_refresh(usd_model_base):
return any(usd_model_base._connections), False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
model = kwargs.get("model")
value_widget = kwargs.get("value_widget", None)
extra_widgets = kwargs.get("extra_widgets", [])
action = None
tooltip = ""
connections = model.get_connections()
if not all(ele == connections[0] for ele in connections):
tooltip = "Attribute have different connections among selected prims."
last_prim_connections = connections[-1]
if len(last_prim_connections) > 0:
if value_widget:
value_widget.enabled = False
for widget in extra_widgets:
widget.enabled = False
if not tooltip:
for path in last_prim_connections:
tooltip += f"{path}\n"
def on_click_connection(*arg, path=last_prim_connections[-1]):
# Get connection on last selected prim
last_prim_connections = model.get_connections()[-1]
if len(last_prim_connections) > 0:
# TODO multi-context, pass context name in payload??
selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([path.GetPrimPath().pathString], True)
action = on_click_connection
return True, action, tooltip
icon_path = f"{self._icon_path}/Expression.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 10)
def _register_locked(self):
def on_refresh(usd_model_base):
return usd_model_base.is_locked(), False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
return True, None, "Value is locked"
icon_path = f"{self._icon_path}/Locked Value.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 20)
def _register_keyed(self):
def on_refresh(usd_model_base):
current_time_code = usd_model_base.get_current_time_code()
for attribute in usd_model_base._get_attributes():
if isinstance(attribute, Usd.Attribute) and omni.usd.attr_has_timesample_on_key(
attribute, current_time_code
):
return True, False
return False, False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
return True, None, "Timesampled keyframe"
icon_path = f"{self._icon_path}/TimeSamples.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 20)
def _register_sampled(self):
def on_refresh(usd_model_base):
return usd_model_base._might_be_time_varying, False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
return True, None, "Timesampled value"
icon_path = f"{self._icon_path}/TimeVarying.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 30)
def _register_not_default(self):
def on_refresh(usd_model_base):
return usd_model_base.is_different_from_default(), False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
model = kwargs.get("model")
widget_comp_index = kwargs.get("widget_comp_index", -1)
return True, lambda *_: model.set_default(widget_comp_index), "Value different from default"
icon_path = f"{self._icon_path}/Changed value.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 40)
| 9,864 | Python | 38.778226 | 144 | 0.598844 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/attribute_context_menu.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import weakref
from functools import partial
import carb
import omni.kit.commands
import omni.kit.context_menu
import omni.kit.undo
import omni.usd
from omni.kit.usd.layers import LayerEditMode, get_layers
from pxr import Sdf
from .usd_attribute_model import (
GfVecAttributeModel,
MdlEnumAttributeModel,
TfTokenAttributeModel,
UsdAttributeModel,
UsdBase,
)
class AttributeContextMenuEvent:
def __init__(self, widget, attribute_paths, stage, time_code, model, comp_index):
self.widget = widget
self.attribute_paths = attribute_paths
self.stage = stage
self.time_code = time_code
self.model = model
self.comp_index = comp_index
self.type = 0
class AttributeContextMenu:
_instance = None
@classmethod
def get_instance(cls):
return weakref.proxy(cls._instance)
def __init__(self):
self._register_context_menus()
AttributeContextMenu._instance = self
def __del__(self):
self.destroy()
def destroy(self):
self._copy_menu_entry = None
self._paste_menu_entry = None
self._delete_menu_entry = None
self._copy_path_menu_entry = None
AttributeContextMenu._instance = None
def on_mouse_event(self, event: AttributeContextMenuEvent):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE):
return
# setup objects, this is passed to all functions
objects = {
"widget": event.widget,
"stage": event.stage,
"attribute_paths": event.attribute_paths,
"time_code": event.time_code,
"model": event.model,
"comp_index": event.comp_index,
}
menu_list = omni.kit.context_menu.get_menu_dict("attribute", "omni.kit.property.usd")
stage = event.stage
if stage:
usd_context = omni.usd.get_context()
layers = get_layers(usd_context)
edit_mode = layers.get_edit_mode()
auto_authoring = layers.get_auto_authoring()
layers_state = layers.get_layers_state()
if edit_mode == LayerEditMode.SPECS_LINKING:
per_layer_link_menu = []
for layer in stage.GetLayerStack():
if auto_authoring.is_auto_authoring_layer(layer.identifier):
continue
layer_name = layers_state.get_layer_name(layer.identifier)
per_layer_link_menu.append(
{
"name": {
f"{layer_name}": [
{
"name": "Link",
"show_fn": [],
"onclick_fn": partial(self._link_attributes, True, layer.identifier),
},
{
"name": "Unlink",
"show_fn": [],
"onclick_fn": partial(self._link_attributes, False, layer.identifier),
},
]
}
}
)
menu_list.append(
{
"name": {"Layers": per_layer_link_menu},
"glyph": "",
}
)
menu_list.extend([{"name": ""}])
menu_list.append(
{
"name": {
"Locks": [
{
"name": "Lock",
"show_fn": [],
"onclick_fn": partial(self._lock_attributes, True),
},
{
"name": "Unlock",
"show_fn": [],
"onclick_fn": partial(self._lock_attributes, False),
},
]
},
"glyph": "",
}
)
omni.kit.context_menu.get_instance().show_context_menu("attribute", objects, menu_list)
def _link_attributes(self, link_or_unlink, layer_identifier, objects):
attribute_paths = objects.get("attribute_paths", None)
if not attribute_paths:
return
if link_or_unlink:
command = "LinkSpecs"
else:
command = "UnlinkSpecs"
omni.kit.commands.execute(command, spec_paths=attribute_paths, layer_identifiers=layer_identifier)
def _lock_attributes(self, lock_or_unlock, objects):
attribute_paths = objects.get("attribute_paths", None)
if not attribute_paths:
return
if lock_or_unlock:
command = "LockSpecs"
else:
command = "UnlockSpecs"
omni.kit.commands.execute(command, spec_paths=attribute_paths)
def _register_context_menus(self):
self._register_copy_paste_menus()
self._register_delete_prop_menu()
self._register_copy_prop_path_menu()
def _register_copy_paste_menus(self):
def can_show_copy_paste(object):
model = object.get("model", None)
if not model:
return False
return isinstance(model, UsdBase)
def can_copy(object):
model: UsdBase = object.get("model", None)
if not model:
return False
# Only support copying during single select per OM-20206
paths = model.get_property_paths()
if len(paths) > 1:
return False
comp_index = object.get("comp_index", -1)
return not model.is_comp_ambiguous(comp_index) and (
isinstance(model, UsdAttributeModel)
or isinstance(model, TfTokenAttributeModel)
or isinstance(model, MdlEnumAttributeModel)
or isinstance(model, GfVecAttributeModel)
)
def on_copy(object):
model = object.get("model", None)
if not model:
return
if isinstance(model, UsdAttributeModel):
value_str = model.get_value_as_string(elide_big_array=False)
elif isinstance(model, TfTokenAttributeModel):
value_str = model.get_value_as_token()
elif isinstance(model, MdlEnumAttributeModel):
value_str = model.get_value_as_string()
elif isinstance(model, GfVecAttributeModel):
value_str = str(model._construct_vector_from_item())
else:
carb.log_warn("Unsupported type to copy")
return
omni.kit.clipboard.copy(value_str)
menu = {
"name": "Copy",
"show_fn": can_show_copy_paste,
"enabled_fn": can_copy,
"onclick_fn": on_copy,
}
self._copy_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
# If type conversion fails, function raise exception and disables menu entry/quit paste
def convert_type(value_type, value_str: str):
if value_type == str or value_type == Sdf.AssetPath or value_type == Sdf.Path:
return value_str
if value_type == Sdf.AssetPathArray:
# Copied AssetPathArray is in this format:
# [@E:/USD/foo.usd@, @E:/USD/bar.usd@]
# parse it manually
value_str = value_str.strip("[] ")
paths = value_str.split(", ")
paths = [path.strip("@") for path in paths]
return paths
else:
# Use an eval here so tuple/list/etc correctly converts from string. May need revisit.
return value_type(eval(value_str))
def can_paste(object):
model = object.get("model", None)
widget = object.get("widget", None)
if not model:
return False
if not widget or not widget.enabled:
return False
comp_index = object.get("comp_index", -1)
paste = omni.kit.clipboard.paste()
if paste:
try:
ret = True
if isinstance(model, UsdAttributeModel):
value = model.get_value_by_comp(comp_index)
convert_type(type(value), paste)
elif isinstance(model, TfTokenAttributeModel):
if not model.is_allowed_token(paste):
raise ValueError(f"Token {paste} is not allowed on this attribute")
elif isinstance(model, MdlEnumAttributeModel):
if not model.is_allowed_enum_string(paste):
raise ValueError(f"Enum {paste} is not allowed on this attribute")
elif isinstance(model, GfVecAttributeModel):
value = model.get_value()
convert_type(type(value), paste)
else:
carb.log_warn("Unsupported type to paste to")
ret = False
return ret
except Exception as e:
carb.log_warn(f"{e}")
pass
return False
def on_paste(object):
model = object.get("model", None)
if not model:
return
comp_index = object.get("comp_index", -1)
value = model.get_value_by_comp(comp_index)
paste = omni.kit.clipboard.paste()
if paste:
try:
if (
isinstance(model, UsdAttributeModel)
or isinstance(model, TfTokenAttributeModel)
or isinstance(model, GfVecAttributeModel)
):
typed_value = convert_type(type(value), paste)
model.set_value(typed_value)
elif isinstance(model, MdlEnumAttributeModel):
model.set_from_enum_string(paste)
except Exception as e:
carb.log_warn(f"Failed to paste: {e}")
menu = {
"name": "Paste",
"show_fn": can_show_copy_paste,
"enabled_fn": can_paste,
"onclick_fn": on_paste,
}
self._paste_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
def _register_delete_prop_menu(self):
def can_show_delete(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
# OM-49324 Hide the Remove context menu for xformOp attributes
# Cannot simply remove an xformOp attribute. Leave it to transform widget context menu
paths = model.get_attribute_paths()
for path in paths:
prop = stage.GetPropertyAtPath(path)
if not prop or prop.GetName().startswith("xformOp:"):
return False
return isinstance(model, UsdBase)
def can_delete(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
paths = model.get_attribute_paths()
for path in paths:
prop = stage.GetPropertyAtPath(path)
if prop:
prim = prop.GetPrim()
prim_definition = prim.GetPrimDefinition()
# If the property is part of a schema, it cannot be completely removed. Removing it will simply reset to default value
prop_spec = prim_definition.GetSchemaPropertySpec(prop.GetPath().name)
if prop_spec:
return False
else:
return False
return True
def on_delete(object):
model = object.get("model", None)
if not model:
return
paths = model.get_attribute_paths()
with omni.kit.undo.group():
for path in paths:
omni.kit.commands.execute("RemoveProperty", prop_path=path)
menu = {
"name": "Remove",
"show_fn": can_show_delete,
"enabled_fn": can_delete,
"onclick_fn": on_delete,
}
self._delete_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
def _register_copy_prop_path_menu(self):
def can_show_copy_path(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
return isinstance(model, UsdBase)
def can_copy_path(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
paths = model.get_attribute_paths()
return len(paths) == 1
def on_copy_path(object):
model = object.get("model", None)
if not model:
return
paths = model.get_attribute_paths()
omni.kit.clipboard.copy(paths[-1].pathString)
menu = {
"name": "Copy Property Path",
"show_fn": can_show_copy_path,
"enabled_fn": can_copy_path,
"onclick_fn": on_copy_path,
}
self._copy_path_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
| 14,703 | Python | 34.602905 | 138 | 0.504183 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_object_model.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 omni.kit.commands
import omni.timeline
import omni.ui as ui
import omni.usd
from .usd_model_base import UsdBase
from typing import List
from pxr import Usd, Sdf
class MetadataObjectModel(ui.AbstractItemModel, UsdBase):
"""The value model that is reimplemented in Python to watch a USD paths.
Paths can be either Attribute or Prim paths"""
def __init__(
self,
stage: Usd.Stage,
object_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
key: str,
default,
options: list,
):
UsdBase.__init__(self, stage, object_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._key = key
self._default_value = default
self._combobox_options = options
self._update_option()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._options
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self):
carb.log_warn("begin_edit not supported in MetadataObjectModel")
def end_edit(self):
carb.log_warn("end_edit not supported in MetadataObjectModel")
def _current_index_changed(self, model):
if not self._has_index:
return
index = model.as_int
if self.set_value(self._options[index].value):
self._item_changed(None)
def _update_option(self):
class OptionItem(ui.AbstractItem):
def __init__(self, display_name: str, value: int):
super().__init__()
self.model = ui.SimpleStringModel(display_name)
self.value = value
self._options = []
for index, option in enumerate(self._combobox_options):
self._options.append(OptionItem(option, int(index)))
def _update_value(self, force=False):
if self._update_value_objects(force, self._get_objects()):
index = -1
for i in range(0, len(self._options)):
if self._options[i].model.get_value_as_string() == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._has_index = False
self._current_index.set_value(index)
self._item_changed(None)
self._has_index = True
def _on_dirty(self):
self._update_value()
def set_value(self, value, comp=-1):
if comp != -1:
carb.log_warn("Arrays not supported in MetadataObjectModel")
self._update_value(True) # reset value
return False
if not self._ambiguous and not any(self._comp_ambiguous) and value == self._value:
return False
self._value = self._combobox_options[int(value)]
objects = self._get_objects()
if len(objects) == 0:
return False
self._write_value(objects=objects, key=self._key, value=self._value)
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
self.update_control_state()
return True
def _read_value(self, object: Usd.Object, time_code: Usd.TimeCode):
value = object.GetMetadata(self._key)
if not value:
value = self._default_value
return value
def _write_value(self, objects: list, key: str, value):
path_list = []
for object in objects:
path_list.append(object.GetPath())
omni.kit.commands.execute("ChangeMetadata", object_paths=path_list, key=key, value=value)
| 4,450 | Python | 31.97037 | 97 | 0.613034 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/versioning_helper.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
import omni.client
class VersioningHelper:
server_cache = {}
@staticmethod
def is_versioning_enabled():
try:
import omni.kit.widget.versioning
enable_versioning = True
except:
enable_versioning = False
return enable_versioning
@staticmethod
def extract_server_from_url(url):
client_url = omni.client.break_url(url)
server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port)
return server_url
@staticmethod
def check_server_checkpoint_support(server: str, on_complete: callable):
if not server:
on_complete(server, False)
return
if server in VersioningHelper.server_cache:
on_complete(server, VersioningHelper.server_cache[server])
return
async def update_server_can_save_checkpoint():
result, server_info = await omni.client.get_server_info_async(server)
support_checkpoint = result and server_info and server_info.checkpoints_enabled
on_complete(server, support_checkpoint)
VersioningHelper.server_cache[server] = support_checkpoint
asyncio.ensure_future(update_server_can_save_checkpoint())
| 1,743 | Python | 31.296296 | 111 | 0.686173 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/custom_layout_helper.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.
#
from collections import OrderedDict
from .usd_property_widget import UsdPropertyUiEntry
stack = []
class Container:
def __init__(self, hide_if_true=None, show_if_true=None):
self._children = []
self._container_name = ""
self._collapsed = False
self._is_visible = True
if isinstance(hide_if_true, bool):
self._is_visible = not hide_if_true
if isinstance(show_if_true, bool):
self._is_visible = show_if_true
def __enter__(self):
stack.append(self)
def __exit__(self, exc_type, exc_value, tb):
stack.pop()
def add_child(self, item):
self._children.append(item)
def get_name(self):
return self._container_name
def get_collapsed(self):
return self._collapsed
def is_visible(self):
return self._is_visible
class CustomLayoutProperty:
def __init__(self, prop_name, display_name=None, build_fn=None, hide_if_true=None, show_if_true=None):
self._prop_name = prop_name
self._display_name = display_name
self._build_fn = build_fn # TODO
self._is_visible = True
if isinstance(hide_if_true, bool):
self._is_visible = not hide_if_true
if isinstance(show_if_true, bool):
self._is_visible = show_if_true
global stack
stack[-1].add_child(self)
def get_property_name(self):
return self._prop_name
def get_display_name(self):
return self._display_name
def get_build_fn(self):
return self._build_fn
def is_visible(self):
return self._is_visible
class CustomLayoutGroup(Container):
def __init__(self, container_name, collapsed=False, hide_if_true=None, show_if_true=None):
super().__init__(hide_if_true=hide_if_true, show_if_true=show_if_true)
self._container_name = container_name
self._collapsed = collapsed
global stack
stack[-1].add_child(self)
class CustomLayoutFrame(Container):
def __init__(self, hide_extra=False):
super().__init__()
self._hide_extra = hide_extra
def apply(self, props):
customized_props = []
# preprocess to speed up lookup
props_dict = OrderedDict()
for prop in props:
props_dict[prop[0]] = prop
self._process_container(self, props_dict, customized_props, "")
# add the remaining
if not self._hide_extra:
for prop in props_dict.values():
customized_props.append(prop)
return customized_props
def _process_container(self, container, props_dict, customized_props, group_name):
for child in container._children:
if isinstance(child, Container):
if child.is_visible():
prefix = group_name + f":{child.get_name()}" if group_name else child.get_name()
self._process_container(child, props_dict, customized_props, prefix)
elif isinstance(child, CustomLayoutProperty):
if child.is_visible():
prop_name = child.get_property_name()
collapsed = container.get_collapsed()
prop = props_dict.pop(prop_name, None) # get and remove
if prop:
if group_name != "":
prop.override_display_group(group_name, collapsed)
display_name = child.get_display_name()
if display_name:
prop.override_display_name(display_name)
prop.build_fn = child.get_build_fn()
customized_props.append(prop)
elif child.get_build_fn():
prop = UsdPropertyUiEntry("", group_name, "", None, child.get_build_fn(), collapsed)
customized_props.append(prop)
| 4,362 | Python | 33.904 | 108 | 0.592618 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/add_attribute_popup.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 weakref
import carb
import omni.kit.commands
import omni.kit.undo
import omni.ui as ui
from pxr import Sdf
from .prim_selection_payload import PrimSelectionPayload
class ValueTypeNameItem(ui.AbstractItem):
def __init__(self, value_type_name: Sdf.ValueTypeName, value_type_name_str: str):
super().__init__()
self.value_type_name = value_type_name
self.model = ui.SimpleStringModel(value_type_name_str)
class VariabilityItem(ui.AbstractItem):
def __init__(self, variability: Sdf.Variability, Variability_str: str):
super().__init__()
self.variability = variability
self.model = ui.SimpleStringModel(Variability_str)
class ComboBoxModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._items = []
self._populate_items()
def _populate_items(self):
...
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
def get_selected_item(self):
return self._items[self._current_index.get_value_as_int()]
class ValueTypeNameModel(ComboBoxModel):
def _populate_items(self):
for property in dir(Sdf.ValueTypeNames):
type_name = getattr(Sdf.ValueTypeNames, property)
if isinstance(type_name, Sdf.ValueTypeName):
self._items.append(ValueTypeNameItem(type_name, property))
class VariabilityModel(ComboBoxModel):
def _populate_items(self):
self._items = [
VariabilityItem(Sdf.VariabilityVarying, "Varying"),
VariabilityItem(Sdf.VariabilityUniform, "Uniform"),
]
class AddAttributePopup:
def __init__(self):
self._add_attribute_window = ui.Window(
"Add Attribute...", visible=False, flags=ui.WINDOW_FLAGS_NO_RESIZE, auto_resize=True
)
with self._add_attribute_window.frame:
with ui.VStack(height=0, spacing=5):
LABEL_WIDTH = 80
WIDGET_WIDTH = 300
with ui.HStack(width=0):
ui.Label("Name", width=LABEL_WIDTH)
self._add_attr_name_field = ui.StringField(width=WIDGET_WIDTH)
self._add_attr_name_field.model.set_value("new_attr")
with ui.HStack(width=0):
ui.Label("Type", width=LABEL_WIDTH)
self._value_type_name_model = ValueTypeNameModel()
ui.ComboBox(self._value_type_name_model, width=WIDGET_WIDTH)
with ui.HStack(width=0):
ui.Label("Custom", width=LABEL_WIDTH)
self._custom_checkbox = ui.CheckBox()
self._custom_checkbox.model.set_value(True)
with ui.HStack(width=0):
ui.Label("Variability", width=LABEL_WIDTH)
self._variability_model = VariabilityModel()
ui.ComboBox(self._variability_model, width=WIDGET_WIDTH)
self._error_msg_label = ui.Label(
"",
visible=False,
style={"color": 0xFF0000FF},
)
with ui.HStack():
ui.Spacer()
def on_add(weak_self):
ref_self = weak_self()
error_message = ""
if ref_self:
stage = ref_self._add_attribute_window_payload.get_stage()
if stage:
selected_item = ref_self._value_type_name_model.get_selected_item()
value_type_name = selected_item.value_type_name
attr_name = ref_self._add_attr_name_field.model.get_value_as_string()
custom = ref_self._custom_checkbox.model.get_value_as_bool()
variability = ref_self._variability_model.get_selected_item().variability
if Sdf.Path.IsValidNamespacedIdentifier(attr_name):
try:
omni.kit.undo.begin_group()
for path in ref_self._add_attribute_window_payload:
path = Sdf.Path(path).AppendProperty(attr_name)
prop = stage.GetPropertyAtPath(path)
if prop:
error_message = "One or more attribute to be created already exists."
else:
omni.kit.commands.execute(
"CreateUsdAttributeOnPath",
attr_path=path,
attr_type=value_type_name,
custom=custom,
variability=variability,
)
finally:
omni.kit.undo.end_group()
else:
error_message = f'Invalid identifier "{attr_name}"'
if error_message:
ref_self._error_msg_label.visible = True
ref_self._error_msg_label.text = error_message
carb.log_warn(error_message)
else:
ref_self._add_attribute_window.visible = False
ui.Button("Add", clicked_fn=lambda weak_self=weakref.ref(self): on_add(weak_self))
def on_cancel(weak_self):
ref_self = weak_self()
if ref_self:
ref_self._add_attribute_window.visible = False
ui.Button("Cancel", clicked_fn=lambda weak_self=weakref.ref(self): on_cancel(weak_self))
ui.Spacer()
def show_fn(self, objects: dict):
if not "prim_list" in objects or not "stage" in objects:
return False
stage = objects["stage"]
if not stage:
return False
return len(objects["prim_list"]) >= 1
def click_fn(self, payload: PrimSelectionPayload):
self._add_attribute_window.visible = True
self._add_attribute_window_payload = payload
self._error_msg_label.visible = False
def __del__(self):
self.destroy()
def destroy(self):
self._add_attribute_window = None
self._add_attribute_window_payload = None
self._error_msg_label = None
self._add_attr_name_field = None
self._value_type_name_model = None
| 7,633 | Python | 39.391534 | 117 | 0.51749 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_material_subid_property.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 os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class ShaderMaterialSubidProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_shader_material_subid_property(self):
import omni.kit.commands
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ['/World/Cone', '/World/Cylinder', '/World/Cube', '/World/Sphere']
# bind OmniSurface_Plastic to prims
omni.kit.commands.execute('BindMaterial', material_path='/World/Looks/OmniSurface_Plastic', prim_path=to_select)
# wait for material to load & UI to refresh
await wait_stage_loading()
# select OmniSurface_Plastic shader
await select_prims(['/World/Looks/OmniSurface_Plastic/Shader'])
await ui_test.human_delay()
# get OmniSurface_Plastic shader
prim = stage.GetPrimAtPath('/World/Looks/OmniSurface_Plastic/Shader')
shader = UsdShade.Shader(prim)
# get subid widget
property_widget = ui_test.find("Property//Frame/**/ComboBox[*].identifier=='sdf_asset_info:mdl:sourceAsset:subIdentifier'")
if property_widget.widget.enabled:
items = property_widget.model.get_item_children(None)
for item in items:
# change selection
property_widget.model.set_value(item.token)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify shader value
self.assertTrue(shader.GetSourceAssetSubIdentifier('mdl') == item.token)
| 2,547 | Python | 37.02985 | 131 | 0.681979 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_material_edits_and_undo.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 os
import carb
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf, Usd
class TestMaterialEditsAndUndo(omni.kit.test.AsyncTestCase):
def __init__(self, tests=()):
super().__init__(tests)
# Before running each test
async def setUp(self):
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
self._stage = self._usd_context.get_stage()
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows(topleft_window="Property", topleft_height=64, topleft_width=800.0)
renderer = "rtx"
if renderer not in self._usd_context.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(renderer, self._usd_context)
await self.wait()
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
async def wait(self, updates=3):
for i in range(updates):
await omni.kit.app.get_app().next_update_async()
async def test_l2_material_edits_and_undo(self):
widget_compare_table = {
Sdf.ValueTypeNames.Half2.type: (Gf.Vec2h(0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float2.type: (Gf.Vec2f(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double2.type: (Gf.Vec2d(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half3.type: (Gf.Vec3h(0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float3.type: (Gf.Vec3f(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double3.type: (Gf.Vec3d(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half4.type: (Gf.Vec4h(0.12345, 0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float4.type: (Gf.Vec4f(0.12345, 0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double4.type: (Gf.Vec4d(0.12345, 0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Int2.type: Gf.Vec2i(9999, 9999),
Sdf.ValueTypeNames.Int3.type: Gf.Vec3i(9999, 9999, 9999),
Sdf.ValueTypeNames.Int4.type: Gf.Vec4i(9999, 9999, 9999, 9999),
Sdf.ValueTypeNames.UChar.type: 99,
Sdf.ValueTypeNames.UInt.type: 99,
Sdf.ValueTypeNames.Int.type: 9999,
Sdf.ValueTypeNames.Int64.type: 9999,
Sdf.ValueTypeNames.UInt64.type: 9999,
}
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
# wait for material to load & UI to refresh
await wait_stage_loading()
material_path = "/OmniPBR"
omni.kit.commands.execute("CreateMdlMaterialPrim", mtl_url="OmniPBR.mdl", mtl_name="OmniPBR", mtl_path=material_path)
prim_path = "/OmniPBR/Shader"
self._usd_context.add_to_pending_creating_mdl_paths(prim_path, True, True)
await self.wait()
await select_prims([prim_path])
# Loading all inputs
await self.wait()
all_widgets = ui_test.find_all("Property//Frame/**/.identifier!=''")
for w in all_widgets:
id = w.widget.identifier
if id.startswith("float_slider_"):
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
old_value = attr.Get()
widget_old_value = w.widget.model.get_value()
new_value = 0.3456
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
await w.input(str(new_value))
await ui_test.human_delay()
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
self.assertAlmostEqual(attr.Get(), new_value, places=4)
self.assertAlmostEqual(w.widget.model.get_value(), new_value, places=4)
omni.kit.undo.undo()
w.widget.scroll_here_y(0.5)
self.assertAlmostEqual(attr.Get(), old_value, places=4)
await self.wait()
self.assertAlmostEqual(w.widget.model.get_value(), widget_old_value, places=4)
elif id.startswith("integer_slider_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[15:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = old_value + 1
sdr_metadata = attr.GetMetadata("sdrMetadata")
if sdr_metadata and sdr_metadata.get("options", None):
is_mdl_enum = True
else:
is_mdl_enum = False
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
if is_mdl_enum:
attr.Set(old_value)
w.widget.model.set_value(new_value)
else:
await w.input(str(new_value))
await ui_test.human_delay()
self.assertEqual(attr.Get(), new_value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
elif id.startswith("drag_per_channel_int"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/IntSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/IntDrag[*]")
self.assertNotEqual(sub_widgets, [])
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
old_value = attr.Get()
for child in sub_widgets:
child.model.set_value(0)
await child.input("9999")
await ui_test.human_delay()
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value = widget_compare_table[type_name]
self.assertEqual(attr.Get(), value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
elif id.startswith("drag_per_channel_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
old_value = attr.Get()
for child in sub_widgets:
await child.input("0.12345")
await self.wait()
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value, places = widget_compare_table[type_name]
self.assertTrue(Gf.IsClose(attr.Get(), value, 1e-3))
# Undo all channels
for i in range(len(sub_widgets)):
omni.kit.undo.undo()
await self.wait()
self.assertTrue(Gf.IsClose(attr.Get(), old_value, 1e-04), f"{attr.Get()} != {old_value}")
for i, child in enumerate(sub_widgets):
self.assertAlmostEqual(child.model.get_value()[i], old_value[i], places=places)
elif id.startswith("bool_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[5:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = not old_value
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
attr.Set(old_value)
w.widget.model.set_value(new_value)
await ui_test.human_delay()
self.assertEqual(attr.Get(), new_value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
elif id.startswith("sdf_asset_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[10:])
await ui_test.human_delay()
old_value = attr.Get()
if isinstance(old_value, Sdf.AssetPath):
old_value = old_value.path
# Skips mdl field
if old_value.startswith("OmniPBR"):
continue
new_value = "testpath/abc.png"
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
attr.Set(old_value)
w.widget.model.set_value(new_value)
await ui_test.human_delay()
self.assertEqual(attr.Get(), new_value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
| 10,657 | Python | 43.781512 | 125 | 0.559444 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_mixed_variant.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 os
import omni.kit.app
import omni.usd
import omni.kit.undo
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class PrimMixedVariantProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "usd_variants/ThreeDollyVariantStage.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_mixed_variant_property(self):
import omni.kit.commands
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select single variant prim
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual'])
await ui_test.human_delay()
# verify mixed is not shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# select two variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01'])
await ui_test.human_delay()
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# select two variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_02'])
await ui_test.human_delay()
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# select all threee variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_02'])
await ui_test.human_delay()
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
async def test_l1_mixed_variant_property_set_value(self):
import omni.kit.commands
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select all threee variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_02'])
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_boxvariant'")
items = [item.model.get_value_as_string() for item in widget.model.get_item_children(None) if item.model.get_value_as_string() != ""]
for item in items:
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_boxvariant'")
widget.model.set_value(item)
await ui_test.human_delay()
# verify mixed is not shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# verify mixed is not shown
omni.kit.undo.redo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_palettevariant'")
items = [item.model.get_value_as_string() for item in widget.model.get_item_children(None) if item.model.get_value_as_string() != ""]
for item in items:
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_palettevariant'")
widget.model.set_value(item)
await ui_test.human_delay()
# verify mixed is not shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# verify mixed is not shown
omni.kit.undo.redo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
| 8,289 | Python | 46.102272 | 187 | 0.654241 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/create_prims.py | import os
import carb
import carb.settings
import omni.kit.commands
from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux
def create_test_stage():
stage = omni.usd.get_context().get_stage()
rootname = ""
if stage.HasDefaultPrim():
rootname = stage.GetDefaultPrim().GetPath().pathString
prim_path = "{}/defaultLight".format(rootname)
# Create basic DistantLight
omni.kit.commands.execute(
"CreatePrim",
prim_path=prim_path,
prim_type="DistantLight",
select_new_prim=False,
attributes={UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000},
create_default_xform=True,
)
return prim_path
| 686 | Python | 24.444444 | 77 | 0.663265 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_usd_api.py | import carb
import unittest
import omni.kit.test
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading
class TestUsdAPI(omni.kit.test.AsyncTestCase):
async def setUp(self):
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows("Stage", 200)
await omni.usd.get_context().new_stage_async()
self._prim_path = omni.kit.property.usd.tests.create_test_stage()
async def tearDown(self):
pass
async def test_usd_api(self):
from omni.kit.property.usd import PrimPathWidget
# test PrimPathWidget.*_button_menu_entry
button_menu_entry = PrimPathWidget.add_button_menu_entry(
path="TestUsdAPI/Test Entry", glyph=None, name_fn=None, show_fn=None, enabled_fn=None, onclick_fn=None
)
self.assertTrue(button_menu_entry != None)
button_menu_entries = PrimPathWidget.get_button_menu_entries()
self.assertTrue(button_menu_entry in button_menu_entries)
PrimPathWidget.remove_button_menu_entry(button_menu_entry)
button_menu_entries = PrimPathWidget.get_button_menu_entries()
self.assertFalse(button_menu_entry in button_menu_entries)
# test PrimPathWidget.*_path_item
path_func_updates = 0
def my_path_func():
nonlocal path_func_updates
path_func_updates += 1
# select prim so prim path widget is drawn
usd_context = omni.usd.get_context()
usd_context.get_selection().set_selected_prim_paths([self._prim_path], True)
PrimPathWidget.add_path_item(my_path_func)
path_items = PrimPathWidget.get_path_items()
self.assertTrue(my_path_func in path_items)
await ui_test.human_delay(10)
self.assertTrue(path_func_updates == 1)
PrimPathWidget.rebuild()
await ui_test.human_delay(10)
self.assertTrue(path_func_updates == 2)
PrimPathWidget.remove_path_item(my_path_func)
self.assertFalse(my_path_func in path_items)
PrimPathWidget.rebuild()
await ui_test.human_delay(10)
self.assertTrue(path_func_updates == 2)
usd_context.get_selection().set_selected_prim_paths([], True)
| 2,239 | Python | 36.966101 | 114 | 0.667262 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/basic_types_ui.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
class TestBasicTypesRange(OmniUiTest):
def __init__(self, tests=()):
super().__init__(tests)
self._widget_compare_table = {
Sdf.ValueTypeNames.Half2.type: (Gf.Vec2h(0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float2.type: (Gf.Vec2f(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double2.type: (Gf.Vec2d(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half3.type: (Gf.Vec3h(0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float3.type: (Gf.Vec3f(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double3.type: (Gf.Vec3d(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half4.type: (Gf.Vec4h(0.12345, 0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float4.type: (Gf.Vec4f(0.12345, 0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double4.type: (Gf.Vec4d(0.12345, 0.12345, 0.12345, 0.12345), 4),
}
# Before running each test
async def setUp(self):
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, arrange_windows
await arrange_windows(topleft_window="Property", topleft_height=64, topleft_width=800.0)
await open_stage(get_test_data_path(__name__, "usd/types.usda"))
await self._show_raw(False)
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
await self._show_raw(True)
async def _show_raw(self, new_state):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims
await select_prims(["/defaultPrim/in_0"])
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if w.widget.title == "Raw USD Properties":
w.widget.collapsed = new_state
# change prim selection immediately after collapsed state change can result in one bad frame
# i.e. selection change event happens before frame UI rebuild, and old widget models are already destroyed.
await ui_test.human_delay()
await select_prims([])
async def test_l1_basic_type_coverage_ui(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
UsdPropertiesWidgetBuilder.reset_builder_coverage_table()
stage = omni.usd.get_context().get_stage()
# wait for material to load & UI to refresh
await wait_stage_loading()
for prim_path in ["/defaultPrim/in_0", "/defaultPrim/in_1", "/defaultPrim/out_0"]:
await select_prims([prim_path])
# scroll so all prims are queryable
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
# create attribute used table
prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
attr_list = {}
for attr in prim.GetAttributes():
attr_list[attr.GetPath().name] = attr.GetTypeName().type.typeName
# remove all widgets from attribute used table
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
id = w.widget.identifier
for type in [
"bool_",
"float_slider_",
"integer_slider_",
"drag_per_channel_",
"boolean_per_channel_",
"token_",
"string_",
"timecode_",
"sdf_asset_array_", # must before "sdf_asset_"
"sdf_asset_",
"fallback_",
]:
if id.startswith(type):
attr_id = id[len(type) :]
# ignore placeholder widgets
if attr_id in attr_list:
del attr_list[attr_id]
break
# check attribute used table is empty
self.assertTrue(attr_list == {}, f"USD attribute {attr_list} have no widgets")
widget_builder_coverage_table = UsdPropertiesWidgetBuilder.widget_builder_coverage_table
for widget_type, builder_state in widget_builder_coverage_table.items():
self.assertTrue(builder_state, f"Failed to test {widget_type}")
async def test_l2_float_rounding(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
# wait for material to load & UI to refresh
await wait_stage_loading()
stage = omni.usd.get_context().get_stage()
for prim_path in ["/defaultPrim/in_0", "/defaultPrim/in_1", "/defaultPrim/out_0"]:
await select_prims([prim_path])
# test float types
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
id = w.widget.identifier
if id.startswith("float_slider_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
await w.input("0.12345")
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
self.assertAlmostEqual(attr.Get(), 0.12345, places=4)
elif id.startswith("drag_per_channel_"):
if id.startswith("drag_per_channel_int"):
continue
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
child.model.set_value(0)
await child.input("0.12345")
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value, places = self._widget_compare_table[type_name]
self.assertAlmostEqual(attr.Get(), value, places=places)
async def test_l2_float_rounding_tab(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
from carb.input import KeyboardInput
# wait for material to load & UI to refresh
await wait_stage_loading()
stage = omni.usd.get_context().get_stage()
for prim_path in ["/defaultPrim/in_0", "/defaultPrim/in_1", "/defaultPrim/out_0"]:
await select_prims([prim_path])
# test float types
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
id = w.widget.identifier
if id.startswith("float_slider_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
await w.input("0.12345", end_key=KeyboardInput.TAB)
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
self.assertAlmostEqual(attr.Get(), 0.12345, places=4)
elif id.startswith("drag_per_channel_"):
if id.startswith("drag_per_channel_int"):
continue
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
child.model.set_value(0)
await child.input("0.12345", end_key=KeyboardInput.TAB)
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value, places = self._widget_compare_table[type_name]
self.assertAlmostEqual(attr.Get(), value, places=places)
| 9,380 | Python | 44.985294 | 116 | 0.566418 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/hard_softrange_array_ui.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 os
import sys
import math
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
class HardSoftRangeArrayUI(AsyncTestCase):
# Before running each test
async def setUp(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
await arrange_windows("Stage", 64, 800)
await open_stage(get_test_data_path(__name__, "usd/soft_range_float3.usda"))
await ui_test.find("Property").focus()
# select prim
await select_prims(["/World/Looks/float3_softrange/Shader"])
# wait for material to load & UI to refresh
await wait_stage_loading()
# After running each test
async def tearDown(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
# de-select prims to prevent _delayed_dirty_handler exception
await select_prims([])
await wait_stage_loading()
def _verify_values(self, widget_name: str, expected_value, model_soft_min, model_soft_max, hard_min, hard_max):
from omni.kit import ui_test
frame = ui_test.find(f"Property//Frame/**/.identifier=='{widget_name}'")
for widget in frame.find_all(f"**/FloatDrag[*]"):
self.assertAlmostEqual(widget.model.get_value_as_float(), expected_value.pop(0))
if model_soft_min and widget.model._soft_range_min:
self.assertAlmostEqual(widget.model._soft_range_min, model_soft_min)
if model_soft_max and widget.model._soft_range_max:
self.assertAlmostEqual(widget.model._soft_range_max, model_soft_max)
self.assertAlmostEqual(widget.widget.min, hard_min)
self.assertAlmostEqual(widget.widget.max, hard_max)
async def _click_type(self, widget_name: str, values):
from omni.kit import ui_test
frame = ui_test.find(f"Property//Frame/**/.identifier=='{widget_name}'")
for widget in frame.find_all(f"**/FloatDrag[*]"):
await widget.input(str(values.pop(0)))
async def test_hard_softrange_float3_ui(self):
from omni.kit import ui_test
# check default values
self._verify_values("drag_per_channel_inputs:float3_1",
expected_value=[0.75, 0.5, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float3_1", values=[0.25, 1.45, 1.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float3_1",
expected_value=[0.25, 1.45, 1.35],
model_soft_min=0.0,
model_soft_max=1.25,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float3_1", values=[23.25, 21.45, 24.5, 99.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float3_1",
[10.0, 10.0, 10.0, 10.0],
model_soft_min=0.0,
model_soft_max=10.0,
hard_min=0,
hard_max=10.0)
# click reset
frame = ui_test.find("Property//Frame/**/.identifier=='drag_per_channel_inputs:float3_1'")
for widget in frame.find_all(f"**/ImageWithProvider[*]"):
await widget.click()
# check default values
self._verify_values("drag_per_channel_inputs:float3_1",
expected_value=[0.75, 0.5, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
async def test_hard_softrange_float4_ui(self):
from omni.kit import ui_test
# check default values
self._verify_values("drag_per_channel_inputs:float4_1",
expected_value=[0.75, 0.5, 0.45, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float4_1", values=[1.25, 1.45, 1.5, 1.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float4_1",
expected_value=[1.25, 1.45, 1.5, 1.35],
model_soft_min=0.0,
model_soft_max=1.25,
hard_min=0,
hard_max=1.25)
# change values
await self._click_type("drag_per_channel_inputs:float4_1", values=[10.25, 10.45, 10.5, 10.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float4_1",
[5.0, 5.0, 5.0, 5.0],
model_soft_min=0.0,
model_soft_max=5.0,
hard_min=0,
hard_max=5.0)
# click reset
frame = ui_test.find("Property//Frame/**/.identifier=='drag_per_channel_inputs:float4_1'")
for widget in frame.find_all(f"**/ImageWithProvider[*]"):
await widget.click()
# check default values
self._verify_values("drag_per_channel_inputs:float4_1",
expected_value=[0.75, 0.5, 0.45, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
async def test_hard_softrange_float2_ui(self):
from omni.kit import ui_test
# check default values
self._verify_values("drag_per_channel_inputs:float2_1", [0.75, 0.25], None, None, 0, 1)
# change values
await self._click_type("drag_per_channel_inputs:float2_1", values=[0.25, 1.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float2_1",
expected_value=[0.25, 1.0],
model_soft_min=0.0,
model_soft_max=1.0,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float2_1", values=[-2.45, -2.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float2_1",
[0.0, 0.0],
model_soft_min=0.0,
model_soft_max=1.0,
hard_min=0,
hard_max=1.0)
# click reset
frame = ui_test.find("Property//Frame/**/.identifier=='drag_per_channel_inputs:float2_1'")
for widget in frame.find_all(f"**/ImageWithProvider[*]"):
await widget.click()
# check default values
self._verify_values("drag_per_channel_inputs:float2_1", [0.75, 0.25], None, None, 0, 1)
| 7,564 | Python | 37.994845 | 129 | 0.556716 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/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.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Gf, Kind, Sdf, UsdShade
from ..usd_attribute_model import GfVecAttributeSingleChannelModel
class TestWidget(OmniUiTest):
# Before running each test
async def setUp(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows
await super().setUp()
await arrange_windows("Stage", 200)
from omni.kit.property.usd.widgets import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute()
import omni.kit.window.property as p
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
self._w = p.get_window()
INT32_MIN = -2147483648
INT32_MAX = 2147483647
INT64_MIN = -9223372036854775808
INT64_MAX = 9223372036854775807
HALF_LOWEST = -65504.0
HALF_MAX = 65504.0
# In double precision
FLT_LOWEST = -3.4028234663852886e38
FLT_MIN = 1.1754943508222875e-38
FLT_MAX = 3.4028234663852886e38
FLT_EPS = 1.1920928955078125e-07
DBL_LOWEST = -1.7976931348623158e308
DBL_MIN = 2.2250738585072014e-308
DBL_MAX = 1.7976931348623158e308
DBL_EPS = 2.2204460492503131e-016
# (attr_name, attr_type, value_0, value_1, value_2, expected_model_count)
self._test_data = [
("bool_attr", Sdf.ValueTypeNames.Bool, True, False, True, 1),
("uchar_attr", Sdf.ValueTypeNames.UChar, ord("o"), ord("v"), ord("k"), 1),
("int_attr", Sdf.ValueTypeNames.Int, -1, 0, 1, 1),
("uint_attr", Sdf.ValueTypeNames.UInt, 1, 2, 3, 1),
("int64_attr", Sdf.ValueTypeNames.Int64, INT64_MIN, 0, INT64_MAX, 1),
(
"uint64_attr",
Sdf.ValueTypeNames.UInt64,
0,
2,
INT64_MAX,
1,
), # omni.ui only supports int64 range, thus uint max won't work
(
"half_attr",
Sdf.ValueTypeNames.Half,
HALF_LOWEST,
0.333251953125,
HALF_MAX,
1,
), # half is stored as double in model
(
"float_attr",
Sdf.ValueTypeNames.Float,
FLT_MIN,
FLT_MAX,
FLT_EPS,
1,
), # Float is stored as double in model
("double_attr", Sdf.ValueTypeNames.Double, DBL_MIN, DBL_MAX, DBL_EPS, 1),
("timdcode_attr", Sdf.ValueTypeNames.TimeCode, Sdf.TimeCode(10), Sdf.TimeCode(20), Sdf.TimeCode(30), 1),
("string_attr", Sdf.ValueTypeNames.String, "This", "is a", "string", 1),
(
"token_attr",
Sdf.ValueTypeNames.Token,
Kind.Tokens.subcomponent,
Kind.Tokens.component,
Kind.Tokens.group,
1,
),
("asset_attr", Sdf.ValueTypeNames.Asset, "/This", "/is/an", "/asset", 1),
(
"int2_attr",
Sdf.ValueTypeNames.Int2,
Gf.Vec2i(INT32_MIN, INT32_MAX),
Gf.Vec2i(INT32_MAX, INT32_MIN),
Gf.Vec2i(INT32_MIN, INT32_MAX),
2 + 1, # Vector has one additional model for label context menu
),
(
"int3_attr",
Sdf.ValueTypeNames.Int3,
Gf.Vec3i(INT32_MIN, INT32_MAX, INT32_MIN),
Gf.Vec3i(INT32_MAX, INT32_MIN, INT32_MAX),
Gf.Vec3i(INT32_MIN, INT32_MAX, INT32_MIN),
3 + 1,
),
(
"int4_attr",
Sdf.ValueTypeNames.Int4,
Gf.Vec4i(INT32_MIN, INT32_MAX, INT32_MIN, INT32_MAX),
Gf.Vec4i(INT32_MAX, INT32_MIN, INT32_MAX, INT32_MIN),
Gf.Vec4i(INT32_MIN, INT32_MAX, INT32_MIN, INT32_MAX),
4 + 1,
),
(
"half2_attr",
Sdf.ValueTypeNames.Half2,
Gf.Vec2h(HALF_LOWEST, HALF_MAX),
Gf.Vec2h(HALF_MAX, HALF_LOWEST),
Gf.Vec2h(HALF_LOWEST, HALF_MAX),
2 + 1,
),
(
"half3_attr",
Sdf.ValueTypeNames.Half3,
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
Gf.Vec3h(HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
3 + 1,
),
(
"half4_attr",
Sdf.ValueTypeNames.Half4,
Gf.Vec4h(HALF_LOWEST, HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec4h(HALF_MAX, HALF_LOWEST, HALF_LOWEST, HALF_MAX),
Gf.Vec4h(HALF_LOWEST, HALF_MAX, HALF_LOWEST, HALF_MAX),
4 + 1,
),
(
"float2_attr",
Sdf.ValueTypeNames.Float2,
Gf.Vec2f(FLT_LOWEST, FLT_MAX),
Gf.Vec2f(FLT_MAX, FLT_LOWEST),
Gf.Vec2f(FLT_MAX, FLT_MAX),
2 + 1,
),
(
"float3_attr",
Sdf.ValueTypeNames.Float3,
Gf.Vec3f(FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec3f(FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec3f(FLT_MAX, FLT_MAX, FLT_MAX),
3 + 1,
),
(
"float4_attr",
Sdf.ValueTypeNames.Float4,
Gf.Vec4f(FLT_LOWEST, FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec4f(FLT_MAX, FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec4f(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX),
4 + 1,
),
(
"double2_attr",
Sdf.ValueTypeNames.Double2,
Gf.Vec2d(DBL_LOWEST, DBL_MAX),
Gf.Vec2d(DBL_MAX, DBL_LOWEST),
Gf.Vec2d(DBL_MAX, DBL_MAX),
2 + 1,
),
(
"double3_attr",
Sdf.ValueTypeNames.Double3,
Gf.Vec3d(DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec3d(DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec3d(DBL_MAX, DBL_MAX, DBL_MAX),
3 + 1,
),
(
"double4_attr",
Sdf.ValueTypeNames.Double4,
Gf.Vec4d(DBL_LOWEST, DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec4d(DBL_MAX, DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec4d(DBL_MAX, DBL_MAX, DBL_MAX, DBL_MAX),
4 + 1,
),
(
"point3h_attr",
Sdf.ValueTypeNames.Point3h,
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
Gf.Vec3h(HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
3 + 1,
),
(
"point3f_attr",
Sdf.ValueTypeNames.Point3f,
Gf.Vec3f(FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec3f(FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec3f(FLT_MAX, FLT_MAX, FLT_MAX),
3 + 1,
),
(
"point3d_attr",
Sdf.ValueTypeNames.Point3d,
Gf.Vec3d(DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec3d(DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec3d(DBL_MAX, DBL_MAX, DBL_MAX),
3 + 1,
),
(
"vector3h_attr",
Sdf.ValueTypeNames.Vector3h,
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
Gf.Vec3h(HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
3 + 1,
),
(
"vector3f_attr",
Sdf.ValueTypeNames.Vector3f,
Gf.Vec3f(FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec3f(FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec3f(FLT_MAX, FLT_MAX, FLT_MAX),
3 + 1,
),
(
"vector3d_attr",
Sdf.ValueTypeNames.Vector3d,
Gf.Vec3d(DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec3d(DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec3d(DBL_MAX, DBL_MAX, DBL_MAX),
3 + 1,
),
(
"normal3h_attr",
Sdf.ValueTypeNames.Normal3h,
Gf.Vec3h(1.0, 0.0, 0.0),
Gf.Vec3h(0.0, 1.0, 0.0),
Gf.Vec3h(0.0, 0.0, 1.0),
3 + 1,
),
(
"normal3f_attr",
Sdf.ValueTypeNames.Normal3f,
Gf.Vec3f(1.0, 0.0, 0.0),
Gf.Vec3f(0.0, 1.0, 0.0),
Gf.Vec3f(0.0, 0.0, 1.0),
3 + 1,
),
(
"normal3d_attr",
Sdf.ValueTypeNames.Normal3d,
Gf.Vec3d(1.0, 0.0, 0.0),
Gf.Vec3d(0.0, 1.0, 0.0),
Gf.Vec3d(0.0, 0.0, 1.0),
3 + 1,
),
(
"color3h_attr",
Sdf.ValueTypeNames.Color3h,
Gf.Vec3h(1.0, 0.0, 0.0),
Gf.Vec3h(0.0, 1.0, 0.0),
Gf.Vec3h(0.0, 0.0, 1.0),
3 + 1, # Color attr has one model per channel + one model for the color picker
),
(
"color3f_attr",
Sdf.ValueTypeNames.Color3f,
Gf.Vec3f(1.0, 0.0, 0.0),
Gf.Vec3f(0.0, 1.0, 0.0),
Gf.Vec3f(0.0, 0.0, 1.0),
3 + 1,
),
(
"color3d_attr",
Sdf.ValueTypeNames.Color3d,
Gf.Vec3d(1.0, 0.0, 0.0),
Gf.Vec3d(0.0, 1.0, 0.0),
Gf.Vec3d(0.0, 0.0, 1.0),
3 + 1,
),
(
"color4h_attr",
Sdf.ValueTypeNames.Color4h,
Gf.Vec4h(1.0, 0.0, 0.0, 1.0),
Gf.Vec4h(0.0, 1.0, 0.0, 1.0),
Gf.Vec4h(0.0, 0.0, 1.0, 1.0),
4 + 1,
),
(
"color4f_attr",
Sdf.ValueTypeNames.Color4f,
Gf.Vec4f(1.0, 0.0, 0.0, 1.0),
Gf.Vec4f(0.0, 1.0, 0.0, 1.0),
Gf.Vec4f(0.0, 0.0, 1.0, 1.0),
4 + 1,
),
(
"color4d_attr",
Sdf.ValueTypeNames.Color4d,
Gf.Vec4d(1.0, 0.0, 0.0, 1.0),
Gf.Vec4d(0.0, 1.0, 0.0, 1.0),
Gf.Vec4d(0.0, 0.0, 1.0, 1.0),
4 + 1,
),
("quath_attr", Sdf.ValueTypeNames.Quath, Gf.Quath(-1), Gf.Quath(0), Gf.Quath(1), 1),
("quatf_attr", Sdf.ValueTypeNames.Quatf, Gf.Quatf(-1), Gf.Quatf(0), Gf.Quatf(1), 1),
("quatd_attr", Sdf.ValueTypeNames.Quatd, Gf.Quatd(-1), Gf.Quatd(0), Gf.Quatd(1), 1),
("matrix2d_attr", Sdf.ValueTypeNames.Matrix2d, Gf.Matrix2d(-1), Gf.Matrix2d(0), Gf.Matrix2d(1), 1),
("matrix3d_attr", Sdf.ValueTypeNames.Matrix3d, Gf.Matrix3d(-1), Gf.Matrix3d(0), Gf.Matrix3d(1), 1),
("matrix4d_attr", Sdf.ValueTypeNames.Matrix4d, Gf.Matrix4d(-1), Gf.Matrix4d(0), Gf.Matrix4d(1), 1),
("frame4d_attr", Sdf.ValueTypeNames.Frame4d, Gf.Matrix4d(-1), Gf.Matrix4d(0), Gf.Matrix4d(1), 1),
(
"texCoord2f_attr",
Sdf.ValueTypeNames.TexCoord2f,
Gf.Vec2f(1.0, 0.0),
Gf.Vec2f(0.0, 1.0),
Gf.Vec2f(1.0, 1.0),
2 + 1,
),
(
"texCoord2d_attr",
Sdf.ValueTypeNames.TexCoord2d,
Gf.Vec2d(1.0, 0.0),
Gf.Vec2d(0.0, 1.0),
Gf.Vec2d(1.0, 1.0),
2 + 1,
),
(
"texCoord2h_attr",
Sdf.ValueTypeNames.TexCoord2h,
Gf.Vec2h(1.0, 0.0),
Gf.Vec2h(0.0, 1.0),
Gf.Vec2h(1.0, 1.0),
2 + 1,
),
(
"texCoord3f_attr",
Sdf.ValueTypeNames.TexCoord3f,
Gf.Vec3f(1.0, 0.0, 1.0),
Gf.Vec3f(0.0, 1.0, 0.0),
Gf.Vec3f(1.0, 1.0, 1.0),
3 + 1,
),
(
"texCoord3d_attr",
Sdf.ValueTypeNames.TexCoord3d,
Gf.Vec3d(1.0, 0.0, 1.0),
Gf.Vec3d(0.0, 1.0, 0.0),
Gf.Vec3d(1.0, 1.0, 1.0),
3 + 1,
),
(
"texCoord3h_attr",
Sdf.ValueTypeNames.TexCoord3h,
Gf.Vec3h(1.0, 0.0, 1.0),
Gf.Vec3h(0.0, 1.0, 0.0),
Gf.Vec3h(1.0, 1.0, 1.0),
3 + 1,
),
# Add array types
(
"asset_array_attr",
Sdf.ValueTypeNames.AssetArray,
Sdf.AssetPathArray(2, [Sdf.AssetPath("foo.ext"), Sdf.AssetPath("bar.ext")]),
Sdf.AssetPathArray(),
Sdf.AssetPathArray(3, [Sdf.AssetPath("foo.ext"), Sdf.AssetPath("bar.ext"), Sdf.AssetPath("baz.ext")]),
1,
),
]
self._test_widget = UsdPropertiesWidget(title="Test USD Properties", collapsed=False)
self._w.register_widget("prim", "test_raw_attribute", self._test_widget)
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
self._stage = self._usd_context.get_stage()
self._test_prim = self._stage.DefinePrim("/TestPrim")
self._usd_context.get_selection().set_selected_prim_paths(["/TestPrim"], True)
await ui_test.human_delay(10)
# After running each test
async def tearDown(self):
from omni.kit import ui_test
self._usd_context.get_selection().set_selected_prim_paths([], False)
await ui_test.human_delay()
await self._usd_context.close_stage_async()
self._w.unregister_widget("prim", "test_raw_attribute")
self._test_widget = None
self._test_prim = None
self._stage = None
await super().tearDown()
# This tests read/write between USD attribute model and USD data
async def test_attribute_model(self):
def verify_model_value(value_idx: int):
models = self._test_widget._models
for attr_data in self._test_data:
attr_path = prim_path.AppendProperty(attr_data[0])
attr_model_list = models.get(attr_path, None)
self.assertNotEqual(attr_model_list, None, msg=attr_data[0])
self.assertEqual(len(attr_model_list), attr_data[5], msg=attr_data[0])
for model in attr_model_list:
self.assertEqual(model.get_value(), attr_data[value_idx], msg=attr_data[0])
# Test Resync event
for attr_data in self._test_data:
attr = self._test_prim.CreateAttribute(attr_data[0], attr_data[1])
self.assertTrue(attr is not None)
attr.Set(attr_data[2])
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
prim_path = self._test_prim.GetPrimPath()
# Verify the model has fetched the correct data
verify_model_value(2)
# Test info changed only event
for attr_data in self._test_data:
attr = self._test_prim.GetAttribute(attr_data[0])
self.assertTrue(attr is not None)
attr.Set(attr_data[3])
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
# Verify the model has fetched the correct data
verify_model_value(3)
# Test set value to model
# TODO ideally new value should be set via UI, and have UI update the model instead of setting model directly,
# it is less useful of a test to write to model directly from user-interaction perspective.
# Update the test once we can locate UI element and emulate input.
models = self._test_widget._models
for attr_data in self._test_data:
attr_path = prim_path.AppendProperty(attr_data[0])
attr_model_list = models.get(attr_path, None)
for i, model in enumerate(attr_model_list):
if isinstance(model, GfVecAttributeSingleChannelModel):
model.set_value(attr_data[4][i])
# Wait for a frame for the rest of the channel model to sync the change
await omni.kit.app.get_app().next_update_async()
else:
model.set_value(attr_data[4])
# verify value updated in USD
for attr_data in self._test_data:
attr = self._test_prim.GetAttribute(attr_data[0])
self.assertNotEqual(attr, None)
self.assertEqual(attr.Get(), attr_data[4], msg=attr_data[0])
async def _test_attribute_ui_base(self, start, end):
await self.docked_test_window(
window=self._w._window,
width=800,
height=950,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
# Populate USD attributes
for attr_data in self._test_data[start:end]:
attr = self._test_prim.CreateAttribute(attr_data[0], attr_data[1])
self.assertTrue(attr is not None)
attr.Set(attr_data[2])
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
# Capture screenshot of property window and compare with golden image (1/2)
# The property list is too long and Window limits max window size base on primary monitor height,
# the test has to be split into 2 each tests half of the attributes
async def test_attribute_ui_1(self):
await self._test_attribute_ui_base(0, int(len(self._test_data) / 2))
# finalize needs to be called here to get proper test name
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_attribute_ui_1.png")
# Capture screenshot of property window and compare with golden image (2/2)
# The property list is too long and Window limits max window size base on primary monitor height,
# the test has to be split into 2 each tests half of the attributes
async def test_attribute_ui_2(self):
await self._test_attribute_ui_base(int(len(self._test_data) / 2), len(self._test_data))
# finalize needs to be called here to get proper test name
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_attribute_ui_2.png")
# Tests the relationship UI
async def test_relationship_ui(self):
await self.docked_test_window(
window=self._w._window,
width=800,
height=950,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
target_prim_paths = ["/Target1", "/Target2", "/Target3"]
for prim_path in target_prim_paths:
self._stage.DefinePrim(prim_path)
rel = self._test_prim.CreateRelationship("TestRelationship")
for prim_path in target_prim_paths:
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path)
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
omni.kit.commands.execute("RemoveRelationshipTarget", relationship=rel, target=target_prim_paths[-1])
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_relationship_ui.png")
# Tests SdfReferences UI
async def test_references_ui(self):
await self.docked_test_window(
window=self._w._window,
width=800,
height=420,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("ref_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
self._stage = usd_context.get_stage()
ref_prim = self._stage.GetPrimAtPath("/World")
ref = Sdf.Reference(primPath="/Xform")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
ref = Sdf.Reference(assetPath="cube.usda", primPath="/Xform")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
ref = Sdf.Reference(assetPath="sphere.usda")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
ref = Sdf.Reference(primPath="/Xform2")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
await omni.kit.app.get_app().next_update_async()
# Select the prim after references are created because the widget hide itself when there's no reference
# Property window does not refresh itself when new ref is added. This is a limitation to property window that
# needs to be fixed.
usd_context.get_selection().set_selected_prim_paths(["/World"], True)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
ref = Sdf.Reference(primPath="/Xform2")
omni.kit.commands.execute(
"RemoveReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
await omni.kit.app.get_app().next_update_async()
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_references_ui.png")
# Tests mixed TfToken (with allowedTokens) and MDL enum that when one changes
# The bug was when selecting 2+ prims with TfToken(or MDL enum) that results in a mixed state,
# changing last selected prim's value from USD API will overwrite the value for other untouched attributes.
async def test_mixed_combobox_attributes(self):
shader_a = UsdShade.Shader.Define(self._stage, "/PrimA")
shader_b = UsdShade.Shader.Define(self._stage, "/PrimB")
enum_options = "a:0|b:1|c:2"
input_a = shader_a.CreateInput("mdl_enum", Sdf.ValueTypeNames.Int)
input_a.SetSdrMetadataByKey("options", enum_options)
input_a.SetRenderType("::dummy::enum")
input_a.Set(0)
input_b = shader_b.CreateInput("mdl_enum", Sdf.ValueTypeNames.Int)
input_b.SetSdrMetadataByKey("options", enum_options)
input_b.SetRenderType("::dummy::enum")
input_b.Set(1)
prim_a = shader_a.GetPrim()
prim_b = shader_b.GetPrim()
allowed_tokens = ["a", "b", "c"]
attr_a = prim_a.CreateAttribute("token", Sdf.ValueTypeNames.Token)
attr_a.SetMetadata("allowedTokens", allowed_tokens)
attr_a.Set(allowed_tokens[0])
attr_b = prim_b.CreateAttribute("token", Sdf.ValueTypeNames.Token)
attr_b.SetMetadata("allowedTokens", allowed_tokens)
attr_b.Set(allowed_tokens[1])
omni.usd.get_context().get_selection().set_selected_prim_paths(["/PrimA", "/PrimB"], True)
# took 5 frames to trigger the bug
for i in range(5):
await omni.kit.app.get_app().next_update_async()
input_b.Set(2)
attr_b.Set(allowed_tokens[2])
await omni.kit.app.get_app().next_update_async()
# if bug happens, input_a's value will be set to 2
self.assertEqual(input_a.Get(), 0)
# if bug happens, attr_a's value will be set to "c"
self.assertEqual(attr_a.Get(), allowed_tokens[0])
| 26,055 | Python | 37.947683 | 118 | 0.526578 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_softrange_ui.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 os
import sys
import math
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
arrange_windows
)
class SoftRangeUI(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "usd/soft_range.usda"))
# After running each test
async def tearDown(self):
# de-select prims to prevent _delayed_dirty_handler exception
await select_prims([])
await wait_stage_loading()
def _verify_values(self, widget_name: str, expected_value, model_soft_min, model_soft_max, min, max, places=4):
for widget in ui_test.find_all(f"Property//Frame/**/.identifier=='{widget_name}'"):
self.assertAlmostEqual(widget.model.get_value(), expected_value, places=places)
if model_soft_min != None:
self.assertAlmostEqual(widget.model._soft_range_min, model_soft_min, places=places)
if model_soft_max != None:
self.assertAlmostEqual(widget.model._soft_range_max, model_soft_max, places=places)
self.assertAlmostEqual(widget.widget.min, min, places=places)
self.assertAlmostEqual(widget.widget.max, max, places=places)
async def _click_type_verify(self, widget_name: str, value, expected_value, model_soft_min, model_soft_max, min, max, places=4):
for widget in ui_test.find_all(f"Property//Frame/**/.identifier=='{widget_name}'"):
await widget.input(str(value))
self._verify_values(widget_name, expected_value, model_soft_min, model_soft_max, min, max, places=places)
async def _hide_frames(self, show_list):
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if show_list == None:
w.widget.collapsed = False
elif w.widget.title in show_list:
w.widget.collapsed = False
else:
w.widget.collapsed = True
await ui_test.human_delay()
async def test_l2_softrange_ui(self):
await ui_test.find("Property").focus()
range_name = "float_slider_inputs:glass_ior"
# select prim
await select_prims(["/World/Looks/OmniGlass/Shader"])
# wait for material to load & UI to refresh
await wait_stage_loading()
# test soft_range unlimited inputs:glass_ior
await self._hide_frames(["Shader", "Refraction"])
# check default values
self._verify_values(range_name, 1.491, None, None, 1, 4)
# something not right here, accuracy of 0.2 ?
await self._click_type_verify(range_name, 1500, 1500, 1, 1500, 1, 1500) # value & max 1500
await self._click_type_verify(range_name, -150, -150, -150, 1500, -150, 1500) # value & min -150 & max 1500
await self._click_type_verify(range_name, 500, 500, -150, 1500, -150, 1500) # value 500 & min -150 & max 1500
await self._click_type_verify(range_name, 0, 0, -150, 1500, -150, 1500) # value 0 & min -150 & max 1500
# reset values
await ui_test.find(f"Property//Frame/**/ImageWithProvider[*].identifier=='control_state_inputs:glass_ior'").click()
# verify
self._verify_values(range_name, 1.491, None, None, 1, 4)
| 3,952 | Python | 41.967391 | 132 | 0.652834 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/__init__.py | from .create_prims import *
from .test_widget import *
from .test_usd_api import *
from .test_placeholder import *
from .test_path_menu import *
from .test_shader_goto_material_property import *
from .test_shader_goto_UDIM_material_property import *
from .hard_softrange_ui import *
from .hard_softrange_array_ui import *
from .test_shader_drag_drop_mdl import *
from .test_references import *
from .test_payloads import *
from .basic_types_ui import *
from .test_drag_drop_material_property_combobox import *
from .test_drag_drop_material_property_preview import *
from .test_material_widget_refresh_on_binding import *
from .test_property_bind_material_combo import *
from .test_shader_material_subid_property import *
from .test_softrange_ui import *
from .test_variant import *
from .test_mixed_variant import *
from .test_path_add_menu import *
from .test_asset_array_widget import *
from .test_relationship import *
from .test_usd_preferences import *
from .test_bool_arrays import *
from .test_material_edits_and_undo import *
| 1,034 | Python | 35.964284 | 56 | 0.773694 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_placeholder.py | import carb
import unittest
import omni.kit.test
from pxr import Sdf, Usd
class TestPlaceholderAttribute(omni.kit.test.AsyncTestCase):
async def setUp(self):
await omni.usd.get_context().new_stage_async()
async def tearDown(self):
pass
async def test_placeholder_attribute(self):
from omni.kit.property.usd.placeholder_attribute import PlaceholderAttribute
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
prim = stage.GetPrimAtPath("/Sphere")
attr_dict = {Sdf.PrimSpec.TypeNameKey: "bool", "customData": {"default": True}}
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test expected usage
#################################################################
attr = PlaceholderAttribute(name="primvars:doNotCastShadows", prim=prim, metadata=attr_dict)
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertTrue(attr.Get())
self.assertEqual(attr.GetPath(), "/Sphere")
self.assertEqual(attr.GetPrim(), prim)
self.assertEqual(attr.GetMetadata("customData"), attr_dict["customData"])
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), attr_dict)
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute does exist
self.assertTrue(prim.GetAttribute("primvars:doNotCastShadows"))
prim.RemoveProperty("primvars:doNotCastShadows")
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test no metadata usage
#################################################################
attr = PlaceholderAttribute(name="primvars:doNotCastShadows", prim=prim, metadata={})
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertEqual(attr.Get(), None)
self.assertEqual(attr.GetPath(), "/Sphere")
self.assertEqual(attr.GetPrim(), prim)
self.assertEqual(attr.GetMetadata("customData"), False)
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), {})
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test no prim usage
#################################################################
attr = PlaceholderAttribute(name="primvars:doNotCastShadows", prim=None, metadata=attr_dict)
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertTrue(attr.Get())
self.assertEqual(attr.GetPath(), None)
self.assertEqual(attr.GetPrim(), None)
self.assertEqual(attr.GetMetadata("customData"), attr_dict["customData"])
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), attr_dict)
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test no name
#################################################################
attr = PlaceholderAttribute(name="", prim=prim, metadata=attr_dict)
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertTrue(attr.Get())
self.assertEqual(attr.GetPath(), "/Sphere")
self.assertEqual(attr.GetPrim(), prim)
self.assertEqual(attr.GetMetadata("customData"), attr_dict["customData"])
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), attr_dict)
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
| 4,689 | Python | 37.76033 | 100 | 0.587545 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_relationship.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 os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, wait_for_window, arrange_windows
class PrimRelationship(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 224)
await open_stage(get_test_data_path(__name__, "usd/relationship.usda"))
await self._open_raw_frame(False)
# After running each test
async def tearDown(self):
await self._open_raw_frame(True)
await wait_stage_loading()
async def _open_raw_frame(self, state):
await select_prims(['/World'])
frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'")
frame.widget.collapsed = state
async def handle_select_targets(self, prim_name):
from pxr import Sdf
# handle assign dialog
window_name = "Select Target(s)"
await wait_for_window(window_name)
# select prim
stage_widget = ui_test.find(f"{window_name}//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{prim_name}'").click()
await ui_test.human_delay()
# click add
await ui_test.find(f"{window_name}//Frame/**/Button[*].identifier=='add_button'").click()
await ui_test.human_delay(50)
async def test_l1_relationship(self):
def get_buttons():
buttons={}
frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'")
for widget in frame.find_all("**/Button[*]"):
buttons[widget.widget.identifier] = widget
return buttons
def remove_add_buttons():
buttons = get_buttons()
for w in buttons.copy():
if w.startswith("add_relationship_"):
del buttons[w]
return buttons
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select relationship prim
await select_prims(['/World/Sphere_02'])
# Raw USD Properties as relationship attribute is not part of any schema
widgets = get_buttons()
await widgets["remove_relationship_World_Sphere_01"].click()
await ui_test.human_delay(50)
# verify only "add_relationship"
widgets = remove_add_buttons()
self.assertEqual(widgets, {})
# "add_relationship"
await get_buttons()["add_relationship_World_Sphere_02_Attr2"].click()
await self.handle_select_targets("/World/Sphere_01")
# "add_relationship"
await get_buttons()["add_relationship_World_Sphere_02_Attr2"].click()
await self.handle_select_targets("/World/Cube_01")
# "add_relationship"
await get_buttons()["add_relationship_World_Sphere_02_Attr2"].click()
await self.handle_select_targets("/World/Cube_02")
# verify
widgets = remove_add_buttons()
self.assertEqual(list(widgets.keys()), ['remove_relationship_World_Sphere_01', 'remove_relationship_World_Cube_01', 'remove_relationship_World_Cube_02'])
| 3,808 | Python | 36.712871 | 161 | 0.648372 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_property_bind_material_combo.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 os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
arrange_windows
)
class PropertyBindMaterialCombo(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_property_bind_material_combo(self):
await ui_test.find("Content").focus()
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"]
await wait_stage_loading()
await select_prims(to_select)
await ui_test.human_delay()
bound_materials = ["None", "/World/Looks/OmniGlass", "/World/Looks/OmniPBR", "/World/Looks/OmniSurface_Plastic"]
for index in range(0, 4):
# show combobox
# NOTE: delay of 4 as that opens a new popup window
topmost_button = sorted(ui_test.find_all("Property//Frame/**/Button[*].identifier=='combo_open_button'"), key=lambda f: f.position.y)[0]
await topmost_button.click(human_delay_speed=4)
# activate menu item
await ui_test.find(f"MaterialPropertyPopupWindow//Frame/**/Label[*].text=='{bound_materials[index]}'").click()
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
if bound_materials[index] != "None":
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == bound_materials[index])
else:
self.assertTrue(bound_material.GetPrim().IsValid() == False)
| 2,812 | Python | 38.069444 | 148 | 0.64936 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/hard_softrange_ui.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 os
import sys
import math
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
class HardSoftRangeUI(AsyncTestCase):
# Before running each test
async def setUp(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, arrange_windows
await arrange_windows("Stage", 64, 800)
await open_stage(get_test_data_path(__name__, "usd/soft_range.usda"))
await ui_test.find("Property").focus()
# After running each test
async def tearDown(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
# de-select prims to prevent _delayed_dirty_handler exception
await select_prims([])
await wait_stage_loading()
async def _hide_frames(self, show_list):
from omni.kit import ui_test
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if show_list == None:
w.widget.collapsed = False
elif w.widget.title in show_list:
w.widget.collapsed = False
else:
w.widget.collapsed = True
await ui_test.human_delay()
async def test_hard_softrange_float_ui(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
def verify_values(widget_name: str, expected_value, model_soft_min, model_soft_max, hard_min, hard_max):
for widget in ui_test.find_all(f"Property//Frame/**/.identifier=='{widget_name}'"):
self.assertAlmostEqual(widget.model.get_value(), expected_value)
if model_soft_min != None:
self.assertAlmostEqual(widget.model._soft_range_min, model_soft_min)
if model_soft_max != None:
self.assertAlmostEqual(widget.model._soft_range_max, model_soft_max)
self.assertAlmostEqual(widget.widget.min, hard_min)
self.assertAlmostEqual(widget.widget.max, hard_max)
# select prim
await select_prims(["/World/Looks/OmniGlass/Shader"])
# wait for material to load & UI to refresh
await wait_stage_loading()
# test hard range 0-1000 & soft range 0-1 inputs:depth
await self._hide_frames(["Shader", "Color"])
# check default values
verify_values("float_slider_inputs:depth",
expected_value=0.001,
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
# something not right here, accuracy of 0.2 ?
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("1500")
# verify changed value
verify_values("float_slider_inputs:depth",
expected_value=1000,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("-150")
# verify changed value
verify_values("float_slider_inputs:depth",
expected_value=0,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("500")
# verify changed value
verify_values("float_slider_inputs:depth",
expected_value=500,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("0")
# verify changed value
verify_values("float_slider_inputs:depth",
0,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# click reset
await ui_test.find(f"Property//Frame/**/ImageWithProvider[*].identifier=='control_state_inputs:depth'").click()
# verify
verify_values("float_slider_inputs:depth",
expected_value=0.001,
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
| 5,215 | Python | 37.352941 | 119 | 0.574305 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_path_menu.py | import carb
import unittest
import omni.kit.test
class TestPathMenu(omni.kit.test.AsyncTestCase):
async def setUp(self):
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows()
async def tearDown(self):
pass
async def test_path_menu(self):
from omni.kit import ui_test
from omni.kit.property.usd import PrimPathWidget
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
from omni.kit.test_suite.helpers import open_stage, wait_stage_loading, select_prims, get_test_data_path, get_prims
test_path_fn_clicked = False
menu_path = "PxrHydraEngine/does/not/support/divergent/render/and/simulation/times"
# setup path button
def test_path_fn(payload: PrimSelectionPayload):
nonlocal test_path_fn_clicked
test_path_fn_clicked = True
self._button_menu_entry = PrimPathWidget.add_button_menu_entry(
menu_path,
onclick_fn=test_path_fn,
)
# load stage
await open_stage(get_test_data_path(__name__, "usd/cube.usda"))
stage = omni.usd.get_context().get_stage()
await select_prims(["/Xform/Cube"])
# test "+add" menu
test_path_fn_clicked = False
for widget in ui_test.find_all("Property//Frame/**/Button[*]"):
if widget.widget.text.endswith(" Add"):
await widget.click()
await ui_test.human_delay()
await ui_test.select_context_menu(menu_path, offset=ui_test.Vec2(10, 10))
#verify clicked
self.assertTrue(test_path_fn_clicked)
# test stage window context menu
test_path_fn_clicked = False
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='/Xform/Cube'").right_click()
await ui_test.human_delay()
# click on context menu item
await ui_test.select_context_menu(f"Add/{menu_path}", offset=ui_test.Vec2(10, 10))
#verify clicked
self.assertTrue(test_path_fn_clicked)
| 2,217 | Python | 34.774193 | 123 | 0.628327 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_path_add_menu.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Gf
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
wait_for_window,
arrange_windows
)
class PropertyPathAddMenu(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_property_path_add(self):
await ui_test.find("Content").focus()
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
# select cone
await select_prims(["/World/Cone"])
await ui_test.human_delay()
# click "Add"
add_widget = [w for w in ui_test.find_all("Property//Frame/**/Button[*].identifier==''") if w.widget.text.endswith("Add")][0]
await add_widget.click()
# select Attribute from menu
await ui_test.select_context_menu("Attribute", offset=ui_test.Vec2(10, 10))
# use "Add Attribute..." window
await wait_for_window("Add Attribute...")
# select settings in window
for w in ui_test.find_all("Add Attribute...//Frame/**"):
if isinstance(w.widget, omni.ui.StringField):
await w.input("MyTestAttribute")
elif isinstance(w.widget, omni.ui.ComboBox):
items = w.widget.model.get_item_children(None)
if len(items) == 2:
w.widget.model.get_item_value_model(None, 0).set_value(1)
else:
bool_index = [index for index, i in enumerate(w.widget.model.get_item_children(None))if i.value_type_name == "bool" if i.value_type_name == "bool"][0]
w.widget.model.get_item_value_model(None, 0).set_value(bool_index)
# click "Add"
await ui_test.find("Add Attribute...//Frame/**/Button[*].text=='Add'").click()
await ui_test.human_delay()
# verify attribute correct type
attr = stage.GetPrimAtPath("/World/Cone").GetAttribute("MyTestAttribute")
self.assertEqual(attr.GetTypeName().cppTypeName, "bool")
| 2,933 | Python | 36.615384 | 170 | 0.640641 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.