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.manipulator.camera/omni/kit/manipulator/camera/tests/test_manipulator_camera.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['TestManipulatorCamera', 'TestFlightMode']
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from omni.ui import scene as sc
from omni.ui import color as cl
import carb
import omni.kit
import omni.kit.app
import omni.ui as ui
from pxr import Gf
from omni.kit.manipulator.camera.manipulator import CameraManipulatorBase, SceneViewCameraManipulator, adjust_center_of_interest
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType, KeyboardEventType, KeyboardInput
CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.camera}/data"))
TEST_WIDTH, TEST_HEIGHT = 500, 500
TEST_UI_CENTER = ui_test.Vec2(TEST_WIDTH / 2, TEST_HEIGHT / 2)
def _flatten_matrix(matrix: Gf.Matrix4d):
return [matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],
matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3]]
class SimpleGrid():
def __init__(self, lineCount: float = 100, lineStep: float = 10, thicknes: float = 1, color: ui.color = ui.color(0.25)):
self.__transform = ui.scene.Transform()
with self.__transform:
for i in range(lineCount * 2 + 1):
ui.scene.Line(
((i - lineCount) * lineStep, 0, -lineCount * lineStep),
((i - lineCount) * lineStep, 0, lineCount * lineStep),
color=color, thickness=thicknes,
)
ui.scene.Line(
(-lineCount * lineStep, 0, (i - lineCount) * lineStep),
(lineCount * lineStep, 0, (i - lineCount) * lineStep),
color=color, thickness=thicknes,
)
class SimpleOrigin():
def __init__(self, length: float = 5, thickness: float = 4):
origin = (0, 0, 0)
with ui.scene.Transform():
ui.scene.Line(origin, (length, 0, 0), color=ui.color.red, thickness=thickness)
ui.scene.Line(origin, (0, length, 0), color=ui.color.green, thickness=thickness)
ui.scene.Line(origin, (0, 0, length), color=ui.color.blue, thickness=thickness)
# Create a few scenes with different camera-maniupulators (a general ui.scene manip and one that allows ortho-tumble )
class SimpleScene:
def __init__(self, ortho: bool = False, custom: bool = False, *args, **kwargs):
self.__scene_view = ui.scene.SceneView(*args, **kwargs)
if ortho:
view = [-1, 0, 0, 0, 0, 0, 0.9999999999999998, 0, 0, 0.9999999999999998, 0, 0, 0, 0, -1000, 1]
projection = [0.008, 0, 0, 0, 0, 0.008, 0, 0, 0, 0, -2.000002000002e-06, 0, 0, 0, -1.000002000002, 1]
else:
view = [0.7071067811865476, -0.40557978767263897, 0.5792279653395693, 0, -2.775557561562892e-17, 0.8191520442889919, 0.5735764363510462, 0, -0.7071067811865477, -0.4055797876726389, 0.5792279653395692, 0, 6.838973831690966e-14, -3.996234471857009, -866.0161835150924, 1.0000000000000002]
projection = [4.7602203407949375, 0, 0, 0, 0, 8.483787309173106, 0, 0, 0, 0, -1.000002000002, -1, 0, 0, -2.000002000002, 0]
view = Gf.Matrix4d(*view)
center_of_interest = [0, 0, -view.Transform((0, 0, 0)).GetLength()]
with self.__scene_view.scene:
self.items = [SimpleGrid(), ui.scene.Arc(100, axis=1, wireframe=True), SimpleOrigin()]
with ui.scene.Transform(transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1000, 0, 1000, 1]):
self.items.append(ui.scene.Arc(100, axis=1, wireframe=True, color=ui.color.green))
with ui.scene.Transform(transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -260, 0, 260, 1]):
self.items.append(ui.scene.Arc(100, axis=1, wireframe=True, color=ui.color.blue))
if custom:
self.items.append(CameraManipulatorBase())
else:
self.items.append(SceneViewCameraManipulator(center_of_interest))
# Push the start values into the CameraManipulator
self.setup_camera_model(self.items[-1].model, view, projection, center_of_interest, ortho)
def setup_camera_model(self, cam_model, view, projection, center_of_interest, ortho):
cam_model.set_floats('transform', _flatten_matrix(view.GetInverse()))
cam_model.set_floats('projection', projection)
cam_model.set_floats('center_of_interest', [0, 0, -view.Transform((0, 0, 0)).GetLength()])
if ortho:
cam_model.set_ints('orthographic', [ortho])
# Setup up the subscription to the CameraModel so changes here get pushed to SceneView
self.model_changed_sub = cam_model.subscribe_item_changed_fn(self.model_changed)
# And push the view and projection into the SceneView.model
cam_model._item_changed(cam_model.get_item('transform'))
cam_model._item_changed(cam_model.get_item('projection'))
def model_changed(self, model, item):
if item == model.get_item('transform'):
transform = Gf.Matrix4d(*model.get_as_floats(item))
# Signal that this this is the final change block, adjust our center-of-interest then
interaction_ended = model.get_as_ints('interaction_ended')
if interaction_ended and interaction_ended[0]:
transform = Gf.Matrix4d(*model.get_as_floats(item))
# Adjust the center-of-interest if requested (zoom out in perspective does this)
initial_transform = Gf.Matrix4d(*model.get_as_floats('initial_transform'))
coi_start, coi_end = adjust_center_of_interest(model, initial_transform, transform)
if coi_end:
model.set_floats('center_of_interest', [coi_end[0], coi_end[1], coi_end[2]])
# Push the start values into the SceneView
self.__scene_view.model.set_floats('view', _flatten_matrix(transform.GetInverse()))
elif item == model.get_item('projection'):
self.__scene_view.model.set_floats('projection', model.get_as_floats('projection'))
@property
def scene(self):
return self.__scene_view.scene
@property
def model(self):
return self.__scene_view.model
async def wait_human_delay(delay=1):
await ui_test.human_delay(delay)
class TestManipulatorCamera(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
# After running each test
async def tearDown(self):
self._golden_img_dir = None
await super().tearDown()
async def create_test_view(self, name: str, ortho: bool = False, custom: bool = False):
window = await self.create_test_window(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False)
with window.frame:
scene_view = SimpleScene(ortho, custom)
return (window, scene_view)
async def _test_perspective_camera(self):
objects = await self.create_test_view('Perspective')
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_perspective_camera.png')
async def _test_orthographic_camera(self):
objects = await self.create_test_view('Orthographic', True)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_orthographic_camera.png')
async def _test_custom_camera(self):
objects = await self.create_test_view('Custom Orthographic', True, True)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_custom_camera.png')
async def _test_mouse_across_screen(self, mouse_down, mouse_up):
objects = await self.create_test_view('WASD Movement')
mouse_begin = ui_test.Vec2(0, TEST_UI_CENTER.y)
mouse_end = ui_test.Vec2(TEST_WIDTH , TEST_UI_CENTER.y)
await ui_test.input.emulate_mouse(MouseEventType.MOVE, mouse_begin)
await wait_human_delay()
try:
await ui_test.input.emulate_mouse(mouse_down, mouse_begin)
await ui_test.input.emulate_mouse_slow_move(mouse_begin, mouse_end)
await wait_human_delay()
finally:
await ui_test.input.emulate_mouse(mouse_up, mouse_end)
await wait_human_delay()
return objects
async def test_pan_across_screen(self):
"""Test pan across X is a full move across NDC by default"""
objects = await self._test_mouse_across_screen(MouseEventType.MIDDLE_BUTTON_DOWN, MouseEventType.MIDDLE_BUTTON_UP)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_pan_across_screen.png')
async def test_look_across_screen(self):
"""Test look rotation across X is 180 degrees by default"""
objects = await self._test_mouse_across_screen(MouseEventType.RIGHT_BUTTON_DOWN, MouseEventType.RIGHT_BUTTON_UP)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name='test_look_across_screen.png')
class TestFlightMode(OmniUiTest):
async def create_test_view(self, name: str, custom=False, ortho: bool = False):
window = await self.create_test_window(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False)
with window.frame:
simple_scene = SimpleScene()
return (window, simple_scene)
def get_translation(self, model):
matrix = model.view
return (matrix[12], matrix[13], matrix[14])
async def do_key_press(self, key: KeyboardInput, operation = None):
try:
await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_PRESS, key)
await wait_human_delay()
if operation:
operation()
finally:
await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_RELEASE, key)
await wait_human_delay()
async def test_movement(self):
"""Test flight movement via WASD keyboard."""
window, simple_scene = await self.create_test_view('WASD Movement')
model = simple_scene.model
await ui_test.input.emulate_mouse(MouseEventType.MOVE, TEST_UI_CENTER)
await wait_human_delay()
start_pos = self.get_translation(model)
try:
await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER)
await wait_human_delay()
await self.do_key_press(KeyboardInput.W)
after_w = self.get_translation(model)
# W should have moved Z forward
self.assertAlmostEqual(after_w[0], start_pos[0], places=5)
self.assertAlmostEqual(after_w[1], start_pos[1], places=5)
self.assertTrue(after_w[2] > start_pos[2])
await self.do_key_press(KeyboardInput.A)
after_wa = self.get_translation(model)
# A should have moved X left
self.assertTrue(after_wa[0] > after_w[0])
self.assertAlmostEqual(after_wa[1], after_w[1], places=5)
self.assertAlmostEqual(after_wa[2], after_w[2], places=5)
await self.do_key_press(KeyboardInput.S)
after_was = self.get_translation(model)
# S should have moved Z back
self.assertAlmostEqual(after_was[0], after_wa[0], places=5)
self.assertAlmostEqual(after_was[1], after_wa[1], places=5)
self.assertTrue(after_was[2] < after_wa[2])
await self.do_key_press(KeyboardInput.D)
after_wasd = self.get_translation(model)
# D should have moved X right
self.assertTrue(after_wasd[0] < after_was[0])
self.assertAlmostEqual(after_wasd[1], after_was[1], places=5)
self.assertAlmostEqual(after_wasd[2], after_was[2], places=5)
# Test disabling flight-mode in the model would stop keyboard from doing anything
before_wasd = self.get_translation(model)
simple_scene.items[-1].model.set_ints('disable_fly', [1])
await self.do_key_press(KeyboardInput.W)
await self.do_key_press(KeyboardInput.A)
await self.do_key_press(KeyboardInput.S)
await self.do_key_press(KeyboardInput.D)
await wait_human_delay()
after_wasd = self.get_translation(model)
simple_scene.items[-1].model.set_ints('disable_fly', [0])
self.assertTrue(Gf.IsClose(before_wasd, after_wasd, 1e-5))
finally:
await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP)
await wait_human_delay()
async def _test_speed_modifier(self, value_a, value_b):
vel_key = '/persistent/app/viewport/camMoveVelocity'
mod_amount_key = '/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount'
settings = carb.settings.get_settings()
window, simple_scene = await self.create_test_view('WASD Movement')
model = simple_scene.model
settings.set(vel_key, 5)
await ui_test.input.emulate_mouse(MouseEventType.MOVE, TEST_UI_CENTER)
await wait_human_delay()
def compare_velocity(velocity):
vel_value = settings.get(vel_key)
self.assertEqual(vel_value, velocity)
try:
compare_velocity(5)
await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN, TEST_UI_CENTER)
# By default Shift should double speed
await self.do_key_press(KeyboardInput.LEFT_SHIFT, lambda: compare_velocity(value_a))
# By default Shift should halve speed
await self.do_key_press(KeyboardInput.LEFT_CONTROL, lambda: compare_velocity(value_b))
await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP)
await wait_human_delay()
compare_velocity(5)
finally:
settings.set(vel_key, 5)
settings.set(mod_amount_key, 2)
await ui_test.input.emulate_mouse(MouseEventType.RIGHT_BUTTON_UP)
await wait_human_delay()
async def test_speed_modifier_a(self):
"""Test default flight speed adjustement: 2x"""
await self._test_speed_modifier(10, 2.5)
async def test_speed_modifier_b(self):
"""Test custom flight speed adjustement: 4x"""
carb.settings.get_settings().set('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount', 4)
await self._test_speed_modifier(20, 1.25)
async def test_speed_modifier_c(self):
"""Test custom flight speed adjustement: 0x"""
# Test when set to 0
carb.settings.get_settings().set('/exts/omni.kit.manipulator.camera/flightMode/keyModifierAmount', 0)
await self._test_speed_modifier(5, 5)
| 15,278 | Python | 45.440729 | 299 | 0.63994 |
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_manipulator_usd.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestManipulatorUSDCamera']
from omni.kit.manipulator.camera.usd_camera_manipulator import UsdCameraManipulator
from omni.kit.manipulator.camera.model import CameraManipulatorModel, _flatten_matrix
import omni.usd
import omni.kit.test
import carb.settings
from pxr import Gf, Sdf, UsdGeom
from pathlib import Path
from typing import List, Sequence
import sys
import unittest
TESTS_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.manipulator.camera}/data")).absolute().resolve()
USD_FILES = TESTS_PATH.joinpath("tests", "usd")
class TestManipulatorUSDCamera(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await omni.usd.get_context().new_stage_async()
self.stage = omni.usd.get_context().get_stage()
super().setUp()
# After running each test
async def tearDown(self):
super().tearDown()
def __reset_initial_xf(self, usd_manip, initial_transform_item, prim):
# Reset the initial transform to the current transform
matrix = omni.usd.get_world_transform_matrix(prim)
usd_manip.model.set_floats(initial_transform_item, _flatten_matrix(matrix))
# This synthesizes the start of a new event
usd_manip._set_context('', prim.GetPath())
def __setup_usdmanip_tumble_test(self, prim_path: Sdf.Path):
usd_manip = UsdCameraManipulator(prim_path=prim_path)
usd_manip.model = CameraManipulatorModel()
usd_manip._on_began(usd_manip.model)
cam_prim = self.stage.GetPrimAtPath(prim_path)
self.assertTrue(bool(cam_prim))
initial_transform_item = usd_manip.model.get_item('initial_transform')
tumble_item = usd_manip.model.get_item('tumble')
transform_item = usd_manip.model.get_item('transform')
self.__reset_initial_xf(usd_manip, initial_transform_item, cam_prim)
usd_manip.model.set_floats(transform_item, _flatten_matrix(Gf.Matrix4d(1)))
usd_manip.on_model_updated(transform_item)
return (usd_manip, cam_prim, initial_transform_item, tumble_item)
async def __test_tumble_camera(self, prim_path: Sdf.Path, rotations: List[Sequence[float]], epsilon: float = 1.0e-5):
(usd_manip, cam_prim,
initial_transform_item, tumble_item) = self.__setup_usdmanip_tumble_test(prim_path)
rotateYXZ = cam_prim.GetAttribute('xformOp:rotateYXZ')
self.assertIsNotNone(rotateYXZ)
cur_rot = Gf.Vec3d(rotateYXZ.Get())
self.assertTrue(Gf.IsClose(cur_rot, Gf.Vec3d(0, 0, 0), epsilon))
is_linux = sys.platform.startswith('linux')
for index, rotation in enumerate(rotations):
usd_manip.model.set_floats(tumble_item, [-90, 0, 0])
usd_manip.model._item_changed(tumble_item)
self.__reset_initial_xf(usd_manip, initial_transform_item, cam_prim)
cur_rot = Gf.Vec3d(rotateYXZ.Get())
is_equal = Gf.IsClose(cur_rot, Gf.Vec3d(rotation), epsilon)
if is_equal:
continue
# Linux and Windows are returning different results for some rotations that are essentially equivalent
is_equal = True
for current, expected in zip(cur_rot, rotation):
if not Gf.IsClose(current, expected, epsilon):
expected = abs(expected)
is_equal = (expected == 180) or (expected == 360)
if not is_equal:
break
self.assertTrue(is_equal,
msg=f"Rotation values differ: current: {cur_rot}, expected: {rotation}")
async def __test_camera_YXZ_edit(self, rotations: List[Sequence[float]]):
camera = UsdGeom.Camera.Define(self.stage, '/Camera')
cam_prim = camera.GetPrim()
cam_prim.CreateAttribute('omni:kit:centerOfInterest', Sdf.ValueTypeNames.Vector3d,
True, Sdf.VariabilityUniform).Set(Gf.Vec3d(0, 0, -10))
await self.__test_tumble_camera(cam_prim.GetPath(), rotations)
async def test_camera_rotate(self):
'''Test rotation values in USD (with controllerUseSRT set to False)'''
await self.__test_camera_YXZ_edit([
(0, -90, 0),
(0, 180, 0),
(0, 90, 0),
(0, 0, 0)
])
async def test_camera_rotate_SRT(self):
'''Test rotation accumulation in USD with controllerUseSRT set to True'''
settings = carb.settings.get_settings()
try:
settings.set('/persistent/app/camera/controllerUseSRT', True)
await self.__test_camera_YXZ_edit([
(0, -90, 0),
(0, -180, 0),
(0, -270, 0),
(0, -360, 0)
])
finally:
settings.destroy_item('/persistent/app/camera/controllerUseSRT')
async def test_camera_yup_in_zup(self):
'''Test Viewport rotation of a camera from a y-up layer, referenced in a z-up stage'''
await omni.usd.get_context().open_stage_async(str(USD_FILES.joinpath('yup_in_zup.usda')))
self.stage = omni.usd.get_context().get_stage()
await self.__test_tumble_camera(Sdf.Path('/World/yup_ref/Camera'),
[
(0, -90, 0),
(0, 180, 0),
(0, 90, 0),
(0, 0, 0)
]
)
async def test_camera_zup_in_yup(self):
'''Test Viewport rotation of a camera from a z-up layer, referenced in a y-up stage'''
await omni.usd.get_context().open_stage_async(str(USD_FILES.joinpath('zup_in_yup.usda')))
self.stage = omni.usd.get_context().get_stage()
await self.__test_tumble_camera(Sdf.Path('/World/zup_ref/Camera'),
[
(0, 0, -90),
(0, 0, 180),
(0, 0, 90),
(0, 0, 0)
]
)
| 6,352 | Python | 38.216049 | 121 | 0.615712 |
omniverse-code/kit/exts/omni.kit.manipulator.camera/omni/kit/manipulator/camera/tests/test_viewport_manipulator.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestViewportCamera']
import omni.kit.app
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType, KeyboardEventType, KeyboardInput
from pxr import Gf, Sdf, UsdGeom
TEST_GUTTER = 10
TEST_WIDTH, TEST_HEIGHT = 500, 500
TEST_UI_CENTER = ui_test.Vec2(TEST_WIDTH / 2, TEST_HEIGHT / 2)
TEST_UI_LEFT = ui_test.Vec2(TEST_GUTTER, TEST_UI_CENTER.y)
TEST_UI_RIGHT = ui_test.Vec2(TEST_WIDTH - TEST_GUTTER, TEST_UI_CENTER.y)
TEST_UI_TOP = ui_test.Vec2(TEST_UI_CENTER.x, TEST_GUTTER)
TEST_UI_BOTTOM = ui_test.Vec2(TEST_UI_CENTER.x, TEST_HEIGHT - TEST_GUTTER)
class TestViewportCamera(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
from omni.kit.viewport.utility import get_active_viewport
self.viewport = get_active_viewport()
await self.viewport.usd_context.new_stage_async()
self.stage = self.viewport.stage
self.camera = UsdGeom.Xformable(self.stage.GetPrimAtPath(self.viewport.camera_path))
# Disable locking to render results, as there are no render-results
self.viewport.lock_to_render_result = False
super().setUp()
await self.wait_n_updates()
# After running each test
async def tearDown(self):
super().tearDown()
async def wait_n_updates(self, n_frames: int = 3):
app = omni.kit.app.get_app()
for _ in range(n_frames):
await app.next_update_async()
async def __do_mouse_interaction(self,
mouse_down: MouseEventType,
start: ui_test.Vec2,
end: ui_test.Vec2,
mouse_up: MouseEventType,
modifier: KeyboardInput | None = None):
if modifier:
await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_PRESS, modifier)
await ui_test.human_delay()
else:
await self.wait_n_updates(10)
await ui_test.input.emulate_mouse(MouseEventType.MOVE, start)
await ui_test.input.emulate_mouse(mouse_down, start)
await ui_test.input.emulate_mouse_slow_move(start, end)
await ui_test.input.emulate_mouse(mouse_up, end)
if modifier:
await ui_test.input.emulate_keyboard(KeyboardEventType.KEY_RELEASE, modifier)
await ui_test.human_delay()
else:
await self.wait_n_updates()
def assertIsClose(self, a, b):
self.assertTrue(Gf.IsClose(a, b, 0.1))
def assertRotationIsClose(self, a, b):
self.assertTrue(Gf.IsClose(a.GetReal(), b.GetReal(), 0.1))
self.assertTrue(Gf.IsClose(a.GetImaginary(), b.GetImaginary(), 0.1))
@property
def camera_position(self):
return self.camera.GetLocalTransformation(self.viewport.time).ExtractTranslation()
@property
def camera_rotation(self):
return self.camera.GetLocalTransformation(self.viewport.time).ExtractRotation().GetQuaternion()
async def test_viewport_scroll(self, is_locked: bool = False):
"""Test scrollwheel with a Viewport"""
test_pos = [
Gf.Vec3d(500, 500, 500),
Gf.Vec3d(1007.76, 1007.76, 1007.76),
Gf.Vec3d(555.97, 555.97, 555.97),
]
if is_locked:
test_pos = [test_pos[0]] * len(test_pos)
await ui_test.input.emulate_mouse_move_and_click(TEST_UI_CENTER)
self.assertIsClose(self.camera_position, test_pos[0])
await ui_test.input.emulate_mouse_scroll(ui_test.Vec2(0, -2500))
await self.wait_n_updates(100)
self.assertIsClose(self.camera_position, test_pos[1])
await ui_test.input.emulate_mouse_scroll(ui_test.Vec2(0, 1000))
await self.wait_n_updates(100)
self.assertIsClose(self.camera_position, test_pos[2])
async def test_viewport_pan(self, is_locked: bool = False):
"""Test panning across a Viewport"""
test_pos = [
Gf.Vec3d(500, 500, 500),
Gf.Vec3d(1189.86, 500, -189.86),
Gf.Vec3d(699.14, 101.7, 699.14),
]
if is_locked:
test_pos = [test_pos[0]] * len(test_pos)
self.assertIsClose(self.camera_position, test_pos[0])
await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN,
TEST_UI_RIGHT, TEST_UI_LEFT,
MouseEventType.MIDDLE_BUTTON_UP)
self.assertIsClose(self.camera_position, test_pos[1])
await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN,
TEST_UI_LEFT, TEST_UI_RIGHT,
MouseEventType.MIDDLE_BUTTON_UP)
self.assertIsClose(self.camera_position, test_pos[0])
await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN,
TEST_UI_CENTER, TEST_UI_TOP,
MouseEventType.MIDDLE_BUTTON_UP)
self.assertIsClose(self.camera_position, test_pos[2])
await self.__do_mouse_interaction(MouseEventType.MIDDLE_BUTTON_DOWN,
TEST_UI_CENTER, TEST_UI_BOTTOM,
MouseEventType.MIDDLE_BUTTON_UP)
self.assertIsClose(self.camera_position, test_pos[0])
async def test_viewport_look(self, is_locked: bool = False):
"""Test panning across a Viewport"""
test_rot = [
Gf.Quaternion(0.88, Gf.Vec3d(-0.27, 0.36, 0.11)),
Gf.Quaternion(-0.33, Gf.Vec3d(0.10, 0.89, 0.28)),
Gf.Quaternion(0.86, Gf.Vec3d(0.33, 0.35, -0.13)),
]
if is_locked:
test_rot = [test_rot[0]] * len(test_rot)
self.assertRotationIsClose(self.camera_rotation, test_rot[0])
await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN,
TEST_UI_RIGHT, TEST_UI_LEFT,
MouseEventType.RIGHT_BUTTON_UP)
self.assertRotationIsClose(self.camera_rotation, test_rot[1])
await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN,
TEST_UI_LEFT, TEST_UI_RIGHT,
MouseEventType.RIGHT_BUTTON_UP)
self.assertRotationIsClose(self.camera_rotation, test_rot[0])
await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN,
TEST_UI_CENTER, TEST_UI_TOP,
MouseEventType.RIGHT_BUTTON_UP)
self.assertRotationIsClose(self.camera_rotation, test_rot[2])
await self.__do_mouse_interaction(MouseEventType.RIGHT_BUTTON_DOWN,
TEST_UI_CENTER, TEST_UI_BOTTOM,
MouseEventType.RIGHT_BUTTON_UP)
self.assertRotationIsClose(self.camera_rotation, test_rot[0])
async def __test_viewport_orbit_modifer_not_working(self, is_locked: bool = False):
"""Test orbit across a Viewport"""
test_rot = [
Gf.Quaternion(0.88, Gf.Vec3d(-0.27, 0.36, 0.11)),
Gf.Quaternion(-0.33, Gf.Vec3d(0.10, 0.89, 0.28)),
Gf.Quaternion(0.86, Gf.Vec3d(0.33, 0.35, -0.13)),
]
if is_locked:
test_rot = [test_rot[0]] * len(test_rot)
await ui_test.input.emulate_mouse_move_and_click(TEST_UI_CENTER)
self.assertRotationIsClose(self.camera_rotation, test_rot[0])
await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN,
TEST_UI_RIGHT, TEST_UI_LEFT,
MouseEventType.LEFT_BUTTON_UP,
KeyboardInput.LEFT_ALT)
self.assertRotationIsClose(self.camera_rotation, test_rot[1])
await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN,
TEST_UI_LEFT, TEST_UI_RIGHT,
MouseEventType.LEFT_BUTTON_UP,
KeyboardInput.LEFT_ALT)
self.assertRotationIsClose(self.camera_rotation, test_rot[0])
await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN,
TEST_UI_CENTER, TEST_UI_TOP,
MouseEventType.LEFT_BUTTON_UP,
KeyboardInput.LEFT_ALT)
self.assertRotationIsClose(self.camera_rotation, test_rot[2])
await self.__do_mouse_interaction(MouseEventType.LEFT_BUTTON_DOWN,
TEST_UI_CENTER, TEST_UI_BOTTOM,
MouseEventType.LEFT_BUTTON_UP,
KeyboardInput.LEFT_ALT)
self.assertRotationIsClose(self.camera_rotation, test_rot[0])
async def test_viewport_lock(self):
"""Test the lock attribute blocks navigation"""
self.camera.GetPrim().CreateAttribute("omni:kit:cameraLock", Sdf.ValueTypeNames.Bool, True).Set(True)
await self.test_viewport_pan(is_locked=True)
await self.test_viewport_look(is_locked=True)
await self.test_viewport_scroll(is_locked=True)
| 9,868 | Python | 44.270642 | 109 | 0.582286 |
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/_test_runner_window.py | """Implementation of the manager of the Test Runner window.
Exports only TestRunnerWindow: The object managing the window, a singleton. Instatiate it to create the window.
Limitations:
- When tests are running and extensions are disabled then enabled as part of it any tests owned by the disabled
extensions are removed and not restored.
Toolbar Interactions - what happens when each control on the toolbar is used:
Run Selected: Gather the list of all selected tests and run them one at a time until completion (disabled when
no tests exist)
Select All: Add all tests to the selection list (disabled when all tests are currently selected)
Deselect All: Remove all tests from the selection list (disabled when no tests are currently selected)
Filter: Text that full tests names must match before being displayed
Load Tests...: Reload the set of available tests from one of the plug-in options
Properties: Display the settings in a separate window
Note that all tests displayed must come from an enabled extension. To add tests on currently disabled extensions you
would just enable the extension and the test list will be repopulated from the new set of enabled extensions. Similarly
if you disable an extension its tests will be removed from the list.
Individual Test Interactions - what happens when each per-test control is used:
Checkbox: Adds or removes the test from the selection list
Run: Run the one test and modify its icon to indicate test state
Soak: Run the one test 1,000 times and modify its icon to indicate test state
Open: Open the source file of the test script for the test
(Final icon is updated to depict the state of the test - not run, running, successful, failed)
TODO: Fix the text file processing to show potential missing extensions
TODO: Add in editing of the user settings in the window
# --------------------------------------------------------------------------------------------------------------
# def _edit_filter_settings(self):
# # Emit the UI commands required to edit the filters defined in the user settings
# from carb.settings import get_settings
# include_tests = get_settings().get("/exts/omni.kit.test/includeTests")
# exclude_tests = get_settings().get("/exts/omni.kit.test/excludeTests")
"""
from __future__ import annotations
import asyncio
from contextlib import suppress
from enum import auto, Enum
import fnmatch
from functools import partial
import logging
from pathlib import Path
import sys
import unittest
import carb
import carb.settings
import omni.ext
import omni.kit.test
import omni.kit.commands
import omni.kit.app
import omni.kit.ui
from omni.kit.test import TestRunStatus
from omni.kit.test import TestPopulator
from omni.kit.test import TestPopulateAll
from omni.kit.test import TestPopulateDisabled
from omni.kit.test import DEFAULT_POPULATOR_NAME
from omni.kit.window.properties import TestingPropertiesWindow
import omni.ui as ui
__all__ = ["TestRunnerWindow"]
# Size constants
_BUTTON_HEIGHT = 24
# ==============================================================================================================
# Local logger for dumping debug information about the test runner window operation.
# By default it is off but it can be enabled in the extension setup.
_LOG = logging.getLogger("test_runner_window")
# ==============================================================================================================
class _TestUiEntry:
"""UI Data for a single test in the test runner"""
def __init__(self, test: unittest.TestCase, file_path: str):
"""Initialize the entry with the given test"""
self.test: unittest.TestCase = test # Test this entry manages
self.checkbox: ui.Checkbox = None # Selection checkbox for this test
self.sub_checked: ui.Subscription = None # Subscription to the checkbox change
self.label_stack: ui.HStack = None # Container stack for the test module and name
self.run_button: ui.Button = None # Button for running the test
self.soak_button: ui.Button = None # Button for running the test 1000 times
self.open_button: ui.Button = None # Button for opening the file containing the test
self.file_path: Path = file_path # Path to the file containing the test
self.status: TestRunStatus = TestRunStatus.UNKNOWN # Current test status
self.status_label: ui.Label = None # Icon label indicating the test status
def destroy(self):
"""Destroy the test entry; mostly to avoid leaking caused by dangling callbacks"""
with suppress(AttributeError):
self.sub_checked = None
self.checkbox = None
with suppress(AttributeError):
self.run_button.set_clicked_fn(None)
self.run_button = None
with suppress(AttributeError):
self.soak_button.set_clicked_fn(None)
self.soak_button = None
with suppress(AttributeError):
self.open_button.set_clicked_fn(None)
self.open_button = None
def __del__(self):
"""Ensure the destroy is always called - it's safe to call it multiple times"""
self.destroy()
# ==============================================================================================================
class _Buttons(Enum):
"""Index for all of the buttons created in the toolbar"""
RUN = auto() # Run all selected tests
SELECT_ALL = auto() # Select every listed test
DESELECT_ALL = auto() # Deselect every listed test
PROPERTIES = auto() # Open the properties window
LOAD_MENU = auto() # Open the menu for loading a test list
# ==============================================================================================================
class _TestUiPopulator:
"""Base class for the objects used to populate the initial list of tests, before filtering."""
def __init__(self, populator: TestPopulator):
"""Set up the populator with the important information it needs for getting tests from some location
Args:
name: Name of the populator, which can be used for a menu
description: Verbose description of the populator, which can be used for the tooltip of the menu item
doing_what: Parameter to the descriptive waiting sentence "Rebuilding after {doing_what}..."
source: Source type this populator implements
"""
self.populator = populator
self._cached_tests: list[_TestUiEntry] = []
# --------------------------------------------------------------------------------------------------------------
@property
def name(self) -> str:
"""The name of the populator"""
return self.populator.name
@property
def description(self) -> str:
"""The description of the populator"""
return self.populator.description
@property
def tests(self) -> list[_TestUiEntry]:
"""The list of test UI entries gleaned from the raw test list supplied by the populator implementation"""
if not self._cached_tests:
_LOG.info("Translating %d unit tests into a _TestUiEntry list", len(self.populator.tests))
self._cached_tests = {}
for test in self.populator.tests:
try:
file_path = sys.modules[test.__module__].__file__
except KeyError:
# if the module is not enabled the test does not belong in the list
continue
entry = _TestUiEntry(test, file_path)
self._cached_tests[test.id()] = entry
return self._cached_tests
# --------------------------------------------------------------------------------------------------------------
def clear(self):
"""Remove the cache so that it can be rebuilt on demand, usually if the contents might have changed"""
self._cached_tests = {}
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
"""Opportunity to clean up any allocated resources"""
self._cached_tests = {}
self.populator.destroy()
# --------------------------------------------------------------------------------------------------------------
def get_tests(self, call_when_done: callable):
"""Main method for retrieving the list of tests that the populator provides.
When the tests are available invoke the callback with the test list.
call_when_done(_TestUiPopulator, canceled: bool)
"""
def __create_cache(canceled: bool = False):
call_when_done(self, canceled)
if not self._cached_tests:
self.populator.get_tests(__create_cache)
else:
call_when_done(self)
# ==============================================================================================================
class TestRunnerWindow:
"""Managers the window containing the test runner
Members:
_buttons: Dictionary of _Buttons:ui.Button for all of the toolbar buttons
_change_sub: Subscription to the extension list change event
_count: Temporary variable to count number of iterations during test soak
_filter_begin_edit_sub: Subscription to the start of editing the filter text field
_filter_end_edit_sub: Subscription to the end of editing the filter text field
_filter_hint: Label widget holding the overlay text for the filter text field
_filter_regex: Expression on which to filter the list of source tests
_filter: StringField widget holding the filter text
_is_running_tests: Are the selected tests currently running?
_load_menu: UI Widget containing the menu used for loading the test list
_properties_window: The temporary dialog that displays the test running properties set by the user
_refresh_task: Async task to refresh the test status values as they are completed
_status_label: Text to show in the label in the toolbar that shows test counts
_test_frame: UI Widget encompassing the frame containing the list of tests to run
_test_list_source_rc: RadioCollection containing the test source choices
_test_populators: Dictionary of name:_TestUiPopulator used to populate the full list of tests in the window
_tests: Dictionary of (ID, Checkbox) corresponding to all visible tests
_tests_selected: Number of tests in the dictionary currently selected. This is maintained on the fly to avoid
an O(N^2) update problem when monitoring checkbox changes and updating the SelectAll buttons
_toolbar_frame: UI Widget encompassing the set of tools at the top of the window
_ui_status_label: UI Widget containing the label displaying test runner status
_window: UI Widget of the toolbar window
"""
# Location of the window in the larger UI element path space
WINDOW_NAME = "Test Runner"
MENU_PATH = f"Window/{WINDOW_NAME}"
_POPULATORS = [TestPopulateAll(), TestPopulateDisabled()]
WINDOW_MANAGER = None
# --------------------------------------------------------------------------------------------------------------
# API for adding and removing custom populators of the test list
@classmethod
def add_populator(cls, new_populator: TestPopulator):
"""Adds the new populator to the available list, raising ValueError if there already is one with that name"""
if new_populator in cls._POPULATORS:
raise ValueError(f"Tried to add the same populator twice '{new_populator.name}'")
cls._POPULATORS.append(new_populator)
# Updating the window allows dynamic adding and removal of populator types
if cls.WINDOW_MANAGER is not None:
cls.WINDOW_MANAGER._test_populators[new_populator.name] = _TestUiPopulator(new_populator) # noqa: PLW0212
cls.WINDOW_MANAGER._toolbar_frame.rebuild() # noqa: PLW0212
@classmethod
def remove_populator(cls, populator_to_remove: str):
"""Removes the populator with the given name, raising KeyError if it does not exist"""
to_remove = None
for populator in cls._POPULATORS:
if populator.name == populator_to_remove:
to_remove = populator
break
if to_remove is None:
raise KeyError(f"Trying to remove populator named {populator_to_remove} before adding it")
# Updating the window allows dynamic adding and removal of populator types
if cls.WINDOW_MANAGER is not None:
del cls.WINDOW_MANAGER._test_populators[populator_to_remove] # pylint: disable=protected-access
cls.WINDOW_MANAGER._toolbar_frame.rebuild() # pylint: disable=protected-access
cls._POPULATORS.remove(to_remove)
def __init__(self, start_open: bool):
"""Set up the window and open it if the setting to always open it is enabled"""
TestRunnerWindow.WINDOW_MANAGER = self
self._buttons: dict[_Buttons, ui.Button] = {}
self._change_sub: carb.Subscription = None
self._count: int = 0
self._filter_begin_edit_sub: carb.Subscription = None
self._filter_end_edit_sub: carb.Subscription = None
self._filter_hint: ui.Label = None
self._filter_regex: str = ""
self._filter: ui.StringField = None
self._is_running_tests: bool = False
self._load_menu: ui.Menu = None
self._test_file_path: Path = None
self._properties_window: TestingPropertiesWindow = None
self._refresh_task: asyncio.Task = None
self._test_frame: ui.ScrollingFrame = None
self._status_label: str = "Checking for tests..."
self._test_list_source_rc: ui.RadioCollection = None
self._tests: dict[str, ui.CheckBox] = {}
self._tests_selected: int = 0
self._test_populators = {
populator.name: _TestUiPopulator(populator) for populator in self._POPULATORS
}
self._test_populator: TestPopulator = None
self._toolbar_frame: ui.Frame = None
self._ui_status_label: ui.Label = None
_LOG.info("Initializing the main window")
manager = omni.kit.app.get_app().get_extension_manager()
self._change_sub = manager.get_change_event_stream().create_subscription_to_pop(
self.on_extensions_changed, name="test_runner extensions change event"
)
self._window = ui.Window(
self.WINDOW_NAME,
menu_path=self.MENU_PATH,
width=1200,
height=800,
dockPreference=ui.DockPreference.RIGHT_TOP,
visibility_changed_fn=self._visibility_changed,
width_changed_fn=self._width_changed,
)
with self._window.frame:
with ui.VStack():
self._toolbar_frame = ui.Frame(height=_BUTTON_HEIGHT + 4)
self._toolbar_frame.set_build_fn(self._build_toolbar_frame)
with self._toolbar_frame:
self._build_toolbar_frame()
self._test_frame = ui.ScrollingFrame(
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
)
self._test_frame.set_build_fn(self._build_test_frame)
# Populate the initial test list
self._populate_test_entries(self._test_populators[DEFAULT_POPULATOR_NAME])
self._window.visible = start_open
# --------------------------------------------------------------------------------------------------------------
def destroy(self):
"""Detach all subscriptions and destroy the window elements to avoid dangling callbacks and UI elements"""
_LOG.info("Destroying the main window {")
self.WINDOW_MANAGER = None
if self._window is not None:
self._window.visible = False
# Remove the callbacks first
for _button_id, button in self._buttons.items():
button.set_clicked_fn(None)
self._buttons = {}
for populator in self._test_populators.values():
populator.destroy()
self._test_populators = None
# Remove the widget elements before removing the window itself
self._clean_refresh_task()
self._change_sub = None
self._count = 0
self._filter = None
self._filter_begin_edit_sub = None
self._filter_end_edit_sub = None
self._filter_hint = None
self._filter_regex = ""
self._load_menu = None
self._ui_status_label = None
self._status_label = None
self._test_list_source_rc = None
self._test_populator = None
self._tests = {}
self._tests_selected = 0
if self._properties_window is not None:
self._properties_window.destroy()
del self._properties_window
self._properties_window = None
if self._toolbar_frame is not None:
self._toolbar_frame.set_build_fn(None)
del self._toolbar_frame
self._toolbar_frame = None
if self._test_frame is not None:
self._test_frame.set_build_fn(None)
del self._test_frame
self._test_frame = None
if self._window is not None:
self._window.set_visibility_changed_fn(None)
self._window.set_width_changed_fn(None)
self._window.frame.set_build_fn(None)
del self._window
self._window = None
# --------------------------------------------------------------------------------------------------------------
@property
def visible(self) -> bool:
return self._window.visible if self._window is not None else False
@visible.setter
def visible(self, visible: bool):
if self._window is not None:
self._window.visible = visible
elif visible:
raise ValueError("Tried to change visibility after window was destroyed")
def _visibility_changed(self, visible: bool):
"""Update the menu with the visibility state"""
_LOG.info("Window visibility changed to %s", visible)
editor_menu = omni.kit.ui.EditorMenu()
editor_menu.set_value(self.MENU_PATH, visible)
# --------------------------------------------------------------------------------------------------------------
def _width_changed(self, new_width: float):
"""Update the sizing of the test frame when the window size changes"""
_LOG.info("Window width changed to %f", new_width)
if self._test_frame is not None:
self._resize_test_frame(new_width)
# --------------------------------------------------------------------------------------------------------------
def on_extensions_changed(self, *_):
"""Callback executed when the known extensions may have changed."""
# Protect calls to _LOG since if it's this extension being disabled it may not exist
if self._is_running_tests:
if _LOG is not None:
_LOG.info("Extension changes ignored while tests are running as it could be part of the tests")
else:
if _LOG is not None:
_LOG.info("Extensions were changed, tests are rebuilding")
for populator in self._test_populators.values():
populator.clear()
self._refresh_after_tests_complete(load_tests=True, cause="extensions changed")
# --------------------------------------------------------------------------------------------------------------
def _refresh_after_tests_complete(self, load_tests: bool, cause: str, new_populator: TestPopulator = None):
"""Refresh the window information after the tests finish running.
If load_tests is True then reconstruct all of the tests from the current test source selected.
If cause is not empty then place a temporary message in the test pane to indicate a rebuild is happening.
If a new_populator is specified then it will replace the existing one if its population step succeeds,
otherwise the original will remain.
"""
async def _delayed_refresh():
try:
# Busy wait until the tests are done running
slept = 0.0
while self._is_running_tests:
_LOG.debug("....sleep(%f)", slept)
slept += 0.2
await asyncio.sleep(0.2)
# Refresh the test information
_LOG.info("Delayed refresh triggered with load_tests=%s", load_tests)
if cause:
self._ui_status_label.text = f"Rebuilding after {cause}..."
await omni.kit.app.get_app().next_update_async()
if load_tests:
_LOG.info("...repopulating the test list")
self._populate_test_entries(new_populator)
else:
_LOG.info("...rebuilding the test frame")
with self._test_frame:
self._build_test_frame()
except asyncio.CancelledError:
pass
except Exception as error: # pylint: disable=broad-except
carb.log_warn(f"Failed to refresh content of window.tests. Error: '{error}' {type(error)}.")
self._clean_refresh_task()
self._refresh_task = asyncio.ensure_future(_delayed_refresh())
# --------------------------------------------------------------------------------------------------------------
def _update_toolbar_status(self):
"""Update the state of the elements in the toolbar, avoiding a full rebuild when values change"""
filtered_tests = self._filtered_tests()
_LOG.info("Refreshing the toolbar status for %d tests", len(filtered_tests))
any_on = self._tests_selected > 0
any_off = self._tests_selected < len(filtered_tests)
_LOG.info(" RUN=%s, SELECT_ALL=%s, DESELECT_ALL=%s", any_on, any_off, any_on)
self._buttons[_Buttons.RUN].enabled = any_on
self._buttons[_Buttons.SELECT_ALL].enabled = any_off
self._buttons[_Buttons.DESELECT_ALL].enabled = any_on
_LOG.info("Reset status to '%s'", self._status_label)
self._ui_status_label.text = self._status_label
# --------------------------------------------------------------------------------------------------------------
def _build_toolbar_frame(self):
"""Emit the UI commands required to build the toolbar that appears at the top of the window"""
_LOG.info("Rebuilding the toolbar frame")
# Defining the toolbar callbacks at the top of this method because they are so small
def on_run(*_):
_LOG.info("Hit the Run button")
tests = [entry.test for entry in self._tests.values() if entry.checkbox.model.as_bool]
self._run_tests(tests)
def on_select_all(*_):
_LOG.info("Hit the Select All button")
filtered_tests = self._filtered_tests()
for entry in filtered_tests.values():
entry.checkbox.model.set_value(True)
self._tests_selected = len(filtered_tests)
self._update_toolbar_status()
def on_deselect_all(*_):
_LOG.info("Hit the Deselect All button")
filtered_tests = self._filtered_tests()
for entry in filtered_tests.values():
entry.checkbox.model.set_value(False)
self._tests_selected = 0
self._update_toolbar_status()
def _on_filter_begin_edit(model: ui.AbstractValueModel):
self._filter_hint.visible = False
def _on_filter_end_edit(model: ui.AbstractValueModel):
if len(model.get_value_as_string()) == 0:
self._filter_hint.visible = True
self._filter_regex = ""
else:
self._filter_regex = f"*{model.get_value_as_string()}*"
_LOG.info("Reset filter to '%s'", self._filter_regex)
self._refresh_after_tests_complete(load_tests=False, cause="filter changed")
def on_properties(*_):
_LOG.info("Hit the Properties button")
if self._properties_window is None:
self._properties_window = TestingPropertiesWindow()
self._properties_window.show()
# + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
with ui.HStack(height=_BUTTON_HEIGHT + 4, style={"Button.Label:disabled": {"color": 0xFF606060}}):
self._buttons[_Buttons.RUN] = ui.Button(
"Run Selected", clicked_fn=on_run, width=ui.Percent(10), style={"border_radius": 5.0})
self._buttons[_Buttons.SELECT_ALL] = ui.Button(
"Select All", clicked_fn=on_select_all, width=ui.Percent(10), style={"border_radius": 5.0})
self._buttons[_Buttons.DESELECT_ALL] = ui.Button(
"Deselect All", clicked_fn=on_deselect_all, width=ui.Percent(10), style={"border_radius": 5.0})
with ui.ZStack(width=ui.Percent(20)):
ui.Spacer(width=ui.Pixel(10))
# Trick required to give the string field a greyed out "hint" as to what should be typed in it
self._filter = ui.StringField(height=_BUTTON_HEIGHT)
self._filter_hint = ui.Label(
" Filter (*, ?)", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
if self._filter_regex:
self._filter.model.set_value(self._filter_regex[1:-1])
self._filter_hint.visible = False
self._filter_begin_edit_sub = self._filter.model.subscribe_begin_edit_fn(_on_filter_begin_edit)
self._filter_end_edit_sub = self._filter.model.subscribe_value_changed_fn(_on_filter_end_edit)
with ui.HStack(height=0, width=ui.Percent(20)):
ui.Spacer(width=ui.Pixel(3))
def __on_flag_set(populator):
_LOG.info("Invoking load menu with %s", populator)
self._load_menu = None
self._refresh_after_tests_complete(
load_tests=True,
cause=f"selecting populator '{populator.name}'",
new_populator=populator
)
def __show_load_menu(mouse_x: int, mouse_y: int, mouse_button: int, modifier: int):
_LOG.info("Invoked load menu at %d,%d - B%d/%d", mouse_x, mouse_y, mouse_button, modifier)
widget = self._buttons[_Buttons.LOAD_MENU]
self._load_menu = ui.Menu()
with self._load_menu:
for populator_name in sorted(self._test_populators.keys()):
populator = self._test_populators[populator_name]
ui.MenuItem(
populator.name,
triggered_fn=partial(__on_flag_set, populator),
checkable=True,
checked=(
self._test_populator is not None and (populator.name == self._test_populator.name)
),
)
self._load_menu.show_at(
(int)(widget.screen_position_x),
(int)(widget.screen_position_y + widget.computed_content_height)
)
self._buttons[_Buttons.LOAD_MENU] = ui.Button(
"Load Tests From...",
height=_BUTTON_HEIGHT + 4,
width=0,
mouse_released_fn=__show_load_menu,
style={"border_radius": 5.0},
)
with ui.HStack(width=ui.Percent(10)):
self._buttons[_Buttons.PROPERTIES] = ui.Button(
"Properties",
clicked_fn=on_properties,
style={"border_radius": 5.0},
)
ui.Spacer(width=ui.Pixel(10))
with ui.HStack(height=_BUTTON_HEIGHT + 4, width=ui.Percent(15)):
self._ui_status_label = ui.Label("Initializing tests...")
# --------------------------------------------------------------------------------------------------------------
def _space_for_test_labels(self, full_width: float) -> float:
"""Returns the number of pixels available for the test labels in the test frame, for manual resizing"""
label_space = full_width - 20 - 45 - 50 - 50 - 30 - 5 * 3
# Arbitrary "minimum readable" limit
if label_space < 200:
_LOG.info("Label space went below the threshold of 200 to %f, clipping it to 200", label_space)
label_space = 200
return label_space
# --------------------------------------------------------------------------------------------------------------
def _resize_test_frame(self, new_size: float):
"""Reset the manually computed size for all of the elements in the test frame. Avoids full rebuild."""
label_space = self._space_for_test_labels(new_size)
_LOG.info("Resizing test frame with %d pixels of %d for labels", label_space, new_size)
for _test_id, entry in self._tests.items():
if entry.label_stack is None:
continue
entry.label_stack.width = ui.Pixel(int(label_space))
# --------------------------------------------------------------------------------------------------------------
def _filtered_tests(self) -> dict[str, ui.CheckBox]:
return {
test_id: entry for test_id, entry in self._tests.items()
if (not self._filter_regex) or fnmatch.fnmatch(test_id.lower(), self._filter_regex.lower())
}
# --------------------------------------------------------------------------------------------------------------
def _build_test_frame(self):
"""Emit the UI commands required to populate the test frame with the list of visible tests"""
_LOG.info("Rebuilding the test frame with %d tests", len(self._tests))
# Compute the space available for the test names by taking the total frame width and subtracting the size
# used by the checkbox, run button, soak button, open button, and status icon, plus spacing between them
label_space = self._space_for_test_labels(self._window.frame.computed_width)
with ui.VStack():
ui.Spacer(height=ui.Pixel(10))
filtered_tests = self._filtered_tests()
for test_id, entry in filtered_tests.items():
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Test-specific callbacks
def on_checked(check_model: ui.AbstractValueModel):
filtered_tests = self._filtered_tests()
if check_model.as_bool:
self._tests_selected += 1
if self._tests_selected in (1, len(filtered_tests)):
self._update_toolbar_status()
else:
self._tests_selected -= 1
if self._tests_selected in (0, len(filtered_tests) - 1):
self._update_toolbar_status()
def on_run_test(*_, test: unittest.TestCase = entry.test):
self._run_tests([test])
def on_soak_test(*_, test: unittest.TestCase = entry.test):
self._run_tests([test], repeats=1000)
def on_open(*_, path: str = entry.file_path):
import webbrowser
webbrowser.open(path)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Test row
entry.hstack = ui.HStack(spacing=2, height=0, width=ui.Percent(100))
with entry.hstack:
entry.checkbox = ui.CheckBox(
value=False,
on_changed_fn=on_checked,
style={"margin_height": 2},
width=20,
)
entry.sub_checked = entry.checkbox.model.subscribe_value_changed_fn(on_checked)
test_class, test_method = test_id.rsplit(".", 1)
entry.label_stack = ui.HStack(width=label_space)
with entry.label_stack:
entry.label1 = ui.Label(
test_class,
tooltip=entry.file_path,
elided_text=True,
alignment=ui.Alignment.LEFT_TOP,
width=ui.Fraction(2),
)
entry.label2 = ui.Label(
test_method,
tooltip=test_method,
elided_text=True,
alignment=ui.Alignment.LEFT_TOP,
width=ui.Fraction(1),
)
entry.run_button = ui.Button("Run", clicked_fn=on_run_test, width=45)
entry.soak_button = ui.Button("Soak", clicked_fn=on_soak_test, width=50)
entry.open_button = ui.Button("Open", clicked_fn=on_open, width=50)
entry.status_label = ui.Label("", width=30)
entry.status = TestRunStatus.UNKNOWN
self._refresh_test_status(test_id)
tests_available = len(self._tests)
tests_used = len(filtered_tests)
if self._test_populator is not None:
self._status_label = f"Showing {tests_used} of {tests_available} test(s) from {self._test_populator.name}"
else:
self._status_label = f"Showing {tests_used} of {tests_available} test(s) with no populator"
self._update_toolbar_status()
# --------------------------------------------------------------------------------------------------------------
def _refresh_test_status(self, test_id: str):
_LOG.debug("Refresh status of test %s to %s", test_id, self._tests[test_id].status)
status = self._tests[test_id].status
status_to_svg = {
TestRunStatus.UNKNOWN: "${glyphs}/question.svg",
TestRunStatus.RUNNING: "${glyphs}/spinner.svg",
TestRunStatus.FAILED: "${glyphs}/exclamation.svg",
TestRunStatus.PASSED: "${glyphs}/check_solid.svg",
}
status_to_color = {
TestRunStatus.UNKNOWN: 0xFFFFFFFF,
TestRunStatus.RUNNING: 0xFFFF7D7D,
TestRunStatus.PASSED: 0xFF00FF00,
TestRunStatus.FAILED: 0xFF0000FF,
}
code = ui.get_custom_glyph_code(status_to_svg.get(status, ""))
label = self._tests[test_id].status_label
label.text = f"{code}"
label.set_style({"color": status_to_color[status]})
# --------------------------------------------------------------------------------------------------------------
def _set_test_status(self, test_id: str, status: TestRunStatus):
_LOG.info("Setting status of test '%s' to %s", test_id, status)
try:
self._tests[test_id].status = status
self._refresh_test_status(test_id)
except KeyError:
_LOG.warning("...could not find test %s in the list", test_id)
# --------------------------------------------------------------------------------------------------------------
def _set_is_running(self, running: bool):
_LOG.info("Change running state to %s", running)
self._is_running_tests = running
self._buttons[_Buttons.RUN].enabled = not running
if running:
self._ui_status_label.text = "Running Tests..."
else:
self._ui_status_label.text = ""
# -------------------------------------------------------------------------------------------------------------
def _populate_test_entries(self, new_populator: TestPopulator = None):
"""Repopulate the test entry information based on the current filtered source test list.
If a new_populator is specified then set the current one to it if the population succeeded, otherwise retain
the original.
"""
async def __populate():
_LOG.info("Retrieving the tests from the populator")
def __repopulate(populator: _TestUiPopulator, canceled: bool = False):
if canceled:
_LOG.info("...test retrieval was canceled")
self._test_frame.enabled = True
else:
self._tests_selected = 0
self._tests = populator.tests
if new_populator is not None:
self._test_populator = new_populator
_LOG.info("...triggering the test frame rebuild after repopulation")
self._test_frame.enabled = True
self._test_frame.rebuild()
self._test_frame.enabled = False
if new_populator is not None:
new_populator.get_tests(__repopulate)
elif self._test_populator is not None:
self._test_populator.get_tests(__repopulate)
asyncio.ensure_future(__populate())
# --------------------------------------------------------------------------------------------------------------
def _run_tests(self, tests, repeats=0, ignore_running=False):
"""Find all of the selected tests and execute them all asynchronously"""
_LOG.info("Running the tests with a repeat of %d", repeats)
if self._is_running_tests and not ignore_running:
_LOG.info("...skipping, already running the tests")
return
def on_finish(runner):
if self._count > 0:
self._count -= 1
print(f"\n\n\n\n{'-'*40} Iteration {self._count} {'-'*40}\n\n")
self._run_tests(tests, self._count, ignore_running=True)
return
self._set_is_running(False)
def on_status_report(test_id, status, **_):
self._set_test_status(test_id, status)
self._count = repeats
self._set_is_running(True)
for t in tests:
self._set_test_status(t.id(), TestRunStatus.UNKNOWN)
omni.kit.test.run_tests(tests, on_finish, on_status_report)
# --------------------------------------------------------------------------------------------------------------
def _clean_refresh_task(self):
"""Clean up the refresh task, canceling it if it is in progress first"""
with suppress(asyncio.CancelledError, AttributeError):
self._refresh_task.cancel()
self._refresh_task = None
| 39,484 | Python | 48.854798 | 119 | 0.54731 |
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/tests.py | """Implementation of the extension containing the Test Runner window."""
import logging
import sys
import carb
import omni.ext
from omni.kit.ui import EditorMenu
# Cannot do relative imports here due to the way the omni.kit.window import space is duplicated in multiple extensions
from omni.kit.window._test_runner_window import _LOG
from omni.kit.window._test_runner_window import TestRunnerWindow
# ==============================================================================================================
class Extension(omni.ext.IExt):
"""The extension manager that handles the life span of the test runner window"""
def __init__(self):
self._test_runner_window = None
self._menu_item = None
super().__init__()
def _show_window(self, menu: str, value: bool):
if self._test_runner_window is None:
self._test_runner_window = TestRunnerWindow(value)
else:
self._test_runner_window.visible = value
def on_startup(self):
_LOG.disabled = True # Set to False to dump out debugging information for the extension
if not _LOG.disabled:
_handler = logging.StreamHandler(sys.stdout)
_handler.setFormatter(logging.Formatter("TestRunner: %(levelname)s: %(message)s"))
_LOG.addHandler(_handler)
_LOG.setLevel(logging.INFO)
_LOG.info("Starting up the test runner extension")
open_window = carb.settings.get_settings().get("/exts/omni.kit.window.tests/openWindow")
self._menu_item = EditorMenu.add_item(TestRunnerWindow.MENU_PATH, self._show_window, toggle=True, value=open_window)
if open_window:
self._show_window(TestRunnerWindow.MENU_PATH, True)
def on_shutdown(self):
"""Cleanup the constructed elements"""
_LOG.info("Shutting down the test runner extension")
if self._test_runner_window is not None:
_LOG.info("Destroying the test runner window")
self._test_runner_window.visible = False
self._test_runner_window.destroy()
self._test_runner_window = None
EditorMenu.remove_item(TestRunnerWindow.MENU_PATH)
handler_list = _LOG.handlers
for handler in handler_list:
_LOG.removeHandler(handler)
self._menu_item = None
| 2,333 | Python | 41.436363 | 124 | 0.63009 |
omniverse-code/kit/exts/omni.kit.window.tests/omni/kit/window/properties.py | import carb
import carb.settings
import omni.kit.app
import omni.ui as ui
HUMAN_DELAY_SETTING = "/exts/omni.kit.ui_test/humanDelay"
class TestingPropertiesWindow:
def __init__(self):
self._window = ui.Window("Testing Properties", width=400, height=200, flags=ui.WINDOW_FLAGS_NO_DOCKING)
self._window.visible = False
def destroy(self):
self._window = None
def show(self):
if not self._window.visible:
self._window.visible = True
self.refresh()
def refresh(self):
with self._window.frame:
with ui.VStack(height=0):
settings = carb.settings.get_settings()
ui.Spacer(height=10)
ui.Label("Test Settings:", style={"color": 0xFFB7F222, "font_size": 16})
ui.Spacer(height=5)
for key in ["/exts/omni.kit.test/includeTests", "/exts/omni.kit.test/excludeTests"]:
value = settings.get(key)
ui.Label(f"{key}: {value}")
ui.Spacer(height=5)
# Setting specific to UI tests
manager = omni.kit.app.get_app().get_extension_manager()
if manager.is_extension_enabled("omni.kit.ui_test"):
ui.Spacer(height=10)
ui.Label("UI Test (omni.kit.ui_test) Settings:", style={"color": 0xFFB7F222, "font_size": 16})
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Label("UI Test Delay (s)")
delay_widget = ui.FloatDrag(min=0, max=1000000)
delay_widget.model.set_value(settings.get_as_float(HUMAN_DELAY_SETTING))
delay_widget.model.add_value_changed_fn(
lambda m: settings.set(HUMAN_DELAY_SETTING, m.get_value_as_float())
)
| 1,912 | Python | 35.094339 | 114 | 0.538703 |
omniverse-code/kit/exts/omni.kit.exec.core/omni/kit/exec/core/unstable/__init__.py | """Python Module Initialization for omni.kit.exec.core"""
from ._omni_kit_exec_core_unstable import *
from .scripts.extension import _PublicExtension
| 151 | Python | 29.399994 | 57 | 0.781457 |
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/extension.py | import omni.ext
from .prompt import PromptManager
class PromptExtension(omni.ext.IExt):
def on_startup(self):
PromptManager.on_startup()
def on_shutdown(self):
PromptManager.on_shutdown()
| 225 | Python | 16.384614 | 37 | 0.671111 |
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/prompt.py | from typing import Callable, List
import carb
import carb.input
import omni
import uuid
class PromptButtonInfo:
def __init__(self, name: str, on_button_clicked_fn: Callable[[], None] = None):
self._name = name
self._on_button_clicked_fn = on_button_clicked_fn
@property
def name(self):
return self._name
@property
def on_button_clicked_fn(self):
return self._on_button_clicked_fn
class PromptManager:
_prompts = set([])
@staticmethod
def on_startup():
pass
@staticmethod
def on_shutdown():
all_prompts = PromptManager._prompts
PromptManager._prompts = set([])
for prompt in all_prompts:
prompt.destroy()
@staticmethod
def query_prompt_by_title(title: str):
for prompt in PromptManager._prompts:
if prompt._title == title:
return prompt
return None
@staticmethod
def add_prompt(prompt):
if prompt not in PromptManager._prompts:
PromptManager._prompts.add(prompt)
@staticmethod
def remove_prompt(prompt):
if prompt in PromptManager._prompts:
PromptManager._prompts.remove(prompt)
@staticmethod
def post_simple_prompt(
title: str, message: str,
ok_button_info: PromptButtonInfo = PromptButtonInfo("OK", None),
cancel_button_info: PromptButtonInfo = None,
middle_button_info: PromptButtonInfo = None,
middle_2_button_info: PromptButtonInfo = None,
on_window_closed_fn: Callable[[], None] = None,
modal=True,
shortcut_keys=True,
standalone=True,
no_title_bar=False,
width=None,
height=None,
callback_addons: List = [],
):
"""When standalone is true, it will hide all other managed prompts in this manager."""
def unwrap_button_info(button_info: PromptButtonInfo):
if button_info:
return button_info.name, button_info.on_button_clicked_fn
else:
return None, None
ok_button_text, ok_button_fn = unwrap_button_info(ok_button_info)
cancel_button_text, cancel_button_fn = unwrap_button_info(cancel_button_info)
middle_button_text, middle_button_fn = unwrap_button_info(middle_button_info)
middle_2_button_text, middle_2_button_fn = unwrap_button_info(middle_2_button_info)
if standalone:
prompts = PromptManager._prompts
PromptManager._prompts = set([])
for prompt in prompts:
prompt.destroy()
prompt = Prompt(
title, message, ok_button_text=ok_button_text,
cancel_button_text=cancel_button_text, middle_button_text=middle_button_text,
middle_2_button_text=middle_2_button_text, ok_button_fn=ok_button_fn,
cancel_button_fn=cancel_button_fn, middle_button_fn=middle_button_fn,
middle_2_button_fn=middle_2_button_fn, modal=modal,
on_closed_fn=on_window_closed_fn, shortcut_keys=shortcut_keys,
no_title_bar=no_title_bar, width=width, height=height, callback_addons=callback_addons
)
prompt.show()
return prompt
class Prompt:
"""Pop up a prompt window that asks the user a simple question with up to four buttons for answers.
Callbacks are executed for each button press, as well as when the window is closed manually.
"""
def __init__(
self,
title,
text,
ok_button_text="OK",
cancel_button_text=None,
middle_button_text=None,
middle_2_button_text=None,
ok_button_fn=None,
cancel_button_fn=None,
middle_button_fn=None,
middle_2_button_fn=None,
modal=False,
on_closed_fn=None,
shortcut_keys=True,
no_title_bar=False,
width=None,
height=None,
callback_addons: List = []
):
"""Initialize the callbacks and window information
Args:
title: Text appearing in the titlebar of the window
text: Text of the question being posed to the user
ok_button_text: Text for the first button
cancel_button_text: Text for the last button
middle_button_text: Text for the middle button
middle_button_2_text: Text for the second middle button
ok_button_fn: Function executed when the first button is pressed
cancel_button_fn: Function executed when the last button is pressed
middle_button_fn: Function executed when the middle button is pressed
middle_2_button_fn: Function executed when the second middle button is pressed
modal: True if the window is modal, shutting down other UI until an answer is received
on_closed_fn: Function executed when the window is closed without hitting a button
shortcut_keys: If it can be confirmed or hidden with shortcut keys like Enter or ESC.
no_title_bar: If it needs to show title bar.
width: The specified width. By default, it will use the computed width.
height: The specified height. By default, it will use the computed height.
callback_addons: Addon widgets which is appended in the prompt window. By default, it is empty
"""
self._title = title
self._text = text
self._cancel_button_text = cancel_button_text
self._cancel_button_fn = cancel_button_fn
self._ok_button_fn = ok_button_fn
self._ok_button_text = ok_button_text
self._middle_button_text = middle_button_text
self._middle_button_fn = middle_button_fn
self._middle_2_button_text = middle_2_button_text
self._middle_2_button_fn = middle_2_button_fn
self._modal = modal
self._on_closed_fn = on_closed_fn
self._button_clicked = False
self._shortcut_keys = shortcut_keys
self._no_title_bar = no_title_bar
self._width = width
self._height = height
self._callback_addons = callback_addons
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._buttons = []
self._build_ui()
def __del__(self):
self.destroy()
def destroy(self):
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
self.hide()
if self._window:
self._window.set_visibility_changed_fn(None)
self._window = None
def __enter__(self):
"""Called on entering a 'with' loop"""
self.show()
return self
def __exit__(self, type, value, trace):
"""Called on exiting a 'with' loop"""
self.hide()
@property
def visible(self):
return self.is_visible()
@visible.setter
def visible(self, value):
if value:
self.show()
else:
self.hide()
def show(self):
"""Make the prompt window visible"""
if not self._window:
self._build_ui()
self._window.visible = True
self._button_clicked = False
PromptManager.add_prompt(self)
def hide(self):
"""Make the prompt window invisible"""
if self._window:
self._window.visible = False
PromptManager.remove_prompt(self)
def is_visible(self):
"""Returns True if the prompt is currently visible"""
return self._window and self._window.visible
def set_text(self, text):
"""Set a new question label"""
self._text_label.text = text
def set_confirm_fn(self, on_ok_button_clicked):
"""Define a new callback for when the first (okay) button is clicked"""
self._ok_button_fn = on_ok_button_clicked
def set_cancel_fn(self, on_cancel_button_clicked):
"""Define a new callback for when the third (cancel) button is clicked"""
self._cancel_button_fn = on_cancel_button_clicked
def set_middle_button_fn(self, on_middle_button_clicked):
"""Define a new callback for when the second (middle) button is clicked"""
self._middle_button_fn = on_middle_button_clicked
def set_middle_2_button_fn(self, on_middle_2_button_clicked):
self._middle_2_button_fn = on_middle_2_button_clicked
def set_on_closed_fn(self, on_on_closed):
"""Define a new callback for when the window is closed without pressing a button"""
self._on_closed_fn = on_on_closed
def _on_visibility_changed(self, new_visibility: bool):
"""Callback executed when visibility of the window closes"""
if not new_visibility:
if not self._button_clicked and self._on_closed_fn is not None:
self._on_closed_fn()
self.hide()
def _on_ok_button_fn(self):
"""Callback executed when the first (okay) button is pressed"""
self._button_clicked = True
self.hide()
if self._ok_button_fn:
self._ok_button_fn()
def _on_cancel_button_fn(self):
"""Callback executed when the third (cancel) button is pressed"""
self._button_clicked = True
self.hide()
if self._cancel_button_fn:
self._cancel_button_fn()
def _on_middle_button_fn(self):
"""Callback executed when the second (middle) button is pressed"""
self._button_clicked = True
self.hide()
if self._middle_button_fn:
self._middle_button_fn()
def _on_closed_fn(self):
"""Callback executed when the window is closed without pressing a button"""
self._button_clicked = True
self.hide()
if self._on_closed_fn:
self._on_closed_fn()
def _on_middle_2_button_fn(self):
self._button_clicked = True
self.hide()
if self._middle_2_button_fn:
self._middle_2_button_fn()
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed or not self._shortcut_keys:
return
func = self._key_functions.get(key)
if func:
func()
def _build_ui(self):
"""Construct the window based on the current parameters"""
num_buttons = 0
if self._ok_button_text:
num_buttons += 1
if self._cancel_button_text:
num_buttons += 1
if self._middle_button_text:
num_buttons += 1
if self._middle_2_button_text:
num_buttons += 1
button_width = 120
spacer_width = 60
if self._width:
window_width = self._width
else:
window_width = button_width * num_buttons + spacer_width * 2
if window_width < 400:
window_width = 400
if self._height:
window_height = self._height
else:
window_height = 0
if self._title:
window_id = self._title
else:
# Generates unique id for this window to make sure all prompts are unique.
window_id = f"##{str(uuid.uuid1())}"
self._window = omni.ui.Window(
window_id, visible=False, height=window_height, width=window_width,
dockPreference=omni.ui.DockPreference.DISABLED,
visibility_changed_fn=self._on_visibility_changed,
)
self._window.flags = (
omni.ui.WINDOW_FLAGS_NO_COLLAPSE | omni.ui.WINDOW_FLAGS_NO_SCROLLBAR |
omni.ui.WINDOW_FLAGS_NO_RESIZE | omni.ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
if self._no_title_bar:
self._window.flags = self._window.flags | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR
if self._modal:
self._window.flags = self._window.flags | omni.ui.WINDOW_FLAGS_MODAL
num_buttons = 0
if self._ok_button_text:
num_buttons += 1
if self._cancel_button_text:
num_buttons += 1
if self._middle_button_text:
num_buttons += 1
if self._middle_2_button_text:
num_buttons += 1
button_width = 120
with self._window.frame:
with omni.ui.VStack(height=0):
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=40)
self._text_label = omni.ui.Label(
self._text, word_wrap=True, width=self._window.width - 80, height=0, name="prompt_text"
)
omni.ui.Spacer(width=40)
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(height=0)
if self._ok_button_text:
ok_button = omni.ui.Button(self._ok_button_text, name="confirm_button", width=button_width, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
self._buttons.append(ok_button)
if self._middle_button_text:
middle_button = omni.ui.Button(self._middle_button_text, name="middle_button", width=button_width, height=0)
middle_button.set_clicked_fn(self._on_middle_button_fn)
self._buttons.append(middle_button)
if self._middle_2_button_text:
middle_2_button = omni.ui.Button(self._middle_2_button_text, name="middle_2_button", width=button_width, height=0)
middle_2_button.set_clicked_fn(self._on_middle_2_button_fn)
self._buttons.append(middle_2_button)
if self._cancel_button_text:
cancel_button = omni.ui.Button(self._cancel_button_text, name="cancel_button", width=button_width, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(cancel_button)
omni.ui.Spacer(height=0)
omni.ui.Spacer(width=0, height=10)
for callback in self._callback_addons:
if callback and callable(callback):
callback()
| 14,437 | Python | 35.004987 | 138 | 0.584748 |
omniverse-code/kit/exts/omni.kit.widget.prompt/omni/kit/widget/prompt/tests/test_prompt.py | import omni.kit.test
import omni.kit.ui_test as ui_test
from functools import partial
from omni.kit.widget.prompt import Prompt, PromptManager, PromptButtonInfo
class TestPrompt(omni.kit.test.AsyncTestCase):
async def setUp(self):
PromptManager.on_shutdown()
async def _wait(self, frames=5):
for i in range(frames):
await omni.kit.app.get_app().next_update_async()
async def test_show_prompt_and_button_clicks(self):
value = ""
def f(text):
nonlocal value
value = text
button_names = ["left", "right", "middle", "middle_2"]
prompt = Prompt(
"title", "information text", *button_names,
ok_button_fn=partial(f, button_names[0]), cancel_button_fn=partial(f, button_names[1]),
middle_button_fn=partial(f, button_names[2]), middle_2_button_fn=partial(f, button_names[3])
)
for button_name in button_names:
prompt.show()
self.assertTrue(prompt.visible)
await ui_test.find("title").focus()
label = ui_test.find("title//Frame/**/Label[*].text=='information text'")
self.assertTrue(label)
button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'")
self.assertTrue(button)
await button.click()
self.assertEqual(value, button_name)
self.assertFalse(prompt.visible)
self.assertFalse(prompt.is_visible())
prompt.destroy()
async def test_set_buttons_fn(self):
value = ""
def f(text):
nonlocal value
value = text
button_names = ["left", "right", "middle", "middle_2"]
prompt = Prompt("title", "test", *button_names)
prompt.set_confirm_fn(partial(f, button_names[0]))
prompt.set_cancel_fn(partial(f, button_names[1]))
prompt.set_middle_button_fn(partial(f, button_names[2]))
prompt.set_middle_2_button_fn(partial(f, button_names[3]))
prompt.set_on_closed_fn(partial(f, "closed"))
for button_name in button_names:
prompt.show()
self.assertTrue(prompt.visible)
await ui_test.find("title").focus()
label = ui_test.find("title//Frame/**/Label[*].text=='test'")
self.assertTrue(label)
button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'")
self.assertTrue(button)
await button.click()
self.assertEqual(value, button_name)
self.assertFalse(prompt.visible)
self.assertFalse(prompt.is_visible())
prompt.show()
prompt.hide()
self.assertEqual(value, "closed")
prompt.destroy()
async def test_hide_prompt(self):
value = ""
def f(text):
nonlocal value
value = text
prompt = Prompt("title", "hide dialog", on_closed_fn=partial(f, "closed"))
prompt.show()
self.assertTrue(prompt.visible)
prompt.hide()
self.assertEqual(value, "closed")
self.assertFalse(prompt.visible)
prompt.show()
self.assertTrue(prompt.visible)
prompt.visible = False
self.assertFalse(prompt.visible)
async def test_set_text(self):
prompt = Prompt("test", "test")
prompt.show()
prompt.set_text("set text")
await ui_test.find("test").focus()
label = ui_test.find("test//Frame/**/Label[*].text=='set text'")
self.assertTrue(label)
async def test_prompt_manager(self):
value = ""
def f(text):
nonlocal value
value = text
n = ["1left", "1right", "1middle", "1middle_2"]
prompt = PromptManager.post_simple_prompt(
"title", "test",
ok_button_info=PromptButtonInfo(n[0], partial(f, n[0])),
cancel_button_info=PromptButtonInfo(n[1], partial(f, n[1])),
middle_button_info=PromptButtonInfo(n[2], partial(f, n[2])),
middle_2_button_info=PromptButtonInfo(n[3], partial(f, n[3])),
on_window_closed_fn=partial(f, "closed")
)
for button_name in n:
prompt.show()
self.assertTrue(prompt.visible)
await ui_test.find("title").focus()
label = ui_test.find("title//Frame/**/Label[*].text=='test'")
self.assertTrue(label)
button = ui_test.find(f"title//Frame/**/Button[*].text=='{button_name}'")
self.assertTrue(button)
await button.click()
self.assertEqual(value, button_name)
self.assertFalse(prompt.visible)
self.assertFalse(prompt.is_visible())
prompt.show()
prompt.hide()
self.assertEqual(value, "closed")
prompt.destroy()
| 4,873 | Python | 34.838235 | 104 | 0.567823 |
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = [
'frame_viewport_prims',
'frame_viewport_selection',
'get_viewport_from_window_name',
'get_active_viewport',
'get_active_viewport_window'
'get_active_viewport_and_window',
'get_viewport_window_camera_path',
'get_viewport_window_camera_string',
'get_active_viewport_camera_path',
'get_active_viewport_camera_string',
'get_num_viewports',
'capture_viewport_to_file',
'capture_viewport_to_buffer',
'post_viewport_message',
'toggle_global_visibility',
'create_drop_helper',
'disable_selection',
'get_ground_plane_info'
]
import asyncio
import carb
from pxr import Gf, Sdf
from typing import Callable, List, Optional, Tuple
_g_is_viewport_next = None
def _is_viewport_next(self):
global _g_is_viewport_next
if _g_is_viewport_next is None:
vp_window_name = carb.settings.get_settings().get('/exts/omni.kit.viewport.window/startup/windowName')
_g_is_viewport_next = vp_window_name and (vp_window_name == 'Viewport')
return _g_is_viewport_next
def _get_default_viewport_window_name(window_name: str = None):
if window_name:
return window_name
return carb.settings.get_settings().get('/exts/omni.kit.viewport.window/startup/windowName') or 'Viewport'
def get_viewport_from_window_name(window_name: str = None):
'''Return the first Viewport that is held inside a specific Window name.'''
window_name = _get_default_viewport_window_name(window_name)
try:
from omni.kit.viewport.window import get_viewport_window_instances
# Get every ViewportWindow, regardless of UsdContext it is attached to
for window in get_viewport_window_instances(None):
if window.title == window_name:
return window.viewport_api
except ImportError:
pass
try:
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
viewport_handle = vp_iface.get_instance(window_name)
if viewport_handle:
vp_window = vp_iface.get_viewport_window(viewport_handle)
if vp_window:
from .legacy_viewport_api import LegacyViewportAPI
return LegacyViewportAPI(vp_iface.get_viewport_window_name(viewport_handle))
except ImportError:
pass
return None
def get_active_viewport_and_window(usd_context_name: str = '', wrap_legacy: bool = True, window_name: str = None):
'''Return the active Viewport for a given UsdContext and the name of the Window it is inside of.'''
default_window_name = _get_default_viewport_window_name(window_name)
try:
from omni.kit.viewport.window import get_viewport_window_instances, ViewportWindow
# If no windowname provided, see if the ViewportWindow already knows what is active
if window_name is None:
active_window = ViewportWindow.active_window
if active_window:
# Have an active Window, need to make sure UsdContext name matches (or passed None to avoid the match)
viewport_api = active_window.viewport_api
if (usd_context_name is None) or (usd_context_name == viewport_api.usd_context_name):
return (viewport_api, active_window)
active_window = None
# Get all ViewportWindows attached the UsdContext with this name
for window in get_viewport_window_instances(usd_context_name):
# If matching by name, check that first ignoring whether focused or not (multiple Windows cannot have same name)
window_title = window.title
if window_name and window_name != window_title:
continue
# If this Window is focused, then return it
if window.focused:
active_window = window
break
# Save the first encountered Window as he fallback 'default' Window
if window_title == default_window_name:
active_window = window
elif active_window is None:
active_window = window
if active_window:
return (active_window.viewport_api, active_window)
except ImportError:
pass
try:
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
instance_list = vp_iface.get_instance_list()
if instance_list:
first_context_match = None
for viewport_handle in vp_iface.get_instance_list():
vp_window = vp_iface.get_viewport_window(viewport_handle)
if not vp_window:
continue
# If matching by name, check that first ignoring whether focused or not (multiple Windows cannot have same name)
window_title = vp_iface.get_viewport_window_name(viewport_handle)
if window_name and window_name != vp_iface.get_viewport_window_name(viewport_handle):
continue
# Filter by UsdContext name, where None means any UsdContext
if (usd_context_name is not None) and (usd_context_name != vp_window.get_usd_context_name()):
continue
if vp_window.is_focused():
first_context_match = viewport_handle
break
elif window_title == default_window_name:
first_context_match = viewport_handle
elif first_context_match is None:
first_context_match = viewport_handle
# If there was a match on UsdContext name (but not focused), return the first one
if first_context_match is not None:
vp_window = vp_iface.get_viewport_window(first_context_match)
if vp_window:
from .legacy_viewport_api import LegacyViewportAPI
window_name = vp_iface.get_viewport_window_name(first_context_match)
viewport_api = LegacyViewportAPI(vp_iface.get_viewport_window_name(first_context_match))
if wrap_legacy:
from .legacy_viewport_window import LegacyViewportWindow
vp_window = LegacyViewportWindow(window_name, viewport_api)
return (viewport_api, vp_window)
except ImportError:
pass
return (None, None)
def get_active_viewport_window(window_name: str = None, wrap_legacy: bool = True, usd_context_name: str = ''):
'''Return the active Viewport for a given UsdContext.'''
return get_active_viewport_and_window(usd_context_name, wrap_legacy, window_name)[1]
def get_active_viewport(usd_context_name: str = ''):
'''Return the active Viewport for a given UsdContext.'''
return get_active_viewport_and_window(usd_context_name, False)[0]
def get_viewport_window_camera_path(window_name: str = None) -> Sdf.Path:
'''Return a Sdf.Path to the camera used by the active Viewport in a named Window.'''
viewport_api = get_viewport_from_window_name(window_name)
return viewport_api.camera_path if viewport_api else None
def get_viewport_window_camera_string(window_name: str = None) -> str:
'''Return a string path to the camera used by the active Viewport in a named Window.'''
viewport_api = get_viewport_from_window_name(window_name)
return viewport_api.camera_path.pathString if viewport_api else None
def get_active_viewport_camera_path(usd_context_name: str = '') -> Sdf.Path:
'''Return a Sdf.Path to the camera used by the active Viewport for a specific UsdContext.'''
viewport_api = get_active_viewport(usd_context_name)
return viewport_api.camera_path if viewport_api else None
def get_active_viewport_camera_string(usd_context_name: str = '') -> str:
'''Return a string path to the camera used by the active Viewport for a specific UsdContext.'''
viewport_api = get_active_viewport(usd_context_name)
return viewport_api.camera_path.pathString if viewport_api else None
def get_available_aovs_for_viewport(viewport_api):
if hasattr(viewport_api, 'legacy_window'):
viewport_handle = viewport_api.frame_info.get('viewport_handle')
asyncio.ensure_future(viewport_api.usd_context.next_frame_async(viewport_handle))
return viewport_api.legacy_window.get_aov_list()
carb.log_error('Available AOVs not implemented')
return []
def add_aov_to_viewport(viewport_api, aov_name: str):
if hasattr(viewport_api, 'legacy_window'):
return viewport_api.legacy_window.add_aov(aov_name)
from pxr import Usd, UsdRender
from omni.usd import editor
stage = viewport_api.stage
render_product_path = viewport_api.render_product_path
with Usd.EditContext(stage, stage.GetSessionLayer()):
render_prod_prim = stage.GetPrimAtPath(render_product_path)
if not render_prod_prim:
raise RuntimeError(f'Invalid renderProduct "{render_product_path}"')
render_var_prim_path = Sdf.Path(f'/Render/Vars/{aov_name}')
render_var_prim = stage.GetPrimAtPath(render_var_prim_path)
if not render_var_prim:
render_var_prim = stage.DefinePrim(render_var_prim_path)
if not render_var_prim:
raise RuntimeError(f'Cannot create renderVar "{render_var_prim_path}"')
render_var_prim.CreateAttribute("sourceName", Sdf.ValueTypeNames.String).Set(aov_name)
render_prod_var_rel = render_prod_prim.GetRelationship('orderedVars')
if not render_prod_var_rel:
render_prod_prim.CreateRelationship('orderedVars')
if not render_prod_var_rel:
raise RuntimeError(f'cannot set orderedVars relationship for renderProduct "{render_product_path}"')
render_prod_var_rel.AddTarget(render_var_prim_path)
editor.set_hide_in_stage_window(render_var_prim, True)
editor.set_no_delete(render_var_prim, True)
return True
def post_viewport_message(viewport_api_or_window, message: str, message_id: str = None):
if hasattr(viewport_api_or_window, 'legacy_window'):
viewport_api_or_window.legacy_window.post_toast(message)
return
if hasattr(viewport_api_or_window, '_post_toast_message'):
viewport_api_or_window._post_toast_message(message, message_id)
return
try:
from omni.kit.viewport.window import get_viewport_window_instances
for window in get_viewport_window_instances(viewport_api_or_window.usd_context_name):
if window.viewport_api.id == viewport_api_or_window.id:
window._post_toast_message(message, message_id)
return
except (ImportError, AttributeError):
pass
class _CaptureHelper:
def __init__(self, legacy_window, is_hdr: bool, file_path: str = None, render_product_path: str = None, on_capture_fn: Callable = None, format_desc: dict = None):
import omni.renderer_capture
self.__future = asyncio.Future()
self.__renderer = omni.renderer_capture.acquire_renderer_capture_interface()
if render_product_path:
self.__future.set_result(True)
self.__renderer.capture_next_frame_using_render_product(viewport_handle=legacy_window.get_id(), filepath=file_path, render_product=render_product_path)
return
self.__is_hdr = is_hdr
self.__legacy_window = legacy_window
self.__file_path = file_path
self.__on_capture_fn = on_capture_fn
self.__format_desc = format_desc
event_stream = legacy_window.get_ui_draw_event_stream()
self.__capture_sub = event_stream.create_subscription_to_pop(self.capture_function, name='omni.kit.viewport.utility.capture_viewport')
def capture_function(self, *args):
self.__capture_sub = None
legacy_window, self.__legacy_window = self.__legacy_window, None
renderer, self.__renderer = self.__renderer, None
if self.__is_hdr:
viewport_rp_resource = legacy_window.get_drawable_hdr_resource()
else:
viewport_rp_resource = legacy_window.get_drawable_ldr_resource()
if self.__on_capture_fn:
def _interecept_capture(*args, **kwargs):
try:
self.__on_capture_fn(*args, **kwargs)
finally:
if not self.__future.done():
self.__future.set_result(True)
renderer.capture_next_frame_rp_resource_callback(_interecept_capture, resource=viewport_rp_resource)
elif self.__file_path:
if not self.__future.done():
self.__future.set_result(True)
if self.__format_desc:
if hasattr(renderer, 'capture_next_frame_rp_resource_to_file'):
renderer.capture_next_frame_rp_resource_to_file(filepath=self.__file_path,
resource=viewport_rp_resource,
format_desc=self.__format_desc)
return
carb.log_error('Format description provided to capture, but not honored')
renderer.capture_next_frame_rp_resource(filepath=self.__file_path, resource=viewport_rp_resource)
async def wait_for_result(self, completion_frames: int = 2):
await self.__future
import omni.kit.app
app = omni.kit.app.get_app()
while completion_frames:
await app.next_update_async()
completion_frames = completion_frames - 1
return self.__future.result()
def capture_viewport_to_buffer(viewport_api, on_capture_fn: Callable, is_hdr: bool = False):
'''Capture the provided viewport and send it to a callback.'''
if hasattr(viewport_api, 'legacy_window'):
return _CaptureHelper(viewport_api.legacy_window, is_hdr=is_hdr, on_capture_fn=on_capture_fn)
from omni.kit.widget.viewport.capture import ByteCapture
return viewport_api.schedule_capture(ByteCapture(on_capture_fn, aov_name='HdrColor' if is_hdr else 'LdrColor'))
def capture_viewport_to_file(viewport_api, file_path: str = None, is_hdr: bool = False, render_product_path: str = None, format_desc: dict = None):
'''Capture the provided viewport to a file.'''
file_path = str(file_path)
if hasattr(viewport_api, 'legacy_window'):
return _CaptureHelper(viewport_api.legacy_window, is_hdr=is_hdr, file_path=file_path,
render_product_path=render_product_path, format_desc=format_desc)
from omni.kit.widget.viewport.capture import MultiAOVFileCapture
class HdrCaptureHelper(MultiAOVFileCapture):
def __init__(self, file_path: str, is_hdr: bool, format_desc: dict = None):
super().__init__(['HdrColor' if is_hdr else 'LdrColor'], [file_path])
# Setup RenderProduct for Hdr
def __del__(self):
# Setdown RenderProduct for Hdr
pass
def capture_aov(self, file_path, aov):
if render_product_path:
self.save_product_to_file(file_path, render_product_path)
else:
self.save_aov_to_file(file_path, aov, format_desc=format_desc)
return viewport_api.schedule_capture(HdrCaptureHelper(file_path, is_hdr))
def get_num_viewports(usd_context_name: str = None):
num_viewports = 0
try:
from omni.kit.viewport.window import get_viewport_window_instances
num_viewports += sum(1 for _ in get_viewport_window_instances(usd_context_name))
except ImportError:
pass
try:
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
for viewport_handle in vp_iface.get_instance_list():
if usd_context_name and (usd_context_name != vp_iface.get_viewport_window(viewport_handle).get_usd_context_name()):
continue
num_viewports += 1
except ImportError:
pass
return num_viewports
def create_viewport_window(name: str = None, usd_context_name: str = '', width: int = 1280, height: int = 720, position_x: int = 0, position_y: int = 0, camera_path: Sdf.Path = None, **kwargs):
window = None
try:
from omni.kit.viewport.window import get_viewport_window_instances, ViewportWindow
if name is None:
name = f"Viewport {get_num_viewports()}"
window = ViewportWindow(name, usd_context_name, width=width, height=height, **kwargs)
return window
except ImportError:
pass
if window is None:
try:
import omni.kit.viewport_legacy as vp_legacy
from .legacy_viewport_window import LegacyViewportWindow
vp_iface = vp_legacy.get_viewport_interface()
vp_handle = vp_iface.create_instance()
assigned_name = vp_iface.get_viewport_window_name(vp_handle)
if name and (name != assigned_name):
carb.log_warn('omni.kit.viewport_legacy does not support explicit Window names, using assigned name "{assigned_name}"')
window = LegacyViewportWindow(assigned_name, **kwargs)
window.width = width
window.height = height
except ImportError:
pass
if window:
window.setPosition(position_x, position_y)
if camera_path:
window.viewport_api.camera_path = camera_path
return window
class ViewportPrimReferencePoint:
BOUND_BOX_CENTER = 0
BOUND_BOX_LEFT = 1
BOUND_BOX_RIGHT = 2
BOUND_BOX_TOP = 3
BOUND_BOX_BOTTOM = 4
def get_ui_position_for_prim(viewport_window, prim_path: str, alignment: ViewportPrimReferencePoint = ViewportPrimReferencePoint.BOUND_BOX_CENTER, force_legacy_api: bool = False):
if isinstance(viewport_window, str):
window_name = str(viewport_window)
viewport_window = get_active_viewport_window(window_name=window_name)
if viewport_window is None:
carb.log_error('No ViewportWindow found with name "{window_name}"')
return (0, 0), False
# XXX: omni.ui constants needed
import omni.ui
dpi = omni.ui.Workspace.get_dpi_scale()
if dpi <= 0.0:
dpi = 1
# XXX: kit default dock splitter size (4)
dock_splitter_size = 4 * dpi
tab_bar_height = 0
if viewport_window.dock_tab_bar_visible or not (viewport_window.flags & omni.ui.WINDOW_FLAGS_NO_TITLE_BAR):
tab_bar_height = 22 * dpi
# Force legacy Viewport code path if requested
if force_legacy_api and hasattr(viewport_window, 'legacy_window'):
import omni.ui
import omni.kit.viewport_legacy as vp_legacy
legacy_window = viewport_window.legacy_window
alignment = {
ViewportPrimReferencePoint.BOUND_BOX_LEFT: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_LEFT,
ViewportPrimReferencePoint.BOUND_BOX_RIGHT: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_RIGHT,
ViewportPrimReferencePoint.BOUND_BOX_TOP: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_TOP,
ViewportPrimReferencePoint.BOUND_BOX_BOTTOM: vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_BOTTOM,
}.get(alignment, vp_legacy.ViewportPrimReferencePoint.BOUND_BOX_CENTER)
success, x, y, z = legacy_window.get_prim_clipping_pos(str(prim_path), alignment)
if not success:
return (0, 0), False
# Changing xy to match the window coord system.
x = (x + 1.0) / 2.0 # x to [0, 1]
y = 1 - (y + 1.0) / 2.0 # y to [0, 1] and reverse its direction.
min_x, min_y, max_x, max_y = legacy_window.get_viewport_rect()
prim_window_pos_x = (max_x - min_x) * x + min_x - dock_splitter_size
prim_window_pos_y = (max_y - min_y) * y + min_y - tab_bar_height - dock_splitter_size
else:
from pxr import UsdGeom, Gf
viewport_api = viewport_window.viewport_api
usd_context = viewport_window.viewport_api.usd_context
stage = usd_context.get_stage()
usd_prim = stage.GetPrimAtPath(prim_path) if stage else False
if usd_prim:
xformable_prim = UsdGeom.Xformable(usd_prim)
else:
xformable_prim = None
if (not stage) or (not xformable_prim):
return (0, 0), False
# Get bounding box from prim
aabb_min, aabb_max = usd_context.compute_path_world_bounding_box(str(prim_path))
gf_range = Gf.Range3d(Gf.Vec3d(aabb_min[0], aabb_min[1], aabb_min[2]), Gf.Vec3d(aabb_max[0], aabb_max[1], aabb_max[2]))
if gf_range.IsEmpty():
# May be empty (UsdGeom.Xform for example), so build a scene-scaled constant box
world_units = UsdGeom.GetStageMetersPerUnit(stage)
if Gf.IsClose(world_units, 0.0, 1e-6):
world_units = 0.01
# XXX: compute_path_world_transform is identity in this case
if False:
world_xform = Gf.Matrix4d(*usd_context.compute_path_world_transform(str(prim_path)))
else:
import omni.timeline
time = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond()
world_xform = xformable_prim.ComputeLocalToWorldTransform(time)
ref_position = world_xform.ExtractTranslation()
extent = Gf.Vec3d(0.2 / world_units) # 20cm by default
gf_range.SetMin(ref_position - extent)
gf_range.SetMax(ref_position + extent)
# Computes the extent in clipping pos
mvp = viewport_api.world_to_ndc
min_x, min_y, min_z = 2.0, 2.0, 2.0
max_x, max_y, max_z = -2.0, -2.0, -2.0
for i in range(8):
corner = gf_range.GetCorner(i)
pos = mvp.Transform(corner)
min_x = min(min_x, pos[0])
min_y = min(min_y, pos[1])
min_z = min(min_z, pos[2])
max_x = max(max_x, pos[0])
max_y = max(max_y, pos[1])
max_z = max(max_z, pos[2])
min_point = Gf.Vec3d(min_x, min_y, min_z)
max_point = Gf.Vec3d(max_x, max_y, max_z)
mid_point = (min_point + max_point) / 2
# Map to reference point in screen space
if alignment == ViewportPrimReferencePoint.BOUND_BOX_LEFT:
ndc_pos = mid_point - Gf.Vec3d((max_x - min_x) / 2, 0, 0)
elif alignment == ViewportPrimReferencePoint.BOUND_BOX_RIGHT:
ndc_pos = mid_point + Gf.Vec3d((max_x - min_x) / 2, 0, 0)
elif alignment == ViewportPrimReferencePoint.BOUND_BOX_TOP:
ndc_pos = mid_point + Gf.Vec3d(0, (max_y - min_y) / 2, 0)
elif alignment == ViewportPrimReferencePoint.BOUND_BOX_BOTTOM:
ndc_pos = mid_point - Gf.Vec3d(0, (max_y - min_y) / 2, 0)
else:
ndc_pos = mid_point
# Make sure its not clipped
if (ndc_pos[2] < 0) or (ndc_pos[0] < -1) or (ndc_pos[0] > 1) or (ndc_pos[1] < -1) or (ndc_pos[1] > 1):
return (0, 0), False
'''
XXX: Simpler world calculation
world_pos = gf_range.GetMidpoint()
dir_sel = (0, 1)
up_axis = UsdGeom.GetStageUpAxis(stage)
if up_axis == UsdGeom.Tokens.z:
dir_sel = (0, 2)
if up_axis == UsdGeom.Tokens.x:
dir_sel = (2, 1)
if alignment == ViewportPrimReferencePoint.BOUND_BOX_LEFT:
world_pos[dir_sel[0]] = gf_range.GetMin()[dir_sel[0]]
elif alignment == ViewportPrimReferencePoint.BOUND_BOX_RIGHT:
world_pos[dir_sel[0]] = gf_range.GetMax()[dir_sel[0]]
elif alignment == ViewportPrimReferencePoint.BOUND_BOX_TOP:
world_pos[dir_sel[1]] = gf_range.GetMax()[dir_sel[1]]
elif alignment == ViewportPrimReferencePoint.BOUND_BOX_BOTTOM:
world_pos[dir_sel[1]] = gf_range.GetMin()[dir_sel[1]]
ndc_pos = viewport_api.world_to_ndc.Transform(world_pos)
'''
x = (ndc_pos[0] + 1.0) / 2.0 # x to [0, 1]
y = 1 - (ndc_pos[1] + 1.0) / 2.0 # y to [0, 1] and reverse its direction.
frame = viewport_window.frame
prim_window_pos_x = dpi * (frame.screen_position_x + x * frame.computed_width) - dock_splitter_size
prim_window_pos_y = dpi * (frame.screen_position_y + y * frame.computed_height) - tab_bar_height - dock_splitter_size
return (prim_window_pos_x, prim_window_pos_y), True
def frame_viewport_prims(viewport_api=None, prims: List[str] = None):
if not prims:
return False
return __frame_viewport_objects(viewport_api, prims=prims, force_legacy_api=False)
def frame_viewport_selection(viewport_api=None, force_legacy_api: bool = False):
return __frame_viewport_objects(viewport_api, prims=None, force_legacy_api=force_legacy_api)
def __frame_viewport_objects(viewport_api=None, prims: Optional[List[str]] = None, force_legacy_api: bool = False):
if not viewport_api:
viewport_api = get_active_viewport()
if not viewport_api:
return False
if force_legacy_api and hasattr(viewport_api, "legacy_window"):
viewport_api.legacy_window.focus_on_selected()
return
# This is new CODE
if prims is None:
# Get current selection
prims = viewport_api.usd_context.get_selection().get_selected_prim_paths()
# Pass None to underlying command to signal "frame all" if selection is empty
prims = prims if prims else None
stage = viewport_api.stage
cam_path = viewport_api.camera_path
if not stage or not cam_path:
return False
cam_prim = stage.GetPrimAtPath(cam_path)
if not cam_prim:
return False
import omni.kit.undo
import omni.kit.commands
from pxr import UsdGeom
look_through = None
# Loop over all targets (should really be only one) and see if we can get a valid UsdGeom.Imageable
for target in cam_prim.GetRelationship('omni:kit:viewport:lookThrough:target').GetForwardedTargets():
target_prim = stage.GetPrimAtPath(target)
if not target_prim:
continue
if UsdGeom.Imageable(target_prim):
look_through = target_prim
break
try:
omni.kit.undo.begin_group()
resolution = viewport_api.resolution
omni.kit.commands.execute(
'FramePrimsCommand',
prim_to_move=cam_path if not look_through else look_through.GetPath(),
prims_to_frame=prims,
time_code=viewport_api.time,
usd_context_name=viewport_api.usd_context_name,
aspect_ratio=resolution[0] / resolution[1]
)
finally:
omni.kit.undo.end_group()
return True
def toggle_global_visibility(force_legacy_api: bool = False):
# Forward to omni.kit.viewport.actions and propogate an errors so caller should update code
carb.log_warn("omni.kit.viewport.utility.toggle_global_visibility is deprecated, use omni.kit.viewport.actions.toggle_global_visibility")
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.get_action("omni.kit.viewport.actions", "toggle_global_visibility").execute()
async def next_viewport_frame_async(viewport, n_frames: int = 0):
"""
Waits until frames have been delivered to the Viewport.
Args:
viewport: the Viewport to wait for a frame on.
n_frames: the number of rendered frames to wait for.
"""
import omni.kit.app
app = omni.kit.app.get_app()
# Make sure at least one frame has been delivered
viewport_handle = viewport.frame_info.get('viewport_handle')
while viewport_handle is None:
await app.next_update_async()
viewport_handle = viewport.frame_info.get('viewport_handle')
# Now wait for any additional frames
usd_context = viewport.usd_context
while n_frames:
await usd_context.next_frame_async(viewport_handle)
n_frames = n_frames - 1
def create_drop_helper(*args, **kwargs):
try:
from omni.kit.viewport.window.dragdrop.legacy import create_drop_helper
return create_drop_helper(*args, **kwargs)
except (ImportError, ModuleNotFoundError):
try:
import omni.kit.viewport_legacy as vp_legacy
return vp_legacy.get_viewport_interface().create_drop_helper(*args, **kwargs)
except (ImportError, ModuleNotFoundError):
pass
class _DisableViewportWindowLayer:
def __init__(self, viewport_or_window, layers_and_categories):
self.__layers = []
# Find the omni.ui.Window for this Viewport to disable selection manipulator
viewport_window = None
from omni.kit.viewport.window import ViewportWindow, get_viewport_window_instances
if not isinstance(viewport_or_window, ViewportWindow):
viewport_id = viewport_or_window.id
for window_instance in get_viewport_window_instances(viewport_or_window.usd_context_name):
viewport_window_viewport = window_instance.viewport_api
if viewport_window_viewport.id == viewport_id:
viewport_window = window_instance
break
else:
viewport_window = viewport_or_window
if viewport_window:
for layer, category in layers_and_categories:
found_layer = viewport_window._find_viewport_layer(layer, category)
if found_layer:
self.__layers.append((found_layer, found_layer.visible))
found_layer.visible = False
def __del__(self):
for layer, visible in self.__layers:
layer.visible = visible
self.__layers = tuple()
def disable_selection(viewport_or_window, disable_click: bool = True):
'''Disable selection rect and possible the single click selection on a Viewport or ViewportWindow.
Returns an object that resets selection when it goes out of scope.'''
# First check if the Viewport is a legacy Viewport
from .legacy_viewport_window import LegacyViewportWindow
legacy_window = None
if hasattr(viewport_or_window, 'legacy_window'):
legacy_window = viewport_or_window.legacy_window
elif isinstance(viewport_or_window, LegacyViewportWindow):
legacy_window = viewport_or_window.legacy_window
if legacy_window:
class LegacySelectionState:
def __init__(self, viewport_window, disable_click):
self.__viewport_window = viewport_window
self.__restore_picking = viewport_window.is_enabled_picking()
if disable_click:
self.__viewport_window.set_enabled_picking(False)
self.__viewport_window.disable_selection_rect(True)
def __del__(self):
self.__viewport_window.set_enabled_picking(self.__restore_picking)
return LegacySelectionState(legacy_window, disable_click)
disable_items = [('Selection', 'manipulator')]
if disable_click:
disable_items.append(('ObjectClick', 'manipulator'))
return _DisableViewportWindowLayer(viewport_or_window, disable_items)
def disable_context_menu(viewport_or_window=None):
'''Disable context menu on a Viewport or ViewportWindow.
Returns an object that resets context menu visibility when it goes out of scope.'''
if viewport_or_window:
# Check if the Viewport is a legacy Viewport, s can only operate on all Viewportwindows in that case
from .legacy_viewport_window import LegacyViewportWindow
if hasattr(viewport_or_window, 'legacy_window') or isinstance(viewport_or_window, LegacyViewportWindow):
carb.log_warn("Cannot disable context menu on an individual Viewport, disabling it for all")
viewport_or_window = None
if viewport_or_window is None:
class _DisableAllContextMenus:
def __init__(self):
# When setting is initially unset, then context menu is enabled
self.__settings = carb.settings.get_settings()
enabled = self.__settings.get('/exts/omni.kit.window.viewport/showContextMenu')
self.__settings.set('/exts/omni.kit.window.viewport/showContextMenu', False)
self.__restore = enabled if (enabled is not None) else True
def __del__(self):
self.__settings.set('/exts/omni.kit.window.viewport/showContextMenu', self.__restore)
return _DisableAllContextMenus()
return _DisableViewportWindowLayer(viewport_or_window, [('ContextMenu', 'manipulator')])
def get_ground_plane_info(viewport, ortho_special: bool = True) -> Tuple[Gf.Vec3d, List[str]]:
"""For a given Viewport returns a tuple representing the ground plane.
@param viewport: ViewportAPI to use for ground plane info
@param ortho_special: bool Use an alternate ground plane for orthographic cameras that are looking down a single axis
@return: A tuple of type (normal: Gf.Vec3d, planes: List[str]), where planes is a list of axis' occupied (x, y, z)
"""
stage = viewport.stage
cam_path = viewport.camera_path
from pxr import UsdGeom
up_axis = UsdGeom.GetStageUpAxis(stage) if stage else UsdGeom.Tokens.y
if up_axis == UsdGeom.Tokens.y:
normal = Gf.Vec3d.YAxis()
planes = ['x', 'z']
elif up_axis == UsdGeom.Tokens.z:
normal = Gf.Vec3d.ZAxis()
planes = ['x', 'y']
else:
normal = Gf.Vec3d.XAxis()
planes = ['y', 'z']
if ortho_special:
cam_prim = stage.GetPrimAtPath(cam_path) if stage else None
if cam_prim:
usd_camera = UsdGeom.Camera(cam_prim)
if usd_camera and usd_camera.GetProjectionAttr().Get(viewport.time) == UsdGeom.Tokens.orthographic:
orthoEpsilon = 0.0001
viewNormal = viewport.transform.TransformDir(Gf.Vec3d(0, 0, -1))
if Gf.IsClose(abs(viewNormal[1]), 1.0, orthoEpsilon):
normal = Gf.Vec3d.YAxis()
planes = ['x', 'z']
elif Gf.IsClose(abs(viewNormal[2]), 1.0, orthoEpsilon):
normal = Gf.Vec3d.ZAxis()
planes = ['x', 'y']
elif Gf.IsClose(abs(viewNormal[0]), 1.0, orthoEpsilon):
normal = Gf.Vec3d.XAxis()
planes = ['y', 'z']
return normal, planes
| 34,909 | Python | 42.528678 | 193 | 0.63783 |
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/legacy_viewport_window.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['LegacyViewportWindow']
import omni.ui
import carb
import weakref
# Wrap a legacy viewport Window in an object that poses as a new omni.kit.viewport.window.ViewportWindow (omni.ui.Window) class
class LegacyViewportWindow(omni.ui.Window):
def __init__(self, window_name: str, viewport_api = None, **kwargs):
kwargs.update({
'window_flags': omni.ui.WINDOW_FLAGS_NO_SCROLLBAR | omni.ui.WINDOW_FLAGS_NO_TITLE_BAR | omni.ui.WINDOW_FLAGS_NO_RESIZE
})
super().__init__(window_name, **kwargs)
self.__z_stack = None
with self.frame:
self.__z_stack = omni.ui.ZStack()
self.__window_name = window_name
if not viewport_api:
from .legacy_viewport_api import LegacyViewportAPI
viewport_api = LegacyViewportAPI(window_name)
self.__viewport_api = viewport_api
self.__added_frames = {}
@property
def name(self):
return self.__window_name
@property
def viewport_api(self):
return weakref.proxy(self.__viewport_api)
def get_frame(self, name: str):
frame = self.__added_frames.get(name)
if frame is None:
with self.__z_stack:
frame = omni.ui.Frame(horizontal_clipping=True)
self.__added_frames[name] = frame
return frame
@property
def legacy_window(self):
return self.__get_legacy_window()
@property
def width(self):
return super().width
@property
def height(self):
return super().height
@width.setter
def width(self, width: float):
width = int(width)
legacy_window = self.legacy_window
if legacy_window:
legacy_window.set_window_size(width, int(self.height))
super(LegacyViewportWindow, self.__class__).width.fset(self, width)
@height.setter
def height(self, height: float):
height = int(height)
legacy_window = self.legacy_window
if legacy_window:
legacy_window.set_window_size(int(self.width), height)
super(LegacyViewportWindow, self.__class__).height.fset(self, height)
@property
def position_x(self):
pos_x = super().position_x
# Workaround omni.ui reporting massive position_y unless laid out ?
return pos_x if pos_x != 340282346638528859811704183484516925440 else 0
@property
def position_y(self):
pos_y = super().position_y
# Workaround omni.ui reporting massive position_y unless laid out ?
return pos_y if pos_y != 340282346638528859811704183484516925440 else 0
@position_x.setter
def position_x(self, position_x: float):
position_x = int(position_x)
legacy_window = self.legacy_window
if legacy_window:
legacy_window.set_window_pos(position_x, int(self.position_y))
super(LegacyViewportWindow, self.__class__).position_x.fset(self, position_x)
@position_y.setter
def position_y(self, position_y: float):
position_y = int(position_y)
legacy_window = self.legacy_window
if legacy_window:
legacy_window.set_window_pos(int(self.position_x), position_y)
super(LegacyViewportWindow, self.__class__).position_y.fset(self, position_y)
def setPosition(self, x: float, y: float):
return self.set_position(x, y)
def set_position(self, x: float, y: float):
x, y = int(x), int(y)
legacy_window = self.legacy_window
if legacy_window:
legacy_window.set_window_pos(x, y)
super().setPosition(x, y)
@property
def visible(self):
legacy_window = self.legacy_window
if legacy_window:
return legacy_window.is_visible()
return super().visible
@visible.setter
def visible(self, visible: bool):
visible = bool(visible)
legacy_window = self.legacy_window
if legacy_window:
legacy_window.set_visible(visible)
super(LegacyViewportWindow, self.__class__).visible.fset(self, visible)
def __del__(self):
self.destroy()
def destroy(self):
self.__viewport_api = None
if self.__z_stack:
self.__z_stack.clear()
self.__z_stack.destroy()
self.__z_stack = None
if self.__added_frames:
for name, frame in self.__added_frames.items():
try:
frame.destroy()
except Exception:
import traceback
carb.log_error(f"Error destroying {self.__window_name}. Traceback:\n{traceback.format_exc()}")
self.__added_frames = None
super().destroy()
def _post_toast_message(self, message: str, message_id: str = None):
legacy_window = self.legacy_window
if legacy_window:
return legacy_window.post_toast(message)
def __get_legacy_window(self):
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
viewport_handle = vp_iface.get_instance(self.__window_name)
return vp_iface.get_viewport_window(viewport_handle)
| 5,623 | Python | 33.716049 | 130 | 0.624755 |
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/camera_state.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['ViewportCameraState']
from pxr import Gf, Sdf, Usd, UsdGeom
class ViewportCameraState:
def __init__(self, camera_path: str = None, viewport = None, time: Usd.TimeCode = None, force_legacy_api: bool = False):
if viewport is None:
from omni.kit.viewport.utility import get_active_viewport
viewport = get_active_viewport()
if viewport is None:
raise RuntimeError('No default or provided Viewport')
self.__viewport_api = viewport
self.__camera_path = str(camera_path if camera_path else viewport.camera_path)
self.__time = Usd.TimeCode.Default() if time is None else time
self.__legacy_window = viewport.legacy_window if (force_legacy_api and hasattr(viewport, 'legacy_window')) else None
def get_world_camera_up(self, stage) -> Gf.Vec3d:
up_axis = UsdGeom.GetStageUpAxis(stage) if stage else UsdGeom.Tokens.y
if up_axis == UsdGeom.Tokens.y:
return Gf.Vec3d(0, 1, 0)
if up_axis == UsdGeom.Tokens.z:
return Gf.Vec3d(0, 0, 1)
if up_axis == UsdGeom.Tokens.x:
return Gf.Vec3d(1, 0, 0)
return Gf.Vec3d(0, 1, 0)
@property
def usd_camera(self) -> Usd.Prim:
camera_prim = self.__viewport_api.stage.GetPrimAtPath(self.__camera_path)
usd_camera = UsdGeom.Camera(camera_prim) if camera_prim else None
if usd_camera:
return usd_camera
raise RuntimeError(f'"{self.__camera_path}" is not a valid Usd.Prim or UsdGeom.Camera')
@property
def position_world(self):
if self.__legacy_window:
success, x, y, z = self.__legacy_window.get_camera_position(self.__camera_path)
if success:
return Gf.Vec3d(x, y, z)
return self.usd_camera.ComputeLocalToWorldTransform(self.__time).Transform(Gf.Vec3d(0, 0, 0))
@property
def target_world(self):
if self.__legacy_window:
success, x, y, z = self.__legacy_window.get_camera_target(self.__camera_path)
if success:
return Gf.Vec3d(x, y, z)
local_coi = self.usd_camera.GetPrim().GetAttribute('omni:kit:centerOfInterest').Get(self.__time)
return self.usd_camera.ComputeLocalToWorldTransform(self.__time).Transform(local_coi)
def set_position_world(self, world_position: Gf.Vec3d, rotate: bool):
if self.__legacy_window:
self.__legacy_window.set_camera_position(self.__camera_path, world_position[0], world_position[1], world_position[2], rotate)
return
usd_camera = self.usd_camera
world_xform = usd_camera.ComputeLocalToWorldTransform(self.__time)
parent_xform = usd_camera.ComputeParentToWorldTransform(self.__time)
iparent_xform = parent_xform.GetInverse()
initial_local_xform = world_xform * iparent_xform
pos_in_parent = iparent_xform.Transform(world_position)
if rotate:
cam_prim = usd_camera.GetPrim()
coi_attr = cam_prim.GetAttribute('omni:kit:centerOfInterest')
prev_local_coi = coi_attr.Get(self.__time)
coi_in_parent = iparent_xform.Transform(world_xform.Transform(prev_local_coi))
cam_up = self.get_world_camera_up(cam_prim.GetStage())
new_local_transform = Gf.Matrix4d(1).SetLookAt(pos_in_parent, coi_in_parent, cam_up).GetInverse()
else:
coi_attr, prev_local_coi = None, None
new_local_transform = Gf.Matrix4d(initial_local_xform)
new_local_transform = new_local_transform.SetTranslateOnly(pos_in_parent)
import omni.kit.commands
omni.kit.commands.create(
'TransformPrimCommand',
path=self.__camera_path,
new_transform_matrix=new_local_transform,
old_transform_matrix=initial_local_xform,
time_code=self.__time,
usd_context_name=self.__viewport_api.usd_context_name
).do()
if coi_attr and prev_local_coi:
prev_world_coi = world_xform.Transform(prev_local_coi)
new_local_coi = (new_local_transform * parent_xform).GetInverse().Transform(prev_world_coi)
omni.kit.commands.create(
'ChangePropertyCommand',
prop_path=coi_attr.GetPath(),
value=new_local_coi,
prev=prev_local_coi,
timecode=self.__time,
usd_context_name=self.__viewport_api.usd_context_name,
type_to_create_if_not_exist=Sdf.ValueTypeNames.Vector3d
).do()
def set_target_world(self, world_target: Gf.Vec3d, rotate: bool):
if self.__legacy_window:
self.__legacy_window.set_camera_target(self.__camera_path, world_target[0], world_target[1], world_target[2], rotate)
return
usd_camera = self.usd_camera
world_xform = usd_camera.ComputeLocalToWorldTransform(self.__time)
parent_xform = usd_camera.ComputeParentToWorldTransform(self.__time)
iparent_xform = parent_xform.GetInverse()
initial_local_xform = world_xform * iparent_xform
cam_prim = usd_camera.GetPrim()
coi_attr = cam_prim.GetAttribute('omni:kit:centerOfInterest')
prev_local_coi = coi_attr.Get(self.__time)
pos_in_parent = iparent_xform.Transform(initial_local_xform.Transform(Gf.Vec3d(0, 0, 0)))
if rotate:
# Rotate camera to look at new target, leaving it where it is
cam_up = self.get_world_camera_up(cam_prim.GetStage())
coi_in_parent = iparent_xform.Transform(world_target)
new_local_transform = Gf.Matrix4d(1).SetLookAt(pos_in_parent, coi_in_parent, cam_up).GetInverse()
new_local_coi = (new_local_transform * parent_xform).GetInverse().Transform(world_target)
else:
# Camera keeps orientation and distance relative to target
# Calculate movement of center-of-interest in parent's space
target_move = iparent_xform.Transform(world_target) - iparent_xform.Transform(world_xform.Transform(prev_local_coi))
# Copy the camera's local transform
new_local_transform = Gf.Matrix4d(initial_local_xform)
# And move it by the delta
new_local_transform.SetTranslateOnly(pos_in_parent + target_move)
import omni.kit.commands
if rotate:
omni.kit.commands.create(
'ChangePropertyCommand',
prop_path=coi_attr.GetPath(),
value=new_local_coi,
prev=prev_local_coi,
timecode=self.__time,
usd_context_name=self.__viewport_api.usd_context_name,
type_to_create_if_not_exist=Sdf.ValueTypeNames.Vector3d
).do()
omni.kit.commands.create(
'TransformPrimCommand',
path=self.__camera_path,
new_transform_matrix=new_local_transform,
old_transform_matrix=initial_local_xform,
time_code=self.__time,
usd_context_name=self.__viewport_api.usd_context_name
).do()
| 7,593 | Python | 45.588957 | 137 | 0.629 |
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/legacy_viewport_api.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ['LegacyViewportAPI']
import carb
import omni.ui
import omni.usd
import omni.timeline
import omni.kit.app
from pxr import Gf, Sdf, Usd, UsdGeom, CameraUtil
from typing import Callable, List, Tuple, Sequence
# Wrap a legacy viewport Window in an object that poses as a new ViewportAPI
class LegacyViewportAPI:
def __init__(self, window_name: str):
self.__window_name = window_name
self.__settings = carb.settings.get_settings()
# All legacy Viewports are locked to timeline time
self.__timeline = None
self.__saved_resolution = None
self.__fill_frame = None
@property
def camera_path(self) -> Sdf.Path:
'''Return an Sdf.Path to the active rendering camera'''
path_str = self.legacy_window.get_active_camera()
return Sdf.Path(path_str) if path_str else Sdf.Path()
@camera_path.setter
def camera_path(self, camera_path: Sdf.Path):
'''Set the active rendering camera from an Sdf.Path'''
self.legacy_window.set_active_camera(str(camera_path))
@property
def render_product_path(self) -> str:
'''Return a string to the UsdRender.Product used by the Viewport'''
return self.legacy_window.get_render_product_path()
@render_product_path.setter
def render_product_path(self, product_path: str):
'''Set the UsdRender.Product used by the Viewport with a string'''
self.legacy_window.set_render_product_path(str(product_path))
@property
def resolution(self) -> Tuple[float]:
'''Return a tuple of (resolution_x, resolution_y) this Viewport is rendering at.'''
# Legacy Viewport applies scale internally, so returned value accounts for scale factor.
return self.legacy_window.get_texture_resolution()
@resolution.setter
def resolution(self, value: Tuple[float]):
'''Set the resolution to render with (resolution_x, resolution_y).'''
# Legacy Viewport applies scale internally based on single carb setting, so just use that
self.legacy_window.set_texture_resolution(value[0], value[1])
@property
def resolution_scale(self) -> float:
'''Get the scaling factor for the Viewport's render resolution.'''
# Legacy Viewport applies scale internally based on single carb setting, so just use that or fallback to 1
return self.__settings.get("/app/renderer/resolution/multiplier") or 1.0
@resolution_scale.setter
def resolution_scale(self, value: float):
'''Set the scaling factor for the Viewport's render resolution.'''
value = float(value)
if value <= 0:
raise ValueError("Viewport resolution scale must be greater than 0.")
self.__settings.set("/app/renderer/resolution/multiplier", value)
@property
def full_resolution(self) -> Tuple[float]:
'''Return a tuple of the full (full_resolution_x, full_resolution_y) this Viewport is rendering at, not accounting for scale.'''
# Legacy Viewport applies scale internally, so undo any scaling factor
resolution = self.resolution
resolution_scale = self.resolution_scale
return (resolution[0] / resolution_scale, resolution[1] / resolution_scale)
# Legacy methods that we also support
def get_active_camera(self) -> Sdf.Path:
'''Return an Sdf.Path to the active rendering camera'''
return self.camera_path
def set_active_camera(self, camera_path: Sdf.Path):
'''Set the active rendering camera from an Sdf.Path'''
self.camera_path = camera_path
def get_render_product_path(self) -> str:
'''Return a string to the UsdRender.Product used by the Viewport'''
return self.render_product_path
def set_render_product_path(self, product_path: str):
'''Set the UsdRender.Product used by the Viewport with a string'''
self.render_product_path = product_path
def get_texture_resolution(self) -> Tuple[float]:
'''Return a tuple of (resolution_x, resolution_y)'''
return self.resolution
def set_texture_resolution(self, value: Tuple[float]):
'''Set the resolution to render with (resolution_x, resolution_y)'''
self.resolution = value
def get_texture_resolution_scale(self) -> float:
'''Get the scaling factor for the Viewport's render resolution.'''
return self.resolution_scale
def set_texture_resolution_scale(self, value: float):
'''Set the scaling factor for the Viewport's render resolution.'''
self.resolution_scale = value
def get_full_texture_resolution(self) -> Tuple[float]:
'''Return a tuple of (full_resolution_x, full_resolution_y)'''
return self.full_resolution
@property
def fill_frame(self) -> bool:
if self.__fill_frame is None:
settings = carb.settings.get_settings()
width, height = settings.get('/app/renderer/resolution/width') or 0, settings.get('/app/renderer/resolution/height') or 0
self.__fill_frame = (width <= 0) or (height <= 0)
return self.__fill_frame
@fill_frame.setter
def fill_frame(self, value: bool):
settings = carb.settings.get_settings()
legacy_window = self.legacy_window
self.__fill_frame = bool(value)
if self.__fill_frame:
self.__saved_resolution = legacy_window.get_texture_resolution()
legacy_window.set_texture_resolution(-1, -1)
settings.set('/app/renderer/resolution/width', -1)
settings.set('/app/renderer/resolution/height', -1)
else:
if self.__saved_resolution is None:
width, height = settings.get('/app/renderer/resolution/width') or 0, settings.get('/app/renderer/resolution/height') or 0
self.__saved_resolution = (width, height) if (width > 0 and height > 0) else (1280, 720)
legacy_window.set_texture_resolution(self.__saved_resolution[0], self.__saved_resolution[1])
@property
def fps(self) -> float:
'''Return the frames-per-second this Viewport is running at'''
return self.legacy_window.get_fps()
@property
def id(self):
'''Return a hashable value for the Viewport'''
return self.legacy_window.get_id()
@property
def frame_info(self):
return { 'viewport_handle' : self.legacy_window.get_id() }
@property
def usd_context_name(self) -> str:
'''Return the name of the omni.usd.UsdContext this Viewport is attached to'''
return self.legacy_window.get_usd_context_name()
@property
def usd_context(self):
'''Return the omni.usd.UsdContext this Viewport is attached to'''
return omni.usd.get_context(self.usd_context_name)
@property
def stage(self):
'''Return the Usd.Stage of the omni.usd.UsdContext this Viewport is attached to'''
return self.usd_context.get_stage()
@property
def projection(self):
'''Return the projection of the UsdCamera in terms of the ui element it sits in.'''
# Check if there are cached values from the ScenView subscriptions
legacy_subs = _LegacySceneView.get(self.__window_name)
if legacy_subs:
projection = legacy_subs.projection
if projection:
return projection
# Get the info from USD
stage = self.stage
cam_prim = stage.GetPrimAtPath(self.camera_path) if stage else None
if cam_prim:
usd_camera = UsdGeom.Camera(cam_prim)
if usd_camera:
image_aspect, canvas_aspect = self._aspect_ratios
return self._conform_projection(self._conform_policy(), usd_camera, image_aspect, canvas_aspect)
return Gf.Matrix4d(1)
@property
def transform(self) -> Gf.Matrix4d:
'''Return the world-space transform of the UsdGeom.Camera being used to render'''
# Check if there are cached values from the ScenView subscriptions
legacy_subs = _LegacySceneView.get(self.__window_name)
if legacy_subs:
view = legacy_subs.view
if view:
return view.GetInverse()
# Get the info from USD
stage = self.stage
cam_prim = stage.GetPrimAtPath(self.camera_path) if stage else None
if cam_prim:
imageable = UsdGeom.Imageable(cam_prim)
if imageable:
return imageable.ComputeLocalToWorldTransform(self.time)
return Gf.Matrix4d(1)
@property
def view(self) -> Gf.Matrix4d:
'''Return the inverse of the world-space transform of the UsdGeom.Camera being used to render'''
# Check if there are cached values from the ScenView subscriptions
legacy_subs = _LegacySceneView.get(self.__window_name)
if legacy_subs:
view = legacy_subs.view
if view:
return view
# Get the info from USD
return self.transform.GetInverse()
@property
def world_to_ndc(self):
return self.view * self.projection
@property
def ndc_to_world(self):
return self.world_to_ndc.GetInverse()
@property
def time(self) -> Usd.TimeCode:
'''Return the Usd.TimeCode this Viewport is using'''
if self.__timeline is None:
self.__timeline = omni.timeline.get_timeline_interface()
time = self.__timeline.get_current_time()
return Usd.TimeCode(omni.usd.get_frame_time_code(time, self.stage.GetTimeCodesPerSecond()))
def map_ndc_to_texture(self, mouse: Sequence[float]):
image_aspect, canvas_aspect = self._aspect_ratios
if image_aspect < canvas_aspect:
ratios = (image_aspect / canvas_aspect, 1)
else:
ratios = (1, canvas_aspect / image_aspect)
# Move into viewport's NDC-space: [-1, 1] bound by viewport
mouse = (mouse[0] / ratios[0], mouse[1] / ratios[1])
# Move from NDC space to texture-space [-1, 1] to [0, 1]
def check_bounds(coord): return coord >= -1 and coord <= 1
return tuple((x + 1.0) * 0.5 for x in mouse), self if (check_bounds(mouse[0]) and check_bounds(mouse[1])) else None
def map_ndc_to_texture_pixel(self, mouse: Sequence[float]):
# Move into viewport's uv-space: [0, 1]
mouse, viewport = self.map_ndc_to_texture(mouse)
# Then scale by resolution flipping-y
resolution = self.resolution
return (int(mouse[0] * resolution[0]), int((1.0 - mouse[1]) * resolution[1])), viewport
def request_query(self, pixel: Sequence[int], callback: Callable, *args):
# TODO: This can't be made 100% compatible without changes to legacy Viewport
# New Viewport will query based on a pixel co-ordinate, regardless of mouse-state; with object and world-space-position
# Legacy Viewport will invoke callback on mouse-click only; with world-space-position info only
self.legacy_window.query_next_picked_world_position(lambda pos: callback(True, pos) if pos else callback(False, None))
carb.log_warn("request_query not full implemented, will only receive a position from a Viewport click")
@property
def hydra_engine(self) -> str:
'''Get the name of the active omni.hydra.engine for this Viewport'''
return self.legacy_window.get_active_hydra_engine()
@hydra_engine.setter
def hydra_engine(self, hd_engine: str) -> str:
'''Set the name of the active omni.hydra.engine for this Viewport'''
return self.set_hd_engine(hd_engine)
@property
def render_mode(self):
'''Get the render-mode for the active omni.hydra.engine used in this Viewport'''
hd_engine = self.hydra_engine
if bool(hd_engine):
return self.__settings.get(self.__render_mode_setting(hd_engine))
@render_mode.setter
def render_mode(self, render_mode: str):
'''Set the render-mode for the active omni.hydra.engine used in this Viewport'''
hd_engine = self.hydra_engine
if bool(hd_engine):
self.__settings.set_string(self.__render_mode_setting(hd_engine), str(render_mode))
def set_hd_engine(self, hd_engine: str, render_mode: str = None):
'''Set the active omni.hydra.engine for this Viewport, and optionally its render-mode'''
# self.__settings.set_string("/renderer/active", hd_engine)
if bool(hd_engine) and bool(render_mode):
self.__settings.set_string(self.__render_mode_setting(hd_engine), render_mode)
self.legacy_window.set_active_hydra_engine(hd_engine)
async def wait_for_rendered_frames(self, additional_frames: int = 0) -> bool:
'''Asynchrnously wait until the renderer has delivered an image'''
app = omni.kit.app.get_app_interface()
legacy_window = self.legacy_window
if legacy_window:
viewport_ldr_rp = None
while viewport_ldr_rp is None:
await app.next_update_async()
viewport_ldr_rp = legacy_window.get_drawable_ldr_resource()
while additional_frames > 0:
additional_frames = additional_frames - 1
await app.next_update_async()
return True
def add_scene_view(self, scene_view):
window_name = self.__window_name
legacy_subs = _LegacySceneView.get(self.__window_name, self.legacy_window)
if not legacy_subs:
raise RuntimeError('Could not create _LegacySceneView subscriptions')
legacy_subs.add_scene_view(scene_view, self.projection, self.view)
def remove_scene_view(self, scene_view):
if not scene_view:
raise RuntimeError('Provided scene_view is invalid')
_LegacySceneView.remove_scene_view_for_window(self.__window_name, scene_view)
### Everything below is NOT part of the new Viewport-API
@property
def legacy_window(self):
'''Expose the underlying legacy viewport for access if needed (not a real ViewportAPI method)'''
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
return vp_iface.get_viewport_window(vp_iface.get_instance(self.__window_name))
@property
def _aspect_ratios(self) -> Tuple[float]:
return _LegacySceneView.aspect_ratios(self.__window_name, self.legacy_window)
def _conform_projection(self, policy, camera: UsdGeom.Camera, image_aspect: float, canvas_aspect: float, projection: Sequence[float] = None):
'''For the given camera (or possible incoming projection) return a projection matrix that matches the rendered image
but keeps NDC co-ordinates for the texture bound to [-1, 1]'''
if projection is None:
# If no projection is provided, conform the camera based on settings
# This wil adjust apertures on the gf_camera
gf_camera = camera.GetCamera(self.time)
if policy == CameraUtil.DontConform:
# For DontConform, still have to conform for the final canvas
if image_aspect < canvas_aspect:
gf_camera.horizontalAperture = gf_camera.horizontalAperture * (canvas_aspect / image_aspect)
else:
gf_camera.verticalAperture = gf_camera.verticalAperture * (image_aspect / canvas_aspect)
else:
CameraUtil.ConformWindow(gf_camera, policy, image_aspect)
projection = gf_camera.frustum.ComputeProjectionMatrix()
else:
projection = Gf.Matrix4d(*projection)
# projection now has the rendered image projection
# Conform again based on canvas size so projection extends with the Viewport sits in the UI
if image_aspect < canvas_aspect:
policy2 = CameraUtil.MatchVertically
else:
policy2 = CameraUtil.MatchHorizontally
if policy != CameraUtil.DontConform:
projection = CameraUtil.ConformedWindow(projection, policy2, canvas_aspect)
return projection
def _conform_policy(self):
conform_setting = self.__settings.get("/app/hydra/aperture/conform")
if (conform_setting is None) or (conform_setting == 1) or (conform_setting == 'horizontal'):
return CameraUtil.MatchHorizontally
if (conform_setting == 0) or (conform_setting == 'vertical'):
return CameraUtil.MatchVertically
if (conform_setting == 2) or (conform_setting == 'fit'):
return CameraUtil.Fit
if (conform_setting == 3) or (conform_setting == 'crop'):
return CameraUtil.Crop
if (conform_setting == 4) or (conform_setting == 'stretch'):
return CameraUtil.DontConform
return CameraUtil.MatchHorizontally
def __render_mode_setting(self, hd_engine: str) -> str:
return f'/{hd_engine}/rendermode' if hd_engine != 'iray' else '/rtx/iray/rendermode'
class _LegacySceneView:
__g_legacy_subs = {}
@staticmethod
def aspect_ratios(window_name: str, legacy_window):
canvas_aspect = 1
viewport_window = omni.ui.Workspace.get_window(window_name)
if viewport_window:
# XXX: Why do some windows have no frame !?
if hasattr(viewport_window, 'frame'):
canvas = viewport_window.frame
canvas_size = (canvas.computed_width, canvas.computed_height)
else:
canvas_size = (1, 1)
canvas_aspect = canvas_size[0] / canvas_size[1] if canvas_size[1] else 1
resolution = legacy_window.get_texture_resolution()
image_aspect = resolution[0] / resolution[1] if resolution[1] else 1
return image_aspect, canvas_aspect
@staticmethod
def get(window_name: str, legacy_window = None):
legacy_subs = _LegacySceneView.__g_legacy_subs.get(window_name)
if legacy_subs is None and legacy_window:
legacy_subs = _LegacySceneView(window_name, legacy_window)
_LegacySceneView.__g_legacy_subs[window_name] = legacy_subs
return legacy_subs
@staticmethod
def remove_scene_view_for_window(window_name: str, scene_view):
if not scene_view:
raise RuntimeError('Provided scene_view is invalid')
legacy_subs = _LegacySceneView.__g_legacy_subs.get(window_name)
if not legacy_subs:
raise RuntimeError('Removing a SceneView for Viewport that is not trakcing any')
if legacy_subs.remove_scene_view(scene_view):
return
legacy_subs.destroy()
del _LegacySceneView.__g_legacy_subs[window_name]
def __init__(self, window_name: str, legacy_window):
self.__window_name = window_name
self.__draw_sub, self.__update_sub = None, None
self.__scene_views = []
self.__projection = None
self.__view = None
events = legacy_window.get_ui_draw_event_stream()
self.__draw_sub = events.create_subscription_to_pop(self.__on_draw, name=f'omni.kit.viewport.utility.LegacyViewportAPI.{window_name}.draw')
events = omni.kit.app.get_app().get_update_event_stream()
self.__update_sub = events.create_subscription_to_pop(self.__on_update, name='omni.kit.viewport.utility.LegacyViewportAPI.{window_name}.update')
@property
def projection(self) -> Gf.Matrix4d:
# Return a copy as the reference would be mutable
return Gf.Matrix4d(self.__projection) if self.__projection else None
@property
def view(self) -> Gf.Matrix4d:
# Return a copy as the reference would be mutable
return Gf.Matrix4d(self.__view) if self.__view else None
def __del__(self):
self.destroy()
def destroy(self):
self.__scene_views = []
if self.__draw_sub:
self.__draw_sub = None
if self.__update_sub:
self.__update_sub = None
self.__save_position = None
self.__scene_views = []
@staticmethod
def _flatten_matrix(m: Gf.Matrix4d) -> List[float]:
m0, m1, m2, m3 = m[0], m[1], m[2], m[3]
return [m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3]]
def __get_legacy_window(self):
import omni.kit.viewport_legacy as vp_legacy
vp_iface = vp_legacy.get_viewport_interface()
window_name = self.__window_name
viewport_handle = vp_iface.get_instance(window_name)
viewport_window = vp_iface.get_viewport_window(viewport_handle)
if not viewport_window:
self.destroy()
del _LegacySceneView.__g_legacy_subs[window_name]
return window_name, viewport_window
def __on_update(self, *args):
window_name, legacy_window = self.__get_legacy_window()
visible = legacy_window.is_visible() if legacy_window else False
viewport_window = omni.ui.Workspace.get_window(window_name)
if viewport_window and (visible != viewport_window.visible):
pruned_views = []
for sv in self.__scene_views:
scene_view = sv()
if scene_view:
scene_view.visible = visible
pruned_views.append(sv)
self.__scene_views = pruned_views
omni.ui.Workspace.show_window(window_name, visible)
# viewport_window.visible = visible
# if not visible:
# self.__save_position = viewport_window.position_x, viewport_window.position_y
# viewport_window.position_x = omni.ui.Workspace.get_main_window_width()
# viewport_window.position_y = omni.ui.Workspace.get_main_window_height()
# elif self.__save_position:
# viewport_window.position_x = self.__save_position[0]
# viewport_window.position_y = self.__save_position[1]
# self.__save_position = None
def __on_draw(self, event, *args):
vm = event.payload["viewMatrix"]
pm = event.payload["projMatrix"]
# Conform the Projection to the layout of the texture in the Window
window_name, legacy_window = self.__get_legacy_window()
image_aspect, canvas_aspect = _LegacySceneView.aspect_ratios(window_name, legacy_window)
if image_aspect < canvas_aspect:
policy = CameraUtil.MatchVertically
else:
policy = CameraUtil.MatchHorizontally
proj_matrix = Gf.Matrix4d(pm[0], pm[1], pm[2], pm[3], pm[4], pm[5], pm[6], pm[7], pm[8], pm[9], pm[10], pm[11], pm[12], pm[13], pm[14], pm[15])
# Fix up RTX projection Matrix for omni.ui.scene...ultimately this should be passed without any compensation
if pm[15] == 0.0:
proj_matrix = Gf.Matrix4d(1.0, 0.0, -0.0, 0.0, 0.0, 1.0, 0.0, -0.0, -0.0, 0.0, 1.0, -1.0, 0.0, -0.0, 0.0, -2.0) * proj_matrix
proj_matrix = CameraUtil.ConformedWindow(proj_matrix, policy, canvas_aspect)
# Cache these for lokkup later
self.__projection = proj_matrix
self.__view = 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])
# Flatten into list for model
pm = _LegacySceneView._flatten_matrix(proj_matrix)
pruned_views = []
for sv in self.__scene_views:
scene_view = sv()
if scene_view:
model = scene_view.model
model.set_floats("projection", pm)
model.set_floats("view", vm)
pruned_views.append(sv)
self.__scene_views = pruned_views
def add_scene_view(self, scene_view, projection: Gf.Matrix4d, view: Gf.Matrix4d):
# Sync the model once now
model = scene_view.model
model.set_floats("projection", _LegacySceneView._flatten_matrix(projection))
model.set_floats("view", _LegacySceneView._flatten_matrix(view))
# And save it for subsequent synchrnoizations
import weakref
self.__scene_views.append(weakref.ref(scene_view))
def remove_scene_view(self, scene_view) -> bool:
for sv in self.__scene_views:
if sv() == scene_view:
self.__scene_views.remove(sv)
break
# Return whether this sub is needed anymore
return True if self.__scene_views else False
| 24,854 | Python | 43.147424 | 152 | 0.634948 |
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/capture.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = [
'DEFAULT_THRESHOLD',
'capture_viewport_and_compare'
]
import carb
import omni.kit.app
import omni.renderer_capture
from omni.kit.test_helpers_gfx import compare, CompareError
from omni.kit.test.teamcity import teamcity_log_fail, teamcity_publish_image_artifact
import pathlib
import traceback
DEFAULT_THRESHOLD = 10.0
def viewport_capture(image_name: str, output_img_dir: str, viewport=None, use_log: bool = True):
"""
Captures a Viewport texture into a file.
Args:
image_name: the image name of the image and golden image.
output_img_dir: the directory path that the capture will be saved to.
golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir.
use_log: whether to log the comparison image path
"""
from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file
image1 = str(pathlib.Path(output_img_dir).joinpath(image_name))
if use_log:
carb.log_info(f"[tests.compare] Capturing {image1}")
if viewport is None:
viewport = get_active_viewport()
return capture_viewport_to_file(viewport, file_path=image1)
def finalize_capture_and_compare(image_name: str, output_img_dir: str, golden_img_dir: str, threshold: float = DEFAULT_THRESHOLD):
"""
Finalizes capture and compares it with the golden image.
Args:
image_name: the image name of the image and golden image.
threshold: the max threshold to collect TC artifacts.
output_img_dir: the directory path that the capture will be saved to.
golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir.
Returns:
A value that indicates the maximum difference between pixels. 0 is no difference
in the range [0-255].
"""
image1 = pathlib.Path(output_img_dir).joinpath(image_name)
image2 = pathlib.Path(golden_img_dir).joinpath(image_name)
image_diffmap_name = f"{pathlib.Path(image_name).stem}.diffmap.png"
image_diffmap = pathlib.Path(output_img_dir).joinpath(image_diffmap_name)
carb.log_info(f"[tests.compare] Comparing {image1} to {image2}")
try:
diff = compare(image1, image2, image_diffmap)
if diff >= threshold:
# TODO pass specific test name here instead of omni.rtx.tests
teamcity_log_fail("omni.rtx.tests", f"Reference image {image_name} differ from golden.")
teamcity_publish_image_artifact(image2, "golden", "Reference")
teamcity_publish_image_artifact(image1, "results", "Generated")
teamcity_publish_image_artifact(image_diffmap, "results", "Diff")
return diff
except CompareError as e:
carb.log_error(f"[tests.compare] Failed to compare images for {image_name}. Error: {e}")
exc = traceback.format_exc()
carb.log_error(f"[tests.compare] Traceback:\n{exc}")
async def capture_viewport_and_wait(image_name: str, output_img_dir: str, viewport = None):
viewport_capture(image_name, output_img_dir, viewport)
app = omni.kit.app.get_app()
capure_iface = omni.renderer_capture.acquire_renderer_capture_interface()
for i in range(3):
capure_iface.wait_async_capture()
await app.next_update_async()
async def capture_viewport_and_compare(image_name: str, output_img_dir: str, golden_img_dir: str, threshold: float = DEFAULT_THRESHOLD, viewport = None, test_caller: str = None):
"""
Captures frame and compares it with the golden image.
Args:
image_name: the image name of the image and golden image.
golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir.
threshold: the max threshold to collect TC artifacts.
viewport: the viewport to capture or None for the active Viewport
Returns:
A value that indicates the maximum difference between pixels. 0 is no difference
in the range [0-255].
"""
await capture_viewport_and_wait(image_name=image_name, output_img_dir=output_img_dir, viewport=viewport)
diff = finalize_capture_and_compare(image_name=image_name, output_img_dir=output_img_dir, golden_img_dir=golden_img_dir, threshold=threshold)
if diff is not None and diff < DEFAULT_THRESHOLD:
return True, ''
carb.log_warn(f"[{image_name}] the generated image has difference {diff}")
if test_caller is None:
import os.path
test_caller = os.path.splitext(image_name)[0]
return False, f"The image for test '{test_caller}' doesn't match the golden one. Difference of {diff} is is not less than threshold of {threshold}."
| 5,144 | Python | 39.511811 | 178 | 0.700428 |
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/__init__.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .capture import *
from .test_suite import *
async def setup_viewport_test_window(resolution_x: int, resolution_y: int, position_x: int = 0, position_y: int = 0):
from omni.kit.viewport.utility import get_active_viewport_window
viewport_window = get_active_viewport_window()
if viewport_window:
viewport_window.position_x = position_x
viewport_window.position_y = position_y
viewport_window.width = resolution_x
viewport_window.height = resolution_y
viewport_window.viewport_api.resolution = (resolution_x, resolution_y)
return viewport_window
| 1,043 | Python | 42.499998 | 117 | 0.744966 |
omniverse-code/kit/exts/omni.kit.viewport.utility/omni/kit/viewport/utility/tests/test_suite.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestViewportUtility']
import omni.kit.test
from omni.kit.test import AsyncTestCase
import omni.kit.viewport.utility
import omni.kit.renderer_capture
import omni.kit.app
import omni.usd
import omni.ui as ui
from pathlib import Path
from pxr import Gf, UsdGeom, Sdf, Usd
TEST_OUTPUT = Path(omni.kit.test.get_test_output_path()).resolve().absolute()
TEST_WIDTH, TEST_HEIGHT = (500, 500)
class TestViewportUtility(AsyncTestCase):
# Before running each test
async def setUp(self):
super().setUp()
await omni.usd.get_context().new_stage_async()
async def tearDown(self):
super().tearDown()
# Legacy Viewport needs some time to adopt the resolution changes
async def wait_for_resolution_change(self, viewport_api):
await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api)
for i in range(3):
await omni.kit.app.get_app().next_update_async()
async def test_get_viewport_from_window_name(self):
'''Test getting a default Viewport from a Window without a name'''
viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name()
self.assertIsNotNone(viewport_window)
async def test_get_viewport_from_window_name_with_name(self):
'''Test getting a default Viewport from a Window name'''
viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name(window_name='Viewport')
self.assertIsNotNone(viewport_window)
async def test_get_active_viewport(self):
'''Test getting a default Viewport'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
viewport_api = omni.kit.viewport.utility.get_active_viewport(usd_context_name='')
self.assertIsNotNone(viewport_api)
async def test_get_viewport_from_non_existant_window_name_with_name(self):
'''Test getting a non-existent Viewport via Window name'''
viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name(window_name='NotExisting')
self.assertIsNone(viewport_window)
async def test_get_non_existant_viewport(self):
'''Test getting a non-existent Viewport via UsdContext name'''
viewport_api = omni.kit.viewport.utility.get_active_viewport(usd_context_name='NotExisting')
self.assertIsNone(viewport_api)
async def test_get_camera_path_api(self):
'''Test camera access API'''
# Test camera-path as an Sdf.Path
cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path()
self.assertTrue(bool(cam_path))
self.assertTrue(isinstance(cam_path, Sdf.Path))
cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path(window_name='Viewport')
self.assertTrue(bool(cam_path))
self.assertTrue(isinstance(cam_path, Sdf.Path))
cam_path = omni.kit.viewport.utility.get_viewport_window_camera_path(window_name='NO_Viewport')
self.assertIsNone(cam_path)
cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path()
self.assertTrue(bool(cam_path))
self.assertTrue(isinstance(cam_path, Sdf.Path))
cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path(usd_context_name='')
self.assertTrue(bool(cam_path))
self.assertTrue(isinstance(cam_path, Sdf.Path))
cam_path = omni.kit.viewport.utility.get_active_viewport_camera_path(usd_context_name='DoesntExist')
self.assertIsNone(cam_path)
# Test camera-path as a string
cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string()
self.assertTrue(bool(cam_path_str))
self.assertTrue(isinstance(cam_path_str, str))
cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string(window_name='Viewport')
self.assertTrue(bool(cam_path_str))
self.assertTrue(isinstance(cam_path_str, str))
cam_path_str = omni.kit.viewport.utility.get_viewport_window_camera_string(window_name='NO_Viewport')
self.assertIsNone(cam_path_str)
cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string()
self.assertTrue(bool(cam_path_str))
self.assertTrue(isinstance(cam_path_str, str))
cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string(usd_context_name='')
self.assertTrue(bool(cam_path_str))
self.assertTrue(isinstance(cam_path_str, str))
cam_path_str = omni.kit.viewport.utility.get_active_viewport_camera_string(usd_context_name='DoesntExist')
self.assertIsNone(cam_path_str)
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
# Test property and method accessors are equal
self.assertEqual(viewport_api.get_active_camera(), viewport_api.camera_path)
async def test_setup_viewport_test_window(self):
'''Test the test-suite utility setup_viewport_test_window'''
from omni.kit.viewport.utility.tests import setup_viewport_test_window
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
resolution = viewport_api.resolution
# Test the keywords arguments for the function
await setup_viewport_test_window(resolution_x=128, resolution_y=128, position_x=10, position_y=10)
# Test the arguments for the function and restore Viewport resolution
await setup_viewport_test_window(resolution[0], resolution[1], 0, 0)
async def test_viewport_resolution(self):
'''Test the test-suite utility setup_viewport_test_window'''
from omni.kit.viewport.utility.tests import setup_viewport_test_window
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
# Legacy Viewport needs some time to adopt the resolution changes
try:
resolution = viewport_api.resolution
self.assertIsNotNone(resolution)
full_resolution = viewport_api.full_resolution
self.assertEqual(resolution, full_resolution)
resolution_scale = viewport_api.resolution_scale
# Resolution scale factor should be 1 by default
self.assertEqual(resolution_scale, 1.0)
viewport_api.resolution_scale = 0.5
await self.wait_for_resolution_change(viewport_api)
# Resolution scale factor should stick
self.assertEqual(viewport_api.resolution_scale, 0.5)
# Full resolution should still be the same
self.assertEqual(viewport_api.full_resolution, full_resolution)
# New resolution should now be half of the original
self.assertEqual(viewport_api.resolution, (resolution[0] * 0.5, resolution[1] * 0.5))
finally:
viewport_api.resolution_scale = 1.0
self.assertEqual(viewport_api.resolution_scale, 1.0)
async def test_testsuite_capture_helpers(self):
'''Test the API exposed to assist other extensions testing/capturing Viewport'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
from omni.kit.viewport.utility.tests.capture import viewport_capture, capture_viewport_and_wait
# Test keyword arguments with an explicit Viewport
await capture_viewport_and_wait(image_name='test_testsuite_capture_helper_01', output_img_dir=str(TEST_OUTPUT), viewport = viewport_api)
# Test arguments with an implicit Viewport
await capture_viewport_and_wait('test_testsuite_capture_helper_02', str(TEST_OUTPUT))
async def test_legacy_as_new_api(self):
'''Test the new API against a new or legacy Viewport'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
self.assertEqual(viewport_api.camera_path.pathString, '/OmniverseKit_Persp')
# Test camera property setter
viewport_api.camera_path = '/OmniverseKit_Top'
self.assertEqual(viewport_api.camera_path.pathString, '/OmniverseKit_Top')
# Test camera method setter
viewport_api.set_active_camera('/OmniverseKit_Persp')
resolution = viewport_api.resolution
self.assertIsNotNone(resolution)
# Test access via legacy method-name
self.assertEqual(resolution, viewport_api.get_texture_resolution())
# Test setting via property
viewport_api.resolution = (128, 128)
await self.wait_for_resolution_change(viewport_api)
self.assertEqual(viewport_api.resolution, (128, 128))
# Test setting via method
viewport_api.set_texture_resolution((256, 256))
await self.wait_for_resolution_change(viewport_api)
self.assertEqual(viewport_api.get_texture_resolution(), (256, 256))
# Test matrix access
self.assertIsNotNone(viewport_api.projection)
self.assertIsNotNone(viewport_api.transform)
self.assertIsNotNone(viewport_api.view)
# Test world-NDC matrix convertor access
self.assertIsNotNone(viewport_api.world_to_ndc)
self.assertIsNotNone(viewport_api.ndc_to_world)
# Test UsdContext and Stage access
self.assertIsNotNone(viewport_api.usd_context_name)
self.assertIsNotNone(viewport_api.usd_context)
self.assertIsNotNone(viewport_api.stage)
render_product_path = viewport_api.render_product_path
self.assertIsNotNone(render_product_path)
# Test access via legacy method-name
self.assertEqual(render_product_path, viewport_api.get_render_product_path())
# Test setting via property
viewport_api.render_product_path = render_product_path
# Test setting via method
viewport_api.set_render_product_path(render_product_path)
# Should have an id property
self.assertIsNotNone(viewport_api.id)
# Should have a frame_info dictionary
self.assertIsNotNone(viewport_api.frame_info)
# Test the NDC to texture-uv mapping API
uv, valid = viewport_api.map_ndc_to_texture((0, 0))
self.assertTrue(bool(valid))
self.assertEqual(uv, (0.5, 0.5))
# Test the NDC to texture-pixel mapping API
pixel, valid = viewport_api.map_ndc_to_texture_pixel((0, 0))
self.assertTrue(bool(valid))
# Test API to set fill-frame resolution
self.assertFalse(viewport_api.fill_frame)
viewport_api.fill_frame = True
await self.wait_for_resolution_change(viewport_api)
self.assertTrue(viewport_api.fill_frame)
viewport_api.fill_frame = False
await self.wait_for_resolution_change(viewport_api)
self.assertFalse(viewport_api.fill_frame)
async def test_viewport_window_api(self):
'''Test the legacy API exposure into the omni.ui window wrapper'''
viewport_window = omni.kit.viewport.utility.get_active_viewport_window()
self.assertIsNotNone(viewport_window)
# Test the get_frame API
frame_1 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_1')
self.assertIsNotNone(frame_1)
frame_2 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_1')
self.assertEqual(frame_1, frame_2)
frame_3 = viewport_window.get_frame('omni.kit.viewport.utility.test_frame_3')
self.assertNotEqual(frame_1, frame_3)
# Test setting visible attribute on Window
viewport_window.visible = True
self.assertTrue(viewport_window.visible)
# Test utility function for legacy usage only
if viewport_window and hasattr(viewport_window.viewport_api, 'legacy_window'):
viewport_window.setPosition(0, 0)
viewport_window.set_position(0, 0)
async def test_toggle_global_visibility(self):
"""Test the expected setting change for omni.kit.viewport.utility.toggle_global_visibility"""
import carb
settings = carb.settings.get_settings()
viewport_api = omni.kit.viewport.utility.get_active_viewport()
if hasattr(viewport_api, 'legacy_window'):
def collect_settings(settings):
return settings.get('/persistent/app/viewport/displayOptions')
else:
def collect_settings(settings):
setting_keys = [
"/persistent/app/viewport/Viewport/Viewport0/guide/grid/visible",
"/persistent/app/viewport/Viewport/Viewport0/hud/deviceMemory/visible",
"/persistent/app/viewport/Viewport/Viewport0/hud/hostMemory/visible",
"/persistent/app/viewport/Viewport/Viewport0/hud/renderFPS/visible",
"/persistent/app/viewport/Viewport/Viewport0/hud/renderProgress/visible",
"/persistent/app/viewport/Viewport/Viewport0/hud/renderResolution/visible",
"/persistent/app/viewport/Viewport/Viewport0/scene/cameras/visible",
"/persistent/app/viewport/Viewport/Viewport0/scene/lights/visible",
"/persistent/app/viewport/Viewport/Viewport0/scene/skeletons/visible",
]
return {k: settings.get(k) for k in setting_keys}
omni.kit.viewport.utility.toggle_global_visibility()
options_1 = collect_settings(settings)
omni.kit.viewport.utility.toggle_global_visibility()
options_2 = collect_settings(settings)
self.assertNotEqual(options_1, options_2)
omni.kit.viewport.utility.toggle_global_visibility()
options_3 = collect_settings(settings)
self.assertEqual(options_1, options_3)
omni.kit.viewport.utility.toggle_global_visibility()
options_4 = collect_settings(settings)
self.assertEqual(options_2, options_4)
async def test_ui_scene_view_model_sync(self):
'''Test API to autmoatically set view and projection on a SceneView model'''
class ModelPoser:
def __init__(model_self):
model_self.set_items = set()
def get_item(model_self, name: str):
if name == 'view' or name == 'projection':
return name
self.assertTrue(False)
def set_floats(model_self, item, floats):
self.assertEqual(len(floats), 16)
self.assertTrue(item == model_self.get_item(item))
model_self.set_items.add(item)
class SceneViewPoser:
def __init__(model_self):
model_self.model = ModelPoser()
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
scene_view = SceneViewPoser()
# Test add_scene_view API
viewport_api.add_scene_view(scene_view)
# Test both view and projection have been set into
self.assertTrue('view' in scene_view.model.set_items)
self.assertTrue('projection' in scene_view.model.set_items)
# Test remove_scene_view API
viewport_api.remove_scene_view(scene_view)
async def test_legacy_drag_drop_helper(self):
pickable = False
add_outline = False
def on_drop_accepted_fn(url):
pass
def on_drop_fn(url, prim_path, unused_viewport_name, usd_context_name):
pass
def on_pick_fn(payload, prim_path, usd_context_name):
pass
dd_from_args = omni.kit.viewport.utility.create_drop_helper(
pickable, add_outline, on_drop_accepted_fn, on_drop_fn, on_pick_fn
)
self.assertIsNotNone(dd_from_args)
dd_from_kw = omni.kit.viewport.utility.create_drop_helper(
pickable=pickable, add_outline=add_outline, on_drop_accepted_fn=on_drop_accepted_fn, on_drop_fn=on_drop_fn, on_pick_fn=on_pick_fn
)
self.assertIsNotNone(dd_from_kw)
async def test_capture_file(self):
'''Test the capture_viewport_to_file capture to a file'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertTrue(bool(viewport_api))
# Make sure renderer is rendering images (also a good place to up the coverage %)
await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api)
file = TEST_OUTPUT.joinpath('capture_01.png')
cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=str(file))
# API should return an object we can await on
self.assertIsNotNone(cap_obj)
# Test that we can in fact wait on that object
result = await cap_obj.wait_for_result(completion_frames=30)
self.assertTrue(result)
# File should exists by now
omni.kit.renderer_capture.acquire_renderer_capture_interface().wait_async_capture()
self.assertTrue(file.exists())
async def test_capture_file_with_exr_compression(self):
'''Test the capture_viewport_to_file capture to a file'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertTrue(bool(viewport_api))
# Make sure renderer is rendering images (also a good place to up the coverage %)
await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api)
format_desc = {}
format_desc["format"] = "exr"
format_desc["compression"] = "b44"
file = TEST_OUTPUT.joinpath(f'capture_{format_desc["compression"]}.{format_desc["format"]}')
cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=str(file), format_desc=format_desc)
# API should return an object we can await on
self.assertIsNotNone(cap_obj)
# Test that we can in fact wait on that object
result = await cap_obj.wait_for_result(completion_frames=30)
self.assertTrue(result)
# File should exists by now
omni.kit.renderer_capture.acquire_renderer_capture_interface().wait_async_capture()
self.assertTrue(file.exists())
async def test_capture_file_str_convert(self):
'''Test the capture_viewport_to_file capture to a file when passed an path-like object'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertTrue(bool(viewport_api))
# Make sure renderer is rendering images (also a good place to up the coverage %)
await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api)
file = TEST_OUTPUT.joinpath('capture_02.png')
cap_obj = omni.kit.viewport.utility.capture_viewport_to_file(viewport_api, file_path=file)
# API should return an object we can await on
self.assertIsNotNone(cap_obj)
# Test that we can in fact wait on that object
result = await cap_obj.wait_for_result(completion_frames=15)
self.assertTrue(result)
# File should exists by now
# self.assertTrue(file.exists())
async def test_capture_to_buffer(self):
'''Test the capture_viewport_to_file capture to a callback function'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertTrue(bool(viewport_api))
# Make sure renderer is rendering images (also a good place to up the coverage %)
await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api)
callback_called = False
def capture_callback(*args, **kwargs):
nonlocal callback_called
callback_called = True
cap_obj = omni.kit.viewport.utility.capture_viewport_to_buffer(viewport_api, capture_callback)
# API should return an object we can await on
self.assertIsNotNone(cap_obj)
# Test that we can in fact wait on that object
result = await cap_obj.wait_for_result()
self.assertTrue(result)
# Callback should have been called
self.assertTrue(callback_called)
async def test_new_viewport_api(self):
'''Test the ability to create a new Viewport and retrieve the number of Viewports open'''
num_vp_1 = omni.kit.viewport.utility.get_num_viewports()
self.assertEqual(num_vp_1, 1)
# Test Window creation, but that would require a renderer other than Storm which can only be created once
# Which would make the tests run slower and in L2
# new_window = omni.kit.viewport.utility.create_viewport_window('TEST WINDOW', width=128, height=128, camera_path='/OmniverseKit_Top')
# self.assertEqual(new_window.viewport_api.camera_path.pathString, '/OmniverseKit_Top')
# num_vp_2 = omni.kit.viewport.utility.get_num_viewports()
# self.assertEqual(num_vp_2, 2)
async def test_post_toast_api(self):
# Post a message with a Viewport only
viewport_api = omni.kit.viewport.utility.get_active_viewport()
omni.kit.viewport.utility.post_viewport_message(viewport_api, "Message from ViewportAPI")
# Post a message with the same API, but a Window
viewport_window = omni.kit.viewport.utility.get_active_viewport_window()
omni.kit.viewport.utility.post_viewport_message(viewport_window, "Message from ViewportWindow")
# Post a message with the same API, but with a method
viewport_window._post_toast_message("Message from ViewportWindow method")
async def test_disable_picking(self):
'''Test ability to disable picking on a Viewport or ViewportWindow'''
from omni.kit import ui_test
viewport_window = omni.kit.viewport.utility.get_active_viewport_window()
self.assertIsNotNone(viewport_window)
# viewport_window.position_x = 0
# viewport_window.position_y = 0
# viewport_window.width = TEST_WIDTH
# viewport_window.height = TEST_HEIGHT
viewport_api = viewport_window.viewport_api
self.assertIsNotNone(viewport_api)
usd_cube = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube")
usd_cube.GetSizeAttr().Set(100)
await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api)
async def test_selection_rect(wait_frames: int = 5):
selection = viewport_api.usd_context.get_selection()
self.assertIsNotNone(selection)
selection.set_selected_prim_paths([], False)
selected_prims = selection.get_selected_prim_paths()
self.assertFalse(bool(selected_prims))
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_drag_and_drop(ui_test.Vec2(100, 100), ui_test.Vec2(400, 400))
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
return selection.get_selected_prim_paths()
# Test initial selection works as expected
selection = await test_selection_rect()
self.assertTrue(len(selection) == 1)
self.assertTrue(selection[0] == '/cube')
# Test disabling selection on the Window leads to no selection
picking_disabled = omni.kit.viewport.utility.disable_selection(viewport_window)
selection = await test_selection_rect()
self.assertTrue(len(selection) == 0)
del picking_disabled
# Test restore of selection works as expected
selection = await test_selection_rect()
self.assertTrue(len(selection) == 1)
self.assertTrue(selection[0] == '/cube')
# Test disabling selection on the Viewport leads to no selection
picking_disabled = omni.kit.viewport.utility.disable_selection(viewport_api)
selection = await test_selection_rect()
self.assertTrue(len(selection) == 0)
del picking_disabled
async def test_frame_viewport(self):
time = Usd.TimeCode.Default()
def set_camera(cam_path: str, camera_pos=None, target_pos=None):
from omni.kit.viewport.utility.camera_state import ViewportCameraState
camera_state = ViewportCameraState(cam_path)
camera_state.set_position_world(camera_pos, True)
camera_state.set_target_world(target_pos, True)
def test_camera_position(cam_path: str, expected_pos: Gf.Vec3d):
prim = viewport_api.stage.GetPrimAtPath(cam_path)
camera = UsdGeom.Camera(prim) if prim else None
world_xform = camera.ComputeLocalToWorldTransform(time)
world_pos = world_xform.Transform(Gf.Vec3d(0, 0, 0))
for w_pos, ex_pos in zip(world_pos, expected_pos):
self.assertAlmostEqual(float(w_pos), float(ex_pos), 4)
viewport_window = omni.kit.viewport.utility.get_active_viewport_window()
self.assertIsNotNone(viewport_window)
viewport_api = viewport_window.viewport_api
usd_cube1 = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube1")
#usd_cube1.GetSizeAttr().Set(10)
usd_cube1_xformable = UsdGeom.Xformable(usd_cube1.GetPrim())
usd_cube1_xformable.AddTranslateOp()
attr = usd_cube1.GetPrim().GetAttribute("xformOp:translate")
attr.Set((200, 800, 4))
usd_cube2 = UsdGeom.Cube.Define(viewport_window.viewport_api.stage, "/cube2")
#usd_cube2.GetSizeAttr().Set(100)
await omni.kit.viewport.utility.next_viewport_frame_async(viewport_api)
selection = viewport_api.usd_context.get_selection()
self.assertIsNotNone(selection)
camera_path = '/OmniverseKit_Persp'
test_camera_position(camera_path, Gf.Vec3d(500, 500, 500))
# select cube1
selection.set_selected_prim_paths(["/cube1"], True)
# frame to the selection
omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api)
# test
test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306))
# select cube2
selection.set_selected_prim_paths(["/cube2"], True)
# frame to the selection
omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api)
# test
test_camera_position(camera_path, Gf.Vec3d(2.49306, 2.49306, 2.49306))
# unselect
selection.set_selected_prim_paths([], True)
# reset camera position
set_camera(camera_path, (500, 500, 500), (0, 0, 0))
test_camera_position(camera_path, Gf.Vec3d(500, 500, 500))
# frame. Because nothing is selected, it should frame to all.
omni.kit.viewport.utility.frame_viewport_selection(viewport_api=viewport_api)
test_camera_position(camera_path, Gf.Vec3d(522.65586, 822.65585, 424.65586))
# unselect
selection.set_selected_prim_paths([], True)
# reset camera position
set_camera(camera_path, (500, 500, 500), (0, 0, 0))
test_camera_position(camera_path, Gf.Vec3d(500, 500, 500))
# no frame on cube2 without to select it
omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api, prims=["/cube2"])
# should be the same as when we select
test_camera_position(camera_path, Gf.Vec3d(2.49306, 2.49306, 2.49306))
# reset camera position
set_camera(camera_path, (500, 500, 500), (0, 0, 0))
test_camera_position(camera_path, Gf.Vec3d(500, 500, 500))
# try on cube1
omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api, prims=["/cube1"])
test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306))
# call frame on prims with no list given
omni.kit.viewport.utility.frame_viewport_prims(viewport_api=viewport_api)
# camera should not move
test_camera_position(camera_path, Gf.Vec3d(202.49306, 802.49306, 6.49306))
async def test_disable_context_menu(self):
'''Test ability to disable context-menu on a Viewport or ViewportWindow'''
from omni.kit import ui_test
ctx_menu_wait = 50
#
# Initial checks about assumption that objects are reachable and that no context manu is visible
#
ui_viewport = ui_test.find("Viewport")
self.assertIsNotNone(ui_viewport)
self.assertIsNone(ui.Menu.get_current())
#
# Test context-menu is working by default
#
await ui_viewport.right_click(human_delay_speed=ctx_menu_wait)
self.assertIsNotNone(ui.Menu.get_current())
#
# Test disabling context-menu with a ViewportWindow
#
viewport_window = omni.kit.viewport.utility.get_active_viewport_window()
self.assertIsNotNone(viewport_window)
context_menu_disabled = omni.kit.viewport.utility.disable_context_menu(viewport_window)
await ui_viewport.right_click(human_delay_speed=ctx_menu_wait)
self.assertIsNone(ui.Menu.get_current())
del context_menu_disabled
# Context menu should work again
await ui_viewport.right_click(human_delay_speed=ctx_menu_wait)
self.assertIsNotNone(ui.Menu.get_current())
#
# Test disabling context-menu with a Viewport instance
#
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
context_menu_disabled = omni.kit.viewport.utility.disable_context_menu(viewport_api)
await ui_viewport.right_click(human_delay_speed=ctx_menu_wait)
self.assertIsNone(ui.Menu.get_current())
del context_menu_disabled
# Context menu should work again
await ui_viewport.right_click(human_delay_speed=ctx_menu_wait)
self.assertIsNotNone(ui.Menu.get_current())
#
# Test disabling context-menu globally
#
context_menu_disabled = omni.kit.viewport.utility.disable_context_menu()
await ui_viewport.right_click(human_delay_speed=ctx_menu_wait)
self.assertIsNone(ui.Menu.get_current())
del context_menu_disabled
# Context menu should work again
await ui_viewport.right_click(human_delay_speed=ctx_menu_wait)
self.assertIsNotNone(ui.Menu.get_current())
async def testget_ground_plane_info(self):
'''Test results from get_ground_plane_info'''
viewport_api = omni.kit.viewport.utility.get_active_viewport()
self.assertIsNotNone(viewport_api)
async def get_camera_ground_plane(path: str, ortho_special: bool = True, wait_frames: int = 3):
app = omni.kit.app.get_app()
viewport_api.camera_path = path
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
return omni.kit.viewport.utility.get_ground_plane_info(viewport_api, ortho_special)
def test_results(results, normal, planes):
self.assertTrue(Gf.IsClose(results[0], normal, 1e-5))
self.assertEqual(results[1], planes)
# Test ground plane info against Y-up stage
UsdGeom.SetStageUpAxis(viewport_api.stage, UsdGeom.Tokens.y)
persp_info = await get_camera_ground_plane('/OmniverseKit_Persp')
front_info = await get_camera_ground_plane('/OmniverseKit_Front')
top_info = await get_camera_ground_plane('/OmniverseKit_Top')
right_info = await get_camera_ground_plane('/OmniverseKit_Right')
right_info_world = await get_camera_ground_plane('/OmniverseKit_Right', False)
test_results(persp_info, Gf.Vec3d(0, 1, 0), ['x', 'z'])
test_results(front_info, Gf.Vec3d(0, 0, 1), ['x', 'y'])
test_results(top_info, Gf.Vec3d(0, 1, 0), ['x', 'z'])
test_results(right_info, Gf.Vec3d(1, 0, 0), ['y', 'z'])
test_results(right_info_world, Gf.Vec3d(0, 1, 0), ['x', 'z'])
# Test ground plane info against Z-up stage
UsdGeom.SetStageUpAxis(viewport_api.stage, UsdGeom.Tokens.z)
persp_info = await get_camera_ground_plane('/OmniverseKit_Persp')
front_info = await get_camera_ground_plane('/OmniverseKit_Front')
top_info = await get_camera_ground_plane('/OmniverseKit_Top')
right_info = await get_camera_ground_plane('/OmniverseKit_Right')
right_info_world = await get_camera_ground_plane('/OmniverseKit_Right', False)
test_results(persp_info, Gf.Vec3d(0, 0, 1), ['x', 'y'])
test_results(front_info, Gf.Vec3d(1, 0, 0), ['y', 'z'])
test_results(top_info, Gf.Vec3d(0, 0, 1), ['x', 'y'])
test_results(right_info, Gf.Vec3d(0, 1, 0), ['x', 'z'])
test_results(right_info_world, Gf.Vec3d(0, 0, 1), ['x', 'y'])
| 33,188 | Python | 43.789474 | 144 | 0.664578 |
omniverse-code/kit/exts/omni.kit.example.toolbar_button/omni/kit/example/toolbar_button/__init__.py | from .toolbar_button import *
| 30 | Python | 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.example.toolbar_button/omni/kit/example/toolbar_button/toolbar_button.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.ext
import omni.kit.app
import omni.kit.window.toolbar
import omni.ui
import os
from carb.input import KeyboardInput as Key
from omni.kit.widget.toolbar import SimpleToolButton, WidgetGroup
class ExampleSimpleToolButton(SimpleToolButton):
"""
Example of how to use SimpleToolButton
"""
def __init__(self, icon_path):
super().__init__(
name="example_simple",
tooltip="Example Simple ToolButton",
icon_path=f"{icon_path}/plus.svg",
icon_checked_path=f"{icon_path}/plus.svg",
hotkey=Key.L,
toggled_fn=lambda c: carb.log_warn(f"Example button toggled {c}"),
)
class ExampleToolButtonGroup(WidgetGroup):
"""
Example of how to create two ToolButton in one WidgetGroup
"""
def __init__(self, icon_path):
super().__init__()
self._icon_path = icon_path
def clean(self):
super().clean()
def get_style(self):
style = {
"Button.Image::example1": {"image_url": f"{self._icon_path}/plus.svg"},
"Button.Image::example1:checked": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::example2": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::example2:checked": {"image_url": f"{self._icon_path}/plus.svg"},
}
return style
def create(self, default_size):
def on_clicked():
# example of getting a button by name from toolbar
toolbar = omni.kit.window.toolbar.get_instance()
button = toolbar.get_widget("scale_op")
if button is not None:
button.enabled = not button.enabled
button1 = omni.ui.ToolButton(
name="example1",
tooltip="Example Button 1",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: on_clicked(),
)
button2 = omni.ui.ToolButton(
name="example2", tooltip="Example Button 2", width=default_size, height=default_size
)
# return a dictionary of name -> widget if you want to expose it to other widget_group
return {"example1": button1, "example2": button2}
class ToolbarButtonExample(omni.ext.IExt):
def on_startup(self, ext_id):
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
icon_path = os.path.join(ext_path, "icons")
self._toolbar = omni.kit.window.toolbar.get_instance()
self._widget_simple = ExampleSimpleToolButton(icon_path)
self._widget = ExampleToolButtonGroup(icon_path)
self._toolbar.add_widget(self._widget, -100)
self._toolbar.add_widget(self._widget_simple, -200)
def on_shutdown(self):
self._toolbar.remove_widget(self._widget)
self._toolbar.remove_widget(self._widget_simple)
self._widget.clean()
self._widget = None
self._widget_simple.clean()
self._widget_simple = None
self._toolbar = None
| 3,501 | Python | 33.673267 | 96 | 0.630963 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preference_builder.py | import asyncio
import os
from typing import List, Callable, Union
from typing import List, Callable, Union
import carb
import omni.kit.menu.utils
import omni.ui as ui
from omni.ui import color as cl
from functools import partial
from omni.kit.widget.settings import create_setting_widget, create_setting_widget_combo, SettingType
from omni.kit.widget.settings import get_style, get_ui_style_name
# Base class for a preference builder
class PreferenceBuilder:
WINDOW_NAME = "Preferences"
def __init__(self, title):
self._title = title
carb.settings.get_settings().set_default_string("/placeholder", "missing setting")
def __del__(self):
pass
def label(self, name: str, tooltip: str=None):
"""
Create a UI widget label.
Args:
name: Name to be in label
tooltip: The Tooltip string to be displayed when mouse hovers on the label
Returns:
:class:`ui.Widget` connected with the setting on the path specified.
"""
if tooltip:
ui.Label(name, word_wrap=True, name="title", width=ui.Percent(50), tooltip=tooltip)
else:
ui.Label(name, word_wrap=True, name="title", width=ui.Percent(50))
def create_setting_widget_combo(self, name: str, setting_path: str, list: List[str], setting_is_index=False, **kwargs) -> ui.Widget:
"""
Creating a Combo Setting widget.
This function creates a combo box that shows a provided list of names and it is connected with setting by path
specified. Underlying setting values are used from values of `items` dict.
Args:
setting_path: Path to the setting to show and edit.
items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are
actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values.
setting_is_index:
True - setting_path value is index into items list
False - setting_path value is string in items list (default)
"""
with ui.HStack(height=24):
self.label(name)
widget, model = create_setting_widget_combo(setting_path, list, setting_is_index=setting_is_index, **kwargs)
return widget
def create_setting_widget(
self, label_name: str, setting_path: str, setting_type: SettingType, **kwargs
) -> ui.Widget:
"""
Create a UI widget connected with a setting.
If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting
goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`.
Args:
setting_path: Path to the setting to show and edit.
setting_type: Type of the setting to expect.
range_from: Limit setting value lower bound.
range_to: Limit setting value upper bound.
Returns:
:class:`ui.Widget` connected with the setting on the path specified.
"""
if carb.settings.get_settings().get(setting_path) is None:
return self.create_setting_widget(label_name, "/placeholder", SettingType.STRING)
clicked_fn = None
if "clicked_fn" in kwargs:
clicked_fn = kwargs["clicked_fn"]
del kwargs["clicked_fn"]
# omni.kit.widget.settings.create_drag_or_slider won't use min/max unless hard_range is set to True
if 'range_from' in kwargs and 'range_to' in kwargs:
kwargs['hard_range'] = True
vheight = 24
vpadding = 0
if setting_type == SettingType.FLOAT or setting_type == SettingType.INT or setting_type == SettingType.STRING:
vheight = 20
vpadding = 3
with ui.HStack(height=vheight):
tooltip = kwargs.pop('tooltip', '')
self.label(label_name, tooltip)
widget, model = create_setting_widget(setting_path, setting_type, **kwargs)
if clicked_fn:
ui.Button(
style={"image_url": "resources/icons/folder.png"}, clicked_fn=partial(clicked_fn, widget), width=24
)
ui.Spacer(height=vpadding)
return widget
def add_frame(self, name: str) -> ui.CollapsableFrame:
"""
Create a UI collapsable frame.
Args:
name: Name to be in frame
Returns:
:class:`ui.Widget` connected with the setting on the path specified.
"""
return ui.CollapsableFrame(title=name, identifier=f"preferences_builder_{name}")
def spacer(self) -> ui.Spacer:
"""
Create a UI spacer.
Args:
None
Returns:
:class:`ui.Widget` connected with the setting on the path specified.
"""
return ui.Spacer(height=10)
def get_title(self) -> str:
"""
Gets the page title
Args:
None
Returns:
str name of the page
"""
return self._title
def cleanup_slashes(self, path: str, is_directory: bool = False) -> str:
"""
Makes path/slashes uniform
Args:
path: path
is_directory is path a directory, so final slash can be added
Returns:
path
"""
path = os.path.normpath(path)
if is_directory:
if path[-1] != "/":
path += "/"
return path.replace("\\", "/")
class PageItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, pages):
super().__init__()
self.name = pages[0].get_title()
self.name_model = ui.SimpleStringModel(self.name)
self.pages = pages
class PageModel(ui.AbstractItemModel):
def __init__(self, page_list: List[str]):
super().__init__()
self._pages = []
for key in page_list:
page = page_list[key]
self._pages.append(PageItem(page))
self._item_changed(None)
def get_item_children(self, item: PageItem) -> List[PageItem]:
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._pages
def get_item_value_model_count(self, item: PageItem) -> int:
"""The number of columns"""
return 1
def get_item_value_model(self, item: PageItem, column_id: int) -> ui.SimpleStringModel:
if item and isinstance(item, PageItem):
return item.name_model
class PreferenceBuilderUI:
def __init__(self, visibility_changed_fn: Callable):
self._visibility_changed_fn = visibility_changed_fn
self._active_page = ""
self._treeview = None
def destroy(self):
ui.Workspace.set_show_window_fn(PreferenceBuilder.WINDOW_NAME, None)
self._page_list = None
self._pages_model = None
self._visibility_changed_fn = None
self._treeview = None
del self._window
def __del__(self):
pass
def update_page_list(self, page_list: List) -> None:
"""
Updates page list
Args:
page_list: list of pages
Returns:
None
"""
self._page_list = {}
self._page_header = []
for page in page_list:
if isinstance(page, PreferenceBuilder):
if not page._title:
self._page_header.append(page)
elif not page._title in self._page_list:
self._page_list[page.get_title()] = [page]
else:
self._page_list[page.get_title()].append(page)
def create_window(self):
"""
Create omni.ui.window
Args:
None
Returns:
None
"""
def set_window_state(v):
self._show_window(None, v)
if v:
self.rebuild_pages()
self._treeview = None
self._window = None
ui.Workspace.set_show_window_fn(PreferenceBuilder.WINDOW_NAME, set_window_state)
def _show_window(self, menu, value):
if value:
self._window = ui.Window(PreferenceBuilder.WINDOW_NAME, width=1000, height=600, dockPreference=ui.DockPreference.LEFT_BOTTOM)
self._window.set_visibility_changed_fn(self._on_visibility_changed_fn)
self._window.frame.set_style(get_style())
self._window.deferred_dock_in("Content")
elif self._window:
self._treeview = None
self._window.destroy()
self._window = None
def rebuild_pages(self) -> None:
"""
Rebuilds window pages using current page list
Args:
None
Returns:
None
"""
self._pages_model = PageModel(self._page_list)
full_list = self._pages_model.get_item_children(None)
if not full_list or not self._window:
return
elif not self._active_page in self._page_list:
self._active_page = next(iter(self._page_list))
def treeview_clicked(treeview):
async def get_selection():
await omni.kit.app.get_app().next_update_async()
if treeview.selection:
selection = treeview.selection[0]
self.set_active_page(selection.name)
asyncio.ensure_future(get_selection())
with self._window.frame:
prefs_style = {"ScrollingFrame::header": {"background_color": 0xFF444444},
"ScrollingFrame::header:hovered": {"background_color": 0xFF444444},
"ScrollingFrame::header:pressed": {"background_color": 0xFF444444},
"Button::global": {"color": cl("#34C7FF"), "margin": 0, "margin_width": 0, "padding": 5},
"Button.Label::global": {"color": cl("#34C7FF")},
"Button::global:hovered": {"background_color": 0xFF545454},
"Button::global:pressed": {"background_color": 0xFF555555},
}
with ui.VStack(style=prefs_style, name="header"):
if self._page_header:
with ui.HStack(width=0, height=10):
for page in self._page_header:
page.build()
ui.Spacer(height=3)
with ui.HStack():
with ui.ScrollingFrame(
width=175, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF
):
if get_ui_style_name() == "NvidiaLight":
FIELD_BACKGROUND = 0xFF545454
FIELD_TEXT_COLOR = 0xFFD6D6D6
else:
FIELD_BACKGROUND = 0xFF23211F
FIELD_TEXT_COLOR = 0xFFD5D5D5
self._treeview = ui.TreeView(
self._pages_model,
root_visible=False,
header_visible=False,
style={
"TreeView.Item": {"margin": 4},
"margin_width": 0.5,
"margin_height": 0.5,
"background_color": FIELD_BACKGROUND,
"color": FIELD_TEXT_COLOR,
},
)
if not self._treeview.selection and len(full_list) > 0:
for page in full_list:
if page.name == self._active_page:
self._treeview.selection = [page]
break
selection = self._treeview.selection
self._treeview.set_mouse_released_fn(lambda x, y, b, c, tv=self._treeview: treeview_clicked(tv))
with ui.VStack():
ui.Spacer(height=7)
self._page_frame = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED
)
if selection:
self._build_page(selection[0].pages)
def set_active_page(self, page_index: Union[int, str]) -> None:
"""
Set the given page index as the active one.
Args:
page_index: Index of page of the page list to set as the active one.
Returns:
None
"""
if isinstance(page_index, str):
self._active_page = page_index
else:
for index, key in enumerate(self._page_list):
if index == page_index:
self._active_page = self._page_list[key].get_title()
break
# Build and display the list of preference widgets on the right-hand column of the panel:
async def rebuild():
await omni.kit.app.get_app().next_update_async()
self._build_page(self._page_list[self._active_page])
asyncio.ensure_future(rebuild())
# Select the title of the page on the left-hand column of the panel, acting as navigation tabs between the
# Preference pages:
if self._pages_model and self._treeview:
for page in self._pages_model.get_item_children(None):
if page.name == self._active_page:
self._treeview.selection = [page]
break
def select_page(self, page: PreferenceBuilder) -> bool:
"""
If found, display the given Preference page and select its title in the TreeView.
Args:
page: One of the page from the list of pages.
Returns:
bool: A flag indicating if the given page was successfully selected.
"""
for key in self._page_list:
items = self._page_list[key]
for item in items:
if item == page:
self.set_active_page(item.get_title())
return True
return False
def _build_page(self, pages: List[PreferenceBuilder]) -> None:
with self._page_frame:
with ui.VStack():
for page in pages:
page.build()
if len(pages) > 1:
ui.Spacer(height=7)
def show_window(self) -> None:
"""
show window
Args:
None
Returns:
None
"""
if not self._window:
self._show_window(None, True)
self.rebuild_pages()
def hide_window(self) -> None:
"""
hide window
Args:
None
Returns:
None
"""
if self._window:
self._show_window(None, False)
def _on_visibility_changed_fn(self, visible) -> None:
self._visibility_changed_fn(visible)
omni.kit.menu.utils.rebuild_menus()
| 15,348 | Python | 33.804989 | 137 | 0.537464 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/__init__.py | from .preferences_window import *
| 34 | Python | 16.499992 | 33 | 0.794118 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preferences_window.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import Callable
import asyncio
import carb
import omni.ext
from enum import IntFlag
from .preference_builder import PreferenceBuilder, PreferenceBuilderUI, SettingType
from .preferences_actions import register_actions, deregister_actions
_extension_instance = None
_preferences_page_list = []
PERSISTENT_SETTINGS_PREFIX = "/persistent"
DEVELOPER_PREFERENCE_PATH = "/app/show_developer_preference_section"
GLOBAL_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_globals"
AUDIO_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_audio"
RENDERING_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_rendering"
RESOURCE_MONITOR_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_resource_monitor"
TAGGING_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_tagging"
class PreferencesExtension(omni.ext.IExt):
class PreferencesState(IntFlag):
Invalid = 0
Created = 1
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, PreferencesExtension, lambda: _extension_instance)
self._hooks = []
self._ready_state = PreferencesExtension.PreferencesState.Invalid
self._window = PreferenceBuilderUI(self._on_visibility_changed_fn)
self._window.update_page_list(get_page_list())
self._window.create_window()
self._window_is_visible = False
self._create_menu()
self._register_pages()
self._resourcemonitor_preferences = None
manager = omni.kit.app.get_app().get_extension_manager()
if carb.settings.get_settings().get(RESOURCE_MONITOR_PREFERENCES_PATH):
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_resourcemonitor_preferences(),
on_disable_fn=lambda _: self._unregister_resourcemonitor_preferences(),
ext_name="omni.resourcemonitor",
hook_name="omni.kit.window.preferences omni.resourcemonitor listener",
)
)
# set app started trigger. refresh_menu_items & rebuild_menus won't do anything until self._ready_state is MenuState.Created
self._app_ready_sub = (
omni.kit.app.get_app()
.get_startup_event_stream()
.create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, self._rebuild_after_loading, name="omni.kit.menu.utils app started trigger"
)
)
def on_shutdown(self):
self._hooks = None
deregister_actions(self._ext_name)
self._window.destroy()
del self._window
self._window = None
self._remove_menu()
self._unregister_resourcemonitor_preferences()
for page in self._created_preferences:
unregister_page(page, rebuild=False)
self._created_preferences = None
# clear globals
global _preferences_page_list
_preferences_page_list = None
global _extension_instance
_extension_instance = None
def _rebuild_after_loading(self, event):
self._ready_state = PreferencesExtension.PreferencesState.Created
self.rebuild_pages()
def _register_pages(self):
from .pages.stage_page import StagePreferences
from .pages.rendering_page import RenderingPreferences
from .pages.screenshot_page import ScreenshotPreferences
from .pages.thumbnail_generation_page import ThumbnailGenerationPreferences
from .pages.audio_page import AudioPreferences
from .pages.tagging_page import TaggingPreferences
from .pages.datetime_format_page import DatetimeFormatPreferences
from .pages.globals import GlobalPreferences
self._developer_preferences = None
self._created_preferences = []
for page in [
ScreenshotPreferences(),
ThumbnailGenerationPreferences(),
StagePreferences(),
DatetimeFormatPreferences(),
]:
self._created_preferences.append(register_page(page))
if carb.settings.get_settings().get(GLOBAL_PREFERENCES_PATH):
self._created_preferences.append(register_page(GlobalPreferences()))
if carb.settings.get_settings().get(AUDIO_PREFERENCES_PATH):
self._created_preferences.append(register_page(AudioPreferences()))
if carb.settings.get_settings().get(RENDERING_PREFERENCES_PATH):
self._created_preferences.append(register_page(RenderingPreferences()))
if carb.settings.get_settings().get(TAGGING_PREFERENCES_PATH):
self._created_preferences.append(register_page(TaggingPreferences()))
# developer options
self._hooks.append(carb.settings.get_settings().subscribe_to_node_change_events(
DEVELOPER_PREFERENCE_PATH, self._on_developer_preference_section_changed
))
self._on_developer_preference_section_changed(None, None)
def _on_developer_preference_section_changed(self, item, event_type):
if event_type == carb.settings.ChangeEventType.CHANGED:
if carb.settings.get_settings().get(DEVELOPER_PREFERENCE_PATH):
if not self._developer_preferences:
from .pages.developer_page import DeveloperPreferences
self._developer_preferences = register_page(DeveloperPreferences())
elif self._developer_preferences:
self._developer_preferences = unregister_page(self._developer_preferences)
def _register_resourcemonitor_preferences(self):
from .pages.resourcemonitor_page import ResourceMonitorPreferences
self._resourcemonitor_preferences = register_page(ResourceMonitorPreferences())
def _unregister_resourcemonitor_preferences(self):
if self._resourcemonitor_preferences:
unregister_page(self._resourcemonitor_preferences)
self._resourcemonitor_preferences = None
def rebuild_pages(self):
if self._ready_state == PreferencesExtension.PreferencesState.Invalid:
return
if self._window:
self._window.update_page_list(get_page_list())
self._window.rebuild_pages()
def select_page(self, page):
if self._window:
if self._window.select_page(page):
return True
return False
async def _refresh_menu_async(self):
omni.kit.menu.utils.refresh_menu_items("Edit")
self._refresh_menu_task = None
def _on_visibility_changed_fn(self, visible):
self._window_is_visible = visible
if visible:
self._window.show_window()
else:
self._window.hide_window()
def _create_menu(self):
from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder
self._edit_menu_list = None
self._refresh_menu_task = None
self._edit_menu_list = [
MenuItemDescription(
name="Preferences",
glyph="cog.svg",
appear_after=["Capture Screenshot", MenuItemOrder.LAST],
ticked=True,
ticked_fn=lambda: self._window_is_visible,
onclick_action=("omni.kit.window.preferences", "toggle_preferences_window"),
),
MenuItemDescription(
appear_after=["Capture Screenshot", MenuItemOrder.LAST],
),
]
omni.kit.menu.utils.add_menu_items(self._edit_menu_list, "Edit", -9)
def _remove_menu(self):
if self._refresh_menu_task:
self._refresh_menu_task.cancel()
self._refresh_menu_task = None
# remove menu
omni.kit.menu.utils.remove_menu_items(self._edit_menu_list, "Edit")
def _toggle_preferences_window(self):
self._window_is_visible = not self._window_is_visible
async def show_windows():
if self._window_is_visible:
self._window.show_window()
else:
self._window.hide_window()
asyncio.ensure_future(show_windows())
asyncio.ensure_future(self._refresh_menu_async())
def show_preferences_window(self):
"""Show the Preferences window to the User."""
if not self._window_is_visible:
self._toggle_preferences_window()
def hide_preferences_window(self):
"""Hide the Preferences window from the User."""
if self._window_is_visible:
self._toggle_preferences_window()
def get_instance():
global _extension_instance
return _extension_instance
def show_preferences_window():
"""Show the Preferences window to the User."""
get_instance().show_preferences_window()
def hide_preferences_window():
"""Hide the Preferences window from the User."""
get_instance().hide_preferences_window()
def get_page_list():
global _preferences_page_list
return _preferences_page_list
def register_page(page):
global _preferences_page_list
_preferences_page_list.append(page)
_preferences_page_list = sorted(_preferences_page_list, key=lambda page: page._title)
get_instance().rebuild_pages()
return page
def select_page(page):
return get_instance().select_page(page)
def rebuild_pages():
get_instance().rebuild_pages()
def unregister_page(page, rebuild: bool=True):
global _preferences_page_list
if hasattr(page, 'destroy'):
page.destroy()
# Explicitly clear properties, that helps to release some C++ objects
page.__dict__.clear()
if _preferences_page_list:
_preferences_page_list.remove(page)
preferences = get_instance()
if preferences and rebuild:
preferences.rebuild_pages()
def show_file_importer(
title: str,
file_exts: list = [("All Files(*)", "")],
filename_url: str = None,
click_apply_fn: Callable = None,
show_only_folders: bool = False,
):
from functools import partial
from omni.kit.window.file_importer import get_file_importer
def on_import(click_fn: Callable, filename: str, dirname: str, selections=[]):
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = f"{dirname}{filename}"
if click_fn:
click_fn(fullpath)
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title=title,
import_button_label="Select",
import_handler=partial(on_import, click_apply_fn),
file_extension_types=file_exts,
filename_url=filename_url,
# OM-96626: Add show_only_folders option to file importer
show_only_folders=show_only_folders,
)
| 11,373 | Python | 35.107936 | 132 | 0.652686 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_config_widget.py | import os
import carb.settings
import omni.kit.notification_manager as nm
import omni.ui as ui
from omni.ui import color as cl
from . import material_config_utils
class EditableListItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
class EditableListItemDelegate(ui.AbstractItemDelegate):
_ITEM_LABEL_STYLE = {
"margin": 3,
"font_size": 16.0,
":selected": {
"color": cl("#333333")
}
}
_DELETE_BUTTON_STYLE = {
"margin": 2,
"padding": 0,
"": {
"image_url": "",
"alignment": ui.Alignment.CENTER,
"background_color": 0x00000000
},
":hovered": {
"image_url": "resources/glyphs/trash.svg",
"color": cl("#cccccc"),
"background_color": 0x00000000
},
":selected": {
"image_url": "resources/glyphs/trash.svg",
"color": cl("#cccccc"),
"background_color": 0x00000000
}
}
def build_widget(self, model, item, column_id, level, expanded):
with ui.ZStack(height=20):
value_model = model.get_item_value_model(item, column_id)
if column_id == 0:
# entry text
label = ui.Label(value_model.as_string, style=self._ITEM_LABEL_STYLE)
field = ui.StringField()
field.model = value_model
field.visible = False
label.set_mouse_double_clicked_fn(
lambda x, y, b, m, f=field, l=label: self.on_label_double_click(b, f, l)
)
elif column_id == 1:
# remove button
with ui.HStack():
ui.Spacer()
button = ui.Button(width=20, style=self._DELETE_BUTTON_STYLE)
button.set_clicked_fn(lambda i=item, m=model: self.on_button_clicked(i, m))
ui.Spacer(width=5)
else:
pass
def on_label_double_click(self, mouse_button, field, label):
if mouse_button != 0:
return
field.visible = True
field.focus_keyboard()
self.subscription = field.model.subscribe_end_edit_fn(
lambda m, f=field, l=label: self.on_field_end_edit(m, f, l)
)
def on_field_end_edit(self, model, field, label):
field.visible = False
if model.as_string: # avoid empty string
label.text = model.as_string
self.subscription = None
def on_button_clicked(self, item, model):
model.remove_item(item)
class EditableListModel(ui.AbstractItemModel):
def __init__(
self,
item_class=EditableListItem,
setting_path=None
):
super().__init__()
self._settings = carb.settings.get_settings()
self._setting_path = setting_path
self._item_class = item_class
self._items = []
self.populate_items()
def populate_items(self):
entries = self._settings.get(self._setting_path)
if not entries:
entries = []
self._items.clear()
for entry in entries:
if not entry:
continue
self._items.append(self._item_class(entry))
self._item_changed(None)
def get_item_children(self, item):
if item is not None:
return []
return self._items
def get_item_value_model_count(self, item):
return 2
def get_item_value_model(self, item, column_id):
if item and isinstance(item, self._item_class):
if column_id == 0:
return item.name_model
else:
return None
def get_drag_mime_data(self, item):
return item.name_model.as_string
def drop_accepted(self, target_item, source, drop_location=1):
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
try:
source_id = self._items.index(source)
except ValueError:
return
if source_id == drop_location:
return
self._items.remove(source)
if drop_location > len(self._items):
self._items.append(source)
else:
if source_id < drop_location:
drop_location = drop_location - 1
self._items.insert(drop_location, source)
self._item_changed(None)
def add_entry(self, text):
self._items.insert(0, self._item_class(text))
self._item_changed(None)
def remove_item(self, item):
self._items.remove(item)
self._item_changed(None)
def save_entries_to_settings(self):
entries = [item.name_model.as_string for item in self._items]
self._settings.set(self._setting_path, entries)
def save_to_material_config_file(self):
material_config_utils.save_live_config_to_file()
class EditableListWidget(ui.Widget):
_ADD_BUTTON_STYLE = {
"image_url": "resources/glyphs/plus.svg",
"color": cl("#cccccc")
}
def __init__(
self,
model_class=EditableListModel,
item_delegate_class=EditableListItemDelegate,
setting_path=None,
list_height=100
):
super(EditableListWidget).__init__()
self._model = model_class(setting_path=setting_path)
self._delegate = item_delegate_class()
# build UI
with ui.VStack():
with ui.HStack():
# list widget
with ui.ScrollingFrame(height=list_height):
ui.Spacer(height=5)
self._view = ui.TreeView(
self._model,
delegate=self._delegate,
header_visible=False,
root_visible=False,
column_widths=[ui.Percent(95)],
drop_between_items=True
)
self._view.set_selection_changed_fn(self.on_item_selection_changed)
ui.Spacer(width=5)
# "+" button
self._add_new_entry_button = ui.Button(
width=20,
height=20,
style=self._ADD_BUTTON_STYLE,
clicked_fn=self.on_add_new_entry_button_clicked
)
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer()
# save button
self._save_button = ui.Button(
"Save",
width=100,
height=0,
clicked_fn=self.on_save_button_clicked
)
ui.Spacer(width=5)
# reset button
self._reset_button = ui.Button(
"Reset",
width=100,
height=0,
clicked_fn=self.on_reset_button_clicked
)
ui.Spacer(width=25)
def on_add_new_entry_button_clicked(self):
self._view.clear_selection()
self._model.add_entry("New Entry")
def on_item_selection_changed(self, items):
# not to allow multi-selection
num_items = len(items)
if num_items > 1:
for i in range(1, num_items):
self._view.toggle_selection(items[i])
def on_save_button_clicked(self):
self._model.save_entries_to_settings()
config_file = material_config_utils.get_config_file_path()
if not os.path.exists(config_file):
ok_button = nm.NotificationButtonInfo(
"OK",
on_complete=self._model.save_to_material_config_file
)
cancel_button = nm.NotificationButtonInfo(
"Cancel",
on_complete=None
)
nm.post_notification(
f"Material config file does not exist. Create?\n\n{config_file}",
status=nm.NotificationStatus.INFO,
button_infos=[ok_button, cancel_button],
hide_after_timeout=False
)
else:
self._model.save_to_material_config_file()
def on_reset_button_clicked(self):
self._view.clear_selection()
self._model.populate_items()
| 8,497 | Python | 29.134752 | 95 | 0.520184 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/preferences_actions.py | import omni.kit.actions.core
def register_actions(extension_id, cls, get_self_fn):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Window Preferences Actions"
# actions
action_registry.register_action(
extension_id,
"show_preferences_window",
get_self_fn().show_preferences_window,
display_name="Show Preferences Window",
description="Show Preferences Window",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"hide_preferences_window",
get_self_fn().hide_preferences_window,
display_name="Hide Preferences Window",
description="Hide Preferences Window",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_preferences_window",
get_self_fn()._toggle_preferences_window,
display_name="Toggle Preferences Window",
description="Toggle Preferences Window",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 1,202 | Python | 29.074999 | 70 | 0.666389 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_path_widget.py | import os
import pathlib
import carb
import carb.settings
import omni.kit.notification_manager as nm
import omni.ui as ui
from omni.kit.window.filepicker import FilePickerDialog
from omni.mdl import pymdlsdk
from omni.ui import color as cl
from . import material_config_utils
from . material_config_widget import EditableListItemDelegate, EditableListModel, EditableListWidget
class MdlPathItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
text = pathlib.PurePath(text).as_posix()
self.name_model = ui.SimpleStringModel(text)
class MdlDefaultPathListModel(ui.AbstractItemModel):
SOURCE_MDL_SYSTEM_PATH = 0
SOURCE_MDL_USER_PATH = 1
SOURCE_ADDITIONAL_SYSTEM_PATHS = 2
SOURCE_ADDITIONAL_USER_PATHS = 3
SOURCE_RENDERER_REQUIRED = 4
SOURCE_RENDERER_TEMPLATES = 5
def __init__(self, mode):
super().__init__()
self._SETTING_NAME_MAP = {
self.SOURCE_ADDITIONAL_SYSTEM_PATHS: "/app/mdl/additionalSystemPaths",
self.SOURCE_ADDITIONAL_USER_PATHS: "/app/mdl/additionalUserPaths",
self.SOURCE_RENDERER_REQUIRED: "/renderer/mdl/searchPaths/required",
self.SOURCE_RENDERER_TEMPLATES: "/renderer/mdl/searchPaths/templates"
}
_FN_MAP = {
self.SOURCE_MDL_SYSTEM_PATH: self._get_paths_from_mdl_config,
self.SOURCE_MDL_USER_PATH: self._get_paths_from_mdl_config,
self.SOURCE_ADDITIONAL_SYSTEM_PATHS: self._get_paths_from_setting,
self.SOURCE_ADDITIONAL_USER_PATHS: self._get_paths_from_setting,
self.SOURCE_RENDERER_REQUIRED: self._get_paths_from_setting,
self.SOURCE_RENDERER_TEMPLATES: self._get_paths_from_setting
}
self._items = []
paths = _FN_MAP[mode](mode)
for path in paths:
self._items.append(MdlPathItem(path))
def _get_omni_neuray_api(self):
import omni.mdl.neuraylib
neuraylib = omni.mdl.neuraylib.get_neuraylib()
ineuray = neuraylib.getNeurayAPI()
neuray = pymdlsdk.attach_ineuray(ineuray)
return neuray
def _get_paths_from_mdl_config(self, mode):
neuray = self._get_omni_neuray_api()
paths = []
with neuray.get_api_component(pymdlsdk.IMdl_configuration) as cfg:
if mode == self.SOURCE_MDL_SYSTEM_PATH:
num_paths = cfg.get_mdl_system_paths_length()
if num_paths:
for i in range(0, num_paths):
paths.append(cfg.get_mdl_system_path(i))
elif mode == self.SOURCE_MDL_USER_PATH:
num_paths = cfg.get_mdl_user_paths_length()
if num_paths:
for i in range(0, num_paths):
paths.append(cfg.get_mdl_user_path(i))
else:
pass
return paths
def _get_paths_from_setting(self, mode):
settings = carb.settings.get_settings()
pathStr = settings.get(self._SETTING_NAME_MAP[mode])
paths = []
if pathStr:
paths = pathStr.split(";")
return paths
def get_item_children(self, item):
if item is not None:
return []
return self._items
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
if item and isinstance(item, MdlPathItem):
return item.name_model
def get_items(self):
return self._items
class MdlDefaultPathListWidget(ui.Widget):
_TREEVIEW_STYLE = {
"TreeView.Item": {
"margin": 3,
"font_size": 16.0,
"color": cl("#777777")
}
}
_FRAME_STYLE = {
"CollapsableFrame": {
"margin": 0,
"padding": 3,
"border_width": 0,
"border_radius": 0,
"secondary_color": cl("#2c2e2e")
}
}
def __init__(self, **kwargs):
super(MdlDefaultPathListWidget).__init__()
self._models = {}
entries = [
["Standard System Paths", MdlDefaultPathListModel.SOURCE_MDL_SYSTEM_PATH],
["Additional System Paths", MdlDefaultPathListModel.SOURCE_ADDITIONAL_SYSTEM_PATHS],
["Standard User Paths", MdlDefaultPathListModel.SOURCE_MDL_USER_PATH],
["Additional User Paths", MdlDefaultPathListModel.SOURCE_ADDITIONAL_USER_PATHS],
["Renderer Required", MdlDefaultPathListModel.SOURCE_RENDERER_REQUIRED],
["Renderer Templates", MdlDefaultPathListModel.SOURCE_RENDERER_TEMPLATES]
]
with ui.VStack(height=0):
for entry in entries:
model = MdlDefaultPathListModel(entry[1])
if not model.get_items():
continue # do not add widget if it is empty
self._add_path_list_widget(entry[0], model)
self._models[entry[1]] = model
def _add_path_list_widget(self, title, model):
with ui.CollapsableFrame(title, collapsed=True, style=self._FRAME_STYLE):
with ui.ScrollingFrame(height=100):
view = ui.TreeView(
model,
header_visible=False,
root_visible=False,
style=self._TREEVIEW_STYLE
)
# do not allow select items
view.set_selection_changed_fn(lambda i: view.clear_selection())
class MdlLocalPathListModel(EditableListModel):
def __init__(self, setting_path):
super().__init__(
MdlPathItem,
setting_path
)
def populate_items(self):
pathStr = self._settings.get(self._setting_path)
paths = pathStr.split(";") if pathStr else []
self._items.clear()
for path in paths:
if not path:
continue
self._items.append(self._item_class(path))
self._item_changed(None)
def find_path(self, path):
pp = pathlib.PurePath(path)
for item in self._items:
ip = pathlib.PurePath(item.name_model.as_string)
if pp == ip:
return ip.as_posix()
return ""
def sanity_check_paths(self):
bad_paths = []
for item in self._items:
path = item.name_model.as_string
if not os.path.exists(path):
bad_paths.append(path)
return bad_paths
def save_entries_to_settings(self):
pathStrs = [item.name_model.as_string for item in self._items]
pathStr = ";".join(pathStrs)
self._settings.set(self._setting_path, pathStr)
def save_to_material_config_file(self):
material_config_utils.save_carb_setting_to_config_file(
"/app/mdl/nostdpath",
"/options/noStandardPath"
)
material_config_utils.save_carb_setting_to_config_file(
self._setting_path,
"/searchPaths/local",
is_paths=True
)
class MdlLocalPathListWidget(EditableListWidget):
def __init__(self):
super().__init__(
MdlLocalPathListModel,
EditableListItemDelegate,
"/renderer/mdl/searchPaths/local",
150
)
self._file_picker_selection = None
self._file_picker = FilePickerDialog(
"Add New Search Path",
allow_multi_selection=False,
apply_button_label="Select",
selection_changed_fn=self.on_file_picker_selection_changed,
click_apply_handler=lambda f, d: self.on_file_picker_apply_clicked(),
click_cancel_handler=None
)
self._file_picker.hide()
def on_file_picker_selection_changed(self, items):
# this is a workaround for that FilePickerDialog has a bug that
# the selection does not get updated if user select a directory
if items:
self._file_picker_selection = items[0].path
def on_file_picker_apply_clicked(self):
if self._model.find_path(self._file_picker_selection):
nm.post_notification(
"Path already exists in the list.",
status=nm.NotificationStatus.INFO,
hide_after_timeout=False
)
return
self._model.add_entry(self._file_picker_selection)
self._file_picker.hide()
def on_add_new_entry_button_clicked(self):
self._view.clear_selection()
self._file_picker.show()
def on_save_button_clicked(self):
bad_paths = self._model.sanity_check_paths()
if bad_paths:
paths = "\n".join(bad_paths)
ok_button = nm.NotificationButtonInfo(
"OK",
on_complete=lambda: self.save_settings_and_config_file()
)
cancel_button = nm.NotificationButtonInfo(
"Cancel",
on_complete=None
)
nm.post_notification(
f"Path(s) below do not exist. Continue?\n\n{paths}",
status=nm.NotificationStatus.WARNING,
button_infos=[ok_button, cancel_button],
hide_after_timeout=False
)
else:
self.save_settings_and_config_file()
def save_settings_and_config_file(self):
self._model.save_entries_to_settings()
config_file = material_config_utils.get_config_file_path()
if not os.path.exists(config_file):
ok_button = nm.NotificationButtonInfo(
"OK",
on_complete=self._model.save_to_material_config_file
)
cancel_button = nm.NotificationButtonInfo(
"Cancel",
on_complete=None
)
nm.post_notification(
f"Material config file does not exist. Create?\n\n{config_file}",
status=nm.NotificationStatus.INFO,
button_infos=[ok_button, cancel_button],
hide_after_timeout=False
)
else:
self._model.save_to_material_config_file()
carb.log_info(f"Material config file saved: {config_file}")
| 10,259 | Python | 32.420195 | 100 | 0.573253 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/material_config_utils.py | import os
import posixpath
# import platform
import pathlib
import copy
import toml
import carb
import carb.settings
SETTING_BUILTINALLOWLIST = "/materialConfig/materialGraph/builtInAllowList"
SETTING_BUILTINBLOCKLIST = "/materialConfig/materialGraph/builtInBlockList"
SETTING_USERALLOWLIST = "/materialConfig/materialGraph/userAllowList"
SETTING_USERBLOCKLIST = "/materialConfig/materialGraph/userBlockList"
def _key_value_to_dict(key, value):
# "/path/to/key", <value> -> {"path": {"to": {"key": <value>}}}
tokens = key.split('/')
tokens = list(filter(None, tokens)) # filter empty strings
dct = value
for token in reversed(tokens):
dct = {token: dct}
return dct
def _merge_dict(dict1, dict2):
merged = copy.deepcopy(dict1)
for k2, v2 in dict2.items():
v1 = merged.get(k2)
if isinstance(v1, dict) and isinstance(v2, dict):
merged[k2] = _merge_dict(v1, v2)
else:
merged[k2] = copy.deepcopy(v2)
return merged
def get_default_config_file_path():
try:
home_dir = pathlib.Path.home()
except Exception as e:
carb.log_error(str(e))
return ""
config_file_path = home_dir / "Documents/Kit/shared" / "material.config.toml"
config_file_path = config_file_path.as_posix()
return str(config_file_path)
def get_config_file_path():
settings = carb.settings.get_settings()
file_path = settings.get('/materialConfig/configFilePath')
if not file_path or not os.path.exists(file_path):
file_path = get_default_config_file_path()
return file_path
def load_config_file(file_path):
config = {}
try:
if os.path.exists(file_path):
config = toml.load(file_path)
except Exception as e:
carb.log_error(str(e))
return config
def save_config_file(config, file_path):
# this setting should not be saved in file
config.pop("configFilePath", None)
try:
toml_str = toml.dumps(config)
# least prettify format
toml_str = toml_str.replace(",", ",\n")
toml_str = toml_str.replace("[ ", "[\n ")
with open(file_path, "w") as f:
f.write(toml_str)
except Exception as e:
carb.log_error(str(e))
return False
return True
def save_carb_setting_to_config_file(carb_setting_key, config_key, is_paths=False, non_standard_path=None):
try:
# get value from carb setting
settings = carb.settings.get_settings()
value = settings.get(carb_setting_key)
if is_paths:
value = value.split(";") if value else []
value = list(filter(None, value)) # remove empty strings
# load config from file
file_path = pathlib.Path(non_standard_path if non_standard_path else get_config_file_path())
if not file_path.exists():
file_path.touch()
config = load_config_file(file_path)
# deep merge configs
new_config = _key_value_to_dict(config_key, value)
merged_config = _merge_dict(config, new_config)
# save config to file
save_config_file(merged_config, file_path)
except Exception as e:
carb.log_error(str(e))
return False
return True
def save_live_config_to_file(non_standard_path=None):
try:
# get live material config from carb setting
settings = carb.settings.get_settings()
live_config = settings.get("/materialConfig")
# save config to file
file_path = pathlib.Path(non_standard_path if non_standard_path else get_config_file_path())
save_config_file(live_config, file_path)
except Exception as e:
carb.log_error(str(e))
return False
return True
| 3,771 | Python | 25.194444 | 107 | 0.631132 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/screenshot_page.py | import os
import carb.settings
import omni.ui as ui
from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType
class ScreenshotPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Capture Screenshot")
self._settings = carb.settings.get_settings()
# setup captureFrame paths
template_path = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path")
if template_path is None or template_path == "./":
template_path = self._settings.get("/app/captureFrame/path")
if template_path[-1] != "/":
template_path += "/"
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", template_path)
# 3D viewport
self._settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/viewport", False)
# ansel defaults
if self._is_ansel_enabled():
ansel_quality_path = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/quality"
self._settings.set_default_string(ansel_quality_path, "Medium")
ansel_super_resolution_size_path = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/superResolution/size"
self._settings.set_default_string(ansel_super_resolution_size_path, "2x")
# create captureFrame directory
original_umask = os.umask(0)
if not os.path.isdir(template_path):
try:
os.makedirs(template_path)
except Exception:
carb.log_error(f"Failed to create directory {template_path}")
os.umask(original_umask)
def build(self):
""" Capture Screenshot """
# The path widget. It's not standard because it has the button browse. Since the main layout has two columns,
# we need to create another layout and put it to the main one.
with ui.VStack(height=0):
with self.add_frame("Capture Screenshot"):
with ui.VStack():
self._settings_widget = self.create_setting_widget(
"Path to save screenshots",
PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path",
SettingType.STRING,
clicked_fn=self._on_browse_button_fn,
)
self.create_setting_widget(
"Capture only the 3D viewport",
PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/viewport",
SettingType.BOOL,
)
# Show Ansel super resolution configuration, only when Ansel enabled
self._create_ansel_super_resolution_settings()
def _add_ansel_settings(self):
# check if Ansel enabled. If not, do not show Ansel settings
if not self._is_ansel_enabled():
return
self.create_setting_widget_combo(
"Quality", PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/quality", ["Low", "Medium", "High"]
)
def _create_ansel_super_resolution_settings(self):
# check if Ansel enabled. If not, do not show Ansel settings
if not self._is_ansel_enabled():
return
self.spacer()
with self.add_frame("Super Resolution"):
with ui.VStack():
self.create_setting_widget_combo(
"Size",
PERSISTENT_SETTINGS_PREFIX + "/exts/omni.ansel/superResolution/size",
["2x", "4x", "8x", "16x", "32x"],
)
self._add_ansel_settings()
def _is_ansel_enabled(self):
return self._settings.get("/exts/omni.ansel/enable")
def _on_browse_button_fn(self, owner):
""" Called when the user picks the Browse button. """
navigate_to = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path")
show_file_importer("Select Screenshot Directory", click_apply_fn=self._on_dir_pick, filename_url=navigate_to,
show_only_folders=True)
def _on_dir_pick(self, real_path):
""" Called when the user accepts directory in the Select Directory dialog. """
directory = self.cleanup_slashes(real_path, is_directory=True)
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/captureFrame/path", directory)
self._settings_widget.model.set_value(directory)
| 4,486 | Python | 42.990196 | 117 | 0.596745 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/globals.py | import asyncio
import carb.settings
import omni.kit.app
import omni.ui as ui
from ..preferences_window import PreferenceBuilder
class GlobalPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("")
def build(self):
async def on_ok_clicked(dialog):
import sys
import carb.events
import omni.kit.app
dialog.hide()
def run_process(args):
import subprocess
import platform
kwargs = {"close_fds": False}
if platform.system().lower() == "windows":
kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP
subprocess.Popen(args, **kwargs) # pylint: disable=consider-using-with
def on_event(e: carb.events.IEvent):
if e.type == omni.kit.app.PRE_SHUTDOWN_EVENT_TYPE:
run_process(sys.argv + ["--reset-user"])
self._shutdown_sub = omni.kit.app.get_app().get_shutdown_event_stream().create_subscription_to_pop(on_event, name="preferences re-start", order=0)
await omni.kit.app.get_app().next_update_async()
omni.kit.app.get_app().post_quit()
def reset_clicked():
from omni.kit.window.popup_dialog import MessageDialog
if omni.usd.get_context().has_pending_edit():
dialog = MessageDialog(
title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings",
width=400,
message=f"This application will restart to remove all custom settings and restore the application to the installed state.\n\nYou will be prompted to save any unsaved changes.",
ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)),
ok_label="Continue",
cancel_label="Cancel",
)
else:
dialog = MessageDialog(
title= f"{omni.kit.ui.get_custom_glyph_code('${glyphs}/exclamation.svg')} Reset to Default Settings",
width=400,
message=f"This application will restart to remove all custom settings and restore the application to the installed state.",
ok_handler=lambda dialog: asyncio.ensure_future(on_ok_clicked(dialog)),
ok_label="Restart",
cancel_label="Cancel",
)
dialog.show()
ui.Button("Reset to Default", clicked_fn=reset_clicked, name="global", tooltip="This will reset all settings back to the installed state after the application is restarted")
def __del__(self):
super().__del__()
| 2,806 | Python | 42.859374 | 196 | 0.581254 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/thumbnail_generation_page.py | import carb.settings
import omni.ui as ui
from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType
MDL_PREFERENCES_PATH = "/exts/omni.kit.window.preferences/show_thumbnail_generation_mdl"
def set_default_usd_thumbnail_generator_settings():
"""Setup default value for the setting of the USD Thumbnail Generator"""
settings = carb.settings.get_settings()
settings.set_default_int("/app/thumbnailsGenerator/usd/width", 256)
settings.set_default_int("/app/thumbnailsGenerator/usd/height", 256)
settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/renderer", "RayTracing")
settings.set_default_int(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/iterations", 8)
settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.thumbnails.usd/thumbnail_on_save", True)
def set_default_mdl_thumbnail_generator_settings():
"""Setup default value for the setting of the MDL Thumbnail Generator"""
settings = carb.settings.get_settings()
settings.set_default_int("/app/thumbnailsGenerator/mdl/width", 256)
settings.set_default_int("/app/thumbnailsGenerator/mdl/height", 256)
settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/renderer", "PathTracing")
settings.set_default_int(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/iterations", 512)
template_url = "/Library/AEC/Materials/Library_Default.thumbnail.usd"
settings.set_default_string(
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", template_url
)
settings.set_default_string(
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/standin_usd_path", "/Stage/ShaderKnob"
)
class ThumbnailGenerationPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Thumbnail Generation")
self._settings = carb.settings.get_settings()
# default_settings
set_default_usd_thumbnail_generator_settings()
set_default_mdl_thumbnail_generator_settings()
def build(self):
"""Thumbnail Generation"""
with ui.VStack(height=0):
if carb.settings.get_settings().get(MDL_PREFERENCES_PATH):
with self.add_frame("MDL Thumbnail Generation Settings"):
with ui.VStack():
self._settings_widget = self.create_setting_widget(
"Path usd template to render MDL Thumnail",
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path",
SettingType.STRING,
clicked_fn=self._on_browse_button_fn,
)
self.create_setting_widget(
"Name of the standin Prim",
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/standin_usd_path",
SettingType.STRING,
)
self.create_setting_widget_combo(
"Renderer Type",
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/renderer",
["RayTracing", "PathTracing"],
)
self.create_setting_widget(
"Rendering Samples",
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/iterations",
SettingType.INT,
)
self.spacer()
with self.add_frame("USD Thumbnail Generation Settings"):
with ui.VStack():
self.create_setting_widget_combo(
"Renderer Type",
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/renderer",
["RayTracing", "PathTracing"],
)
self.create_setting_widget(
"Rendering Samples",
PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/usd/iterations",
SettingType.INT,
)
self.create_setting_widget(
"Save usd thumbnail on save",
PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.thumbnails.usd/thumbnail_on_save",
SettingType.BOOL,
)
def _on_browse_button_fn(self, owner):
"""Called when the user picks the Browse button."""
path = self._settings_widget.model.get_value_as_string()
show_file_importer(title="Select Template", click_apply_fn=self._on_file_pick, filename_url=path)
def _on_file_pick(self, full_path):
"""Called when the user accepts directory in the Select Directory dialog."""
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/thumbnailsGenerator/mdl/usd_template_path", full_path)
self._settings_widget.model.set_value(full_path)
| 5,142 | Python | 48.932038 | 116 | 0.6021 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/usdskel_page.py | import carb.settings
import omni.kit.app
from functools import partial
from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType
class UsdSkelPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("UsdSkel")
self._update_setting = {}
settings = carb.settings.get_settings()
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter") is None:
settings.set_default_bool(
PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape") is None:
settings.set_default_bool(
PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", True
)
def build(self):
import omni.ui as ui
with ui.VStack(height=0):
with self.add_frame("UsdSkel"):
with ui.VStack():
self.create_setting_widget(
"Enable BlendShape",
PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape",
SettingType.BOOL,
tooltip="Enable BlendShape. Will be effective on the next stage load.",
)
def _on_enable_blendshape_change(item, event_type, owner):
if event_type == carb.settings.ChangeEventType.CHANGED:
settings = carb.settings.get_settings()
if settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape"):
if not settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter"):
settings.set_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True)
self._update_setting["Enable BlendShape"] = omni.kit.app.SettingChangeSubscription(
PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape",
partial(_on_enable_blendshape_change, owner=self),
)
def __del__(self):
super().__del__()
self._update_setting = {}
| 2,310 | Python | 40.267856 | 120 | 0.577056 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/material_page.py | import carb.settings
import omni.kit.app
import omni.ui as ui
from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType
from ..material_config_utils import SETTING_USERALLOWLIST, SETTING_USERBLOCKLIST
from ..material_config_widget import EditableListWidget
from ..material_path_widget import MdlDefaultPathListWidget
from ..material_path_widget import MdlLocalPathListWidget
class MaterialPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Material")
settings = carb.settings.get_settings()
self._sub_render_context = omni.kit.app.SettingChangeSubscription(
PERSISTENT_SETTINGS_PREFIX + "/app/hydra/material/renderContext", self._on_render_context_changed
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath") is None:
settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "Relative")
if settings.get("/app/mdl/nostdpath") is None:
settings.set_default_bool("/app/mdl/nostdpath", False)
PreferenceBuilder.__init__(self, "Material")
def build(self):
""" Material """
with ui.VStack(height=0):
""" Material """
with self.add_frame("Material"):
with ui.VStack():
self.create_setting_widget_combo(
"Binding Strength",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/materialStrength",
["weakerThanDescendants", "strongerThanDescendants"],
)
self.create_setting_widget_combo(
"Drag/Drop Path",
PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath",
["Absolute", "Relative"],
)
self.create_setting_widget_combo(
"Render Context / Material Network (Requires Stage Reload)",
PERSISTENT_SETTINGS_PREFIX + "/app/hydra/material/renderContext",
{"default": "", "mdl": "mdl"},
)
self.spacer()
""" Material Search Path """
with self.add_frame("Material Search Path"):
with ui.VStack(height=0):
""" Default Paths """
default_path_frame = self.add_frame("Default Paths")
# default_path_frame.collapsed = True
default_path_frame.collapsed = False
with default_path_frame:
with ui.VStack():
self.create_setting_widget(
"Ignore Standard Paths",
"/app/mdl/nostdpath",
SettingType.BOOL
)
self.spacer()
with ui.HStack():
ui.Spacer(width=5)
self._mdl_default_paths = MdlDefaultPathListWidget()
self.spacer()
""" Local Paths """
with self.add_frame("Local Paths"):
self._mdl_local_paths = MdlLocalPathListWidget()
self.spacer()
""" Material Graph """
if self._isExtensionEnabled("omni.kit.window.material_graph"):
with self.add_frame("Material Graph"):
with ui.VStack(height=0):
""" User Allow List """
user_allow_list_frame = self.add_frame("User Allow List")
with user_allow_list_frame:
self._user_allow_list_widget = EditableListWidget(setting_path=SETTING_USERALLOWLIST)
self.spacer()
""" User Block List """
user_block_list_frame = self.add_frame("User Block List")
with user_block_list_frame:
self._user_block_list_widget = EditableListWidget(setting_path=SETTING_USERBLOCKLIST)
def _isExtensionEnabled(self, name):
manager = omni.kit.app.get_app().get_extension_manager()
for ext in manager.get_extensions():
if ext["name"] == name and ext["enabled"] == True:
return True
return False
def _on_render_context_changed(self, value: str, event_type: carb.settings.ChangeEventType):
import omni.usd
if event_type == carb.settings.ChangeEventType.CHANGED:
stage = omni.usd.get_context().get_stage()
if not stage or stage.GetRootLayer().anonymous:
return
msg = "Material render context has been changed. You will need to reload your stage for this to take effect."
try:
import asyncio
import omni.kit.notification_manager
import omni.kit.app
async def show_msg():
await omni.kit.app.get_app().next_update_async()
omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False)
asyncio.ensure_future(show_msg())
except:
carb.log_warn(msg)
| 5,435 | Python | 42.488 | 121 | 0.529899 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/resourcemonitor_page.py | import omni.ui as ui
from ..preferences_window import PreferenceBuilder, SettingType
class ResourceMonitorPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Resource Monitor")
def build(self):
""" Resource Monitor """
try:
import omni.resourcemonitor as rm
with ui.VStack(height=0):
with self.add_frame("Resource Monitor"):
with ui.VStack():
self.create_setting_widget(
"Time Between Queries",
rm.timeBetweenQueriesSettingName,
SettingType.FLOAT,
)
self.create_setting_widget(
"Send Device Memory Warnings",
rm.sendDeviceMemoryWarningSettingName,
SettingType.BOOL,
)
self.create_setting_widget(
"Device Memory Warning Threshold (MB)",
rm.deviceMemoryWarnMBSettingName,
SettingType.INT,
)
self.create_setting_widget(
"Device Memory Warning Threshold (Fraction)",
rm.deviceMemoryWarnFractionSettingName,
SettingType.FLOAT,
range_from=0.,
range_to=1.,
)
self.create_setting_widget(
"Send Host Memory Warnings",
rm.sendHostMemoryWarningSettingName,
SettingType.BOOL
)
self.create_setting_widget(
"Host Memory Warning Threshold (MB)",
rm.hostMemoryWarnMBSettingName,
SettingType.INT,
)
self.create_setting_widget(
"Host Memory Warning Threshold (Fraction)",
rm.hostMemoryWarnFractionSettingName,
SettingType.FLOAT,
range_from=0.,
range_to=1.,
)
except ImportError:
pass
| 2,435 | Python | 41.736841 | 73 | 0.420534 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/datetime_format_page.py | import carb.settings
import omni.kit.app
from functools import partial
from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX
class DatetimeFormatPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Datetime Format")
settings = carb.settings.get_settings()
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format") is None:
settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format", "MM/DD/YYYY")
def build(self):
import omni.ui as ui
# OM-38343: allow user to switching between different date formats
with ui.VStack(height=0):
with self.add_frame("Datetime Format"):
self.create_setting_widget_combo(
"Display Date As",
PERSISTENT_SETTINGS_PREFIX + "/app/datetime/format",
[
"MM/DD/YYYY",
"DD.MM.YYYY",
"DD-MM-YYYY",
"YYYY-MM-DD",
"YYYY/MM/DD",
"YYYY.MM.DD"
]
)
def __del__(self):
super().__del__()
| 1,232 | Python | 32.324323 | 106 | 0.529221 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/developer_page.py | import carb
import carb.settings
import omni.kit.app
import omni.ui as ui
from ..preferences_window import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX
from typing import Any
from typing import Dict
from typing import Optional
THREAD_SYNC_PRESETS = [
(
"No Pacing",
{
"/app/runLoops/main/rateLimitEnabled": True,
"/app/runLoops/main/rateLimitFrequency": 120,
"/app/runLoops/main/rateLimitUsePrecisionSleep": True,
"/app/runLoops/main/syncToPresent": False,
"/app/runLoops/present/rateLimitEnabled": True,
"/app/runLoops/present/rateLimitFrequency": 120,
"/app/runLoops/present/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/rateLimitEnabled": True,
"/app/runLoops/rendering_0/rateLimitFrequency": 120,
"/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/syncToPresent": False,
"/app/runLoops/rendering_1/rateLimitEnabled": True,
"/app/runLoops/rendering_1/rateLimitFrequency": 120,
"/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_1/syncToPresent": False,
"/app/runLoopsGlobal/syncToPresent": False,
"/app/vsync": False,
"/exts/omni.kit.renderer.core/present/enabled": True,
"/exts/omni.kit.renderer.core/present/presentAfterRendering": False,
"/persistent/app/viewport/defaults/tickRate": 120,
"/rtx-transient/dlssg/enabled": True,
},
),
(
"30x2",
{
"/app/runLoops/main/rateLimitEnabled": True,
"/app/runLoops/main/rateLimitFrequency": 60,
"/app/runLoops/main/rateLimitUsePrecisionSleep": True,
"/app/runLoops/main/syncToPresent": True,
"/app/runLoops/present/rateLimitEnabled": True,
"/app/runLoops/present/rateLimitFrequency": 60,
"/app/runLoops/present/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/rateLimitEnabled": True,
"/app/runLoops/rendering_0/rateLimitFrequency": 30,
"/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/syncToPresent": True,
"/app/runLoops/rendering_1/rateLimitEnabled": True,
"/app/runLoops/rendering_1/rateLimitFrequency": 30,
"/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_1/syncToPresent": True,
"/app/runLoopsGlobal/syncToPresent": True,
"/app/vsync": True,
"/exts/omni.kit.renderer.core/present/enabled": True,
"/exts/omni.kit.renderer.core/present/presentAfterRendering": True,
"/persistent/app/viewport/defaults/tickRate": 30,
"/rtx-transient/dlssg/enabled": True,
},
),
(
"60",
{
"/app/runLoops/main/rateLimitEnabled": True,
"/app/runLoops/main/rateLimitFrequency": 60,
"/app/runLoops/main/rateLimitUsePrecisionSleep": True,
"/app/runLoops/main/syncToPresent": True,
"/app/runLoops/present/rateLimitEnabled": True,
"/app/runLoops/present/rateLimitFrequency": 60,
"/app/runLoops/present/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/rateLimitEnabled": True,
"/app/runLoops/rendering_0/rateLimitFrequency": 60,
"/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/syncToPresent": True,
"/app/runLoops/rendering_1/rateLimitEnabled": True,
"/app/runLoops/rendering_1/rateLimitFrequency": 60,
"/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_1/syncToPresent": True,
"/app/runLoopsGlobal/syncToPresent": True,
"/app/vsync": True,
"/exts/omni.kit.renderer.core/present/enabled": True,
"/exts/omni.kit.renderer.core/present/presentAfterRendering": True,
"/persistent/app/viewport/defaults/tickRate": 60,
"/rtx-transient/dlssg/enabled": False,
},
),
(
"60x2",
{
"/app/runLoops/main/rateLimitEnabled": True,
"/app/runLoops/main/rateLimitFrequency": 60,
"/app/runLoops/main/rateLimitUsePrecisionSleep": True,
"/app/runLoops/main/syncToPresent": True,
"/app/runLoops/present/rateLimitEnabled": True,
"/app/runLoops/present/rateLimitFrequency": 120,
"/app/runLoops/present/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/rateLimitEnabled": True,
"/app/runLoops/rendering_0/rateLimitFrequency": 60,
"/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/syncToPresent": True,
"/app/runLoops/rendering_1/rateLimitEnabled": True,
"/app/runLoops/rendering_1/rateLimitFrequency": 60,
"/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_1/syncToPresent": True,
"/app/runLoopsGlobal/syncToPresent": True,
"/app/vsync": True,
"/exts/omni.kit.renderer.core/present/enabled": True,
"/exts/omni.kit.renderer.core/present/presentAfterRendering": True,
"/persistent/app/viewport/defaults/tickRate": 60,
"/rtx-transient/dlssg/enabled": True,
},
),
(
"120",
{
"/app/runLoops/main/rateLimitEnabled": True,
"/app/runLoops/main/rateLimitFrequency": 120,
"/app/runLoops/main/rateLimitUsePrecisionSleep": True,
"/app/runLoops/main/syncToPresent": True,
"/app/runLoops/present/rateLimitEnabled": True,
"/app/runLoops/present/rateLimitFrequency": 120,
"/app/runLoops/present/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/rateLimitEnabled": True,
"/app/runLoops/rendering_0/rateLimitFrequency": 120,
"/app/runLoops/rendering_0/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_0/syncToPresent": True,
"/app/runLoops/rendering_1/rateLimitEnabled": True,
"/app/runLoops/rendering_1/rateLimitFrequency": 120,
"/app/runLoops/rendering_1/rateLimitUsePrecisionSleep": True,
"/app/runLoops/rendering_1/syncToPresent": True,
"/app/runLoopsGlobal/syncToPresent": True,
"/app/vsync": True,
"/exts/omni.kit.renderer.core/present/enabled": True,
"/exts/omni.kit.renderer.core/present/presentAfterRendering": True,
"/persistent/app/viewport/defaults/tickRate": 120,
"/rtx-transient/dlssg/enabled": False,
},
),
]
class ThreadSyncPresets:
def __init__(self):
# Get all the settings to watch
names = []
paths = set()
for name, setting in THREAD_SYNC_PRESETS:
names.append(name)
for key, default in setting.items():
paths.add(key)
self._settings = carb.settings.get_settings()
self._subscriptions = []
for path in paths:
self._subscriptions.append(self._settings.subscribe_to_node_change_events(path, self._on_setting_changed))
combo = ui.ComboBox(*([0, ""] + names), height=0)
self._model = combo.model
self._sub = self._model.subscribe_item_changed_fn(self._on_model_changed)
def _on_setting_changed(self, item, event_type):
for name, setting in THREAD_SYNC_PRESETS:
all_is_good = True
for key, default in setting.items():
if self._settings.get(key) != default:
all_is_good = False
break
if all_is_good:
self._on_preset_changed(name)
return
self._on_preset_changed(None)
def _on_preset_changed(self, preset: Optional[str]):
# Find ID
for i, child_item in enumerate(self._model.get_item_children()):
if self._model.get_item_value_model(child_item).as_string == preset:
self._set_preset_id(i)
def _set_preset_id(self, preset_id: int):
self._model.get_item_value_model().as_int = preset_id
def _on_model_changed(self, model: ui.AbstractItemModel, item: ui.AbstractItem):
preset_id = self._model.get_item_value_model().as_int
child_item = self._model.get_item_children()[preset_id]
child_name = self._model.get_item_value_model(child_item).as_string
if not child_name:
return
# Find prest
for name, setting in THREAD_SYNC_PRESETS:
if name == child_name:
self._set_settings(setting)
break
def _set_settings(self, batch: Dict[str, Any]):
for key, value in batch.items():
if self._settings.get(key) != value:
self._settings.set(key, value)
carb.log_info(f"Present Sets Setting {key} -> {value}")
class DeveloperPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Developer")
def build(self):
with ui.VStack(height=0):
""" Throttle Rendering """
with self.add_frame("Throttle Rendering"):
with ui.VStack():
with ui.HStack():
self.label("Global Thread Synchronization Preset")
self.__presets = ThreadSyncPresets()
self.create_setting_widget("Async Rendering", "/app/asyncRendering", SettingType.BOOL)
self.create_setting_widget(
"Skip Rendering While Minimized", "/app/renderer/skipWhileMinimized", SettingType.BOOL
)
self.create_setting_widget(
"Yield 'ms' while in focus",
"/app/renderer/sleepMsOnFocus",
SettingType.INT,
range_from=0,
range_to=50,
)
self.create_setting_widget(
"Yield 'ms' while not in focus",
"/app/renderer/sleepMsOutOfFocus",
SettingType.INT,
range_from=0,
range_to=200,
)
self.create_setting_widget(
"Enable UI FPS Limit", "/app/runLoops/main/rateLimitEnabled", SettingType.BOOL
)
self.create_setting_widget(
"UI FPS Limit uses Busy Loop", "/app/runLoops/main/rateLimitUseBusyLoop", SettingType.BOOL
)
self.create_setting_widget(
"UI FPS Limit",
"/app/runLoops/main/rateLimitFrequency",
SettingType.FLOAT,
range_from=10,
range_to=360,
)
self.create_setting_widget(
"Use Fixed Time Stepping", "/app/player/useFixedTimeStepping", SettingType.BOOL
)
# Present thread
self.create_setting_widget(
"Use Present Thread", "/exts/omni.kit.renderer.core/present/enabled", SettingType.BOOL
)
self.create_setting_widget(
"Sync Threads and Present Thread", "/app/runLoopsGlobal/syncToPresent", SettingType.BOOL
)
self.create_setting_widget(
"Present Thread FPS Limit",
"/app/runLoops/present/rateLimitFrequency",
SettingType.FLOAT,
range_from=10,
range_to=360,
)
self.create_setting_widget(
"Sync Present Thread to Present After Rendering",
"/exts/omni.kit.renderer.core/present/presentAfterRendering",
SettingType.BOOL
)
self.create_setting_widget(
"Vsync",
"/app/vsync",
SettingType.BOOL
)
| 12,661 | Python | 44.060498 | 118 | 0.564647 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/stage_page.py | import carb.settings
import omni.kit.app
from functools import partial
from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType
class StagePreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Stage")
self._update_setting = {}
settings = carb.settings.get_settings()
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange") is None:
settings.set_float_array(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange", [0, 100])
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond") is None:
settings.set_default_float(PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond", 60.0)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps") is None:
settings.set_default_bool(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps", True
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType") is None:
settings.set_default_string(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType", "Scale, Rotate, Translate"
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder") is None:
settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder", "XYZ")
# OM-47905: Default camera rotation order should be YXZ.
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder") is None:
settings.set_default_string(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder", "YXZ")
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder") is None:
settings.set_default_string(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder",
"xformOp:translate, xformOp:rotate, xformOp:scale",
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision") is None:
settings.set_default_string(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision", "Double"
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport") is None:
settings.set_default_string(
PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport", "payload"
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring") is None:
settings.set_default_bool(
PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring", False
)
if settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace") is None:
settings.set_default_bool(
PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace", True
)
def build(self):
import omni.ui as ui
""" New Stage """
with ui.VStack(height=0):
with self.add_frame("New Stage"):
with ui.VStack():
self.create_setting_widget_combo(
"Default Up Axis", PERSISTENT_SETTINGS_PREFIX + "/app/stage/upAxis", ["Y", "Z"]
)
self.create_setting_widget(
"Default Animation Rate (TimeCodesPerSecond)",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodesPerSecond",
SettingType.FLOAT
)
self.create_setting_widget(
"Default Meters Per Unit",
PERSISTENT_SETTINGS_PREFIX + "/simulation/defaultMetersPerUnit",
SettingType.FLOAT,
range_from=0.001,
range_to=1.0,
speed=0.001,
identifier="default_meters_per_unit"
)
self.create_setting_widget(
"Default Time Code Range",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/timeCodeRange",
SettingType.DOUBLE2,
)
self.create_setting_widget(
"Default DefaultPrim Name",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/defaultPrimName",
SettingType.STRING,
)
self.create_setting_widget_combo(
"Interpolation Type",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/interpolationType",
["Linear", "Held"],
)
self.create_setting_widget(
"Enable Static Material Network Topology",
"/omnihydra/staticMaterialNetworkTopology",
SettingType.BOOL,
)
self._create_prim_creation_settings_widgets()
self.spacer()
""" Authoring """
with self.add_frame("Authoring"):
with ui.VStack():
self.create_setting_widget(
"Keep Prim World Transfrom When Reparenting",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/movePrimInPlace",
SettingType.BOOL,
)
self.create_setting_widget(
'Set "Instanceable" When Creating Reference',
PERSISTENT_SETTINGS_PREFIX + "/app/stage/instanceableOnCreatingReference",
SettingType.BOOL,
)
self.create_setting_widget(
"Transform Gizmo Manipulates Scale/Rotate/Translate Separately (New)",
PERSISTENT_SETTINGS_PREFIX + "/app/transform/gizmoUseSRT",
SettingType.BOOL,
)
self.create_setting_widget(
"Camera Controller Manipulates Scale/Rotate/Translate Separately (New)",
PERSISTENT_SETTINGS_PREFIX + "/app/camera/controllerUseSRT",
SettingType.BOOL,
)
self.create_setting_widget(
"Allow nested gprims authoring",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/nestedGprimsAuthoring",
SettingType.BOOL,
)
self.spacer()
""" Import """
with self.add_frame("Import"):
with ui.VStack():
self.create_setting_widget_combo(
"Drag & Drop USD Method",
PERSISTENT_SETTINGS_PREFIX + "/app/stage/dragDropImport",
["payload", "reference"],
)
self.spacer()
""" Logging """
with self.add_frame("Logging"):
with ui.VStack():
self.create_setting_widget(
"Mute USD Coding Error from USD Diagnostic Manager",
PERSISTENT_SETTINGS_PREFIX + "/app/usd/muteUsdCodingError",
SettingType.BOOL,
)
self.spacer()
""" Compatibility """
with self.add_frame("Compatibility"):
with ui.VStack():
self.create_setting_widget(
"Support unprefixed UsdLux attributes (USD <= 20.11)",
PERSISTENT_SETTINGS_PREFIX + "/app/usd/usdLuxUnprefixedCompat",
SettingType.BOOL,
)
def __del__(self):
super().__del__()
self._update_setting = {}
def _create_prim_creation_settings_widgets(self):
self.create_setting_widget(
"Start with Transform Op on Prim Creation",
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps",
SettingType.BOOL,
)
def _on_prim_creation_with_default_xform_ops_change(item, event_type, owner):
if event_type == carb.settings.ChangeEventType.CHANGED:
owner._update_prim_creation_with_default_xform_ops()
self._update_setting["PrimCreationWithDefaultXformOps"] = omni.kit.app.SettingChangeSubscription(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps",
partial(_on_prim_creation_with_default_xform_ops_change, owner=self),
)
widget = self.create_setting_widget_combo(
" Default Transform Op Type",
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType",
["Scale, Rotate, Translate", "Scale, Orient, Translate", "Transform"],
)
def _on_default_xform_op_type_change(item, event_type, owner):
if event_type == carb.settings.ChangeEventType.CHANGED:
owner._update_prim_creation_with_default_xform_ops()
self._update_setting["DefaultXformOpType"] = omni.kit.app.SettingChangeSubscription(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType",
partial(_on_default_xform_op_type_change, owner=self),
)
self._widget_default_xform_op_type = widget
widget = self.create_setting_widget_combo(
" Default Camera Rotation Order",
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultCameraRotationOrder",
["XYZ", "XZY", "YZX", "YXZ", "ZXY", "ZYX"],
)
self._widget_default_camera_rotation_order = widget
widget = self.create_setting_widget_combo(
" Default Rotation Order",
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultRotationOrder",
["XYZ", "XZY", "YZX", "YXZ", "ZXY", "ZYX"],
)
self._widget_default_rotation_order = widget
widget = self.create_setting_widget_combo(
" Default Xform Op Order",
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder",
[
"xformOp:translate, xformOp:rotate, xformOp:scale",
"xformOp:translate, xformOp:orient, xformOp:scale",
"xformOp:transform",
],
)
self._widget_default_xform_op_order = widget
widget = self.create_setting_widget_combo(
" Default Xform Precision",
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpPrecision",
["Float", "Double"],
)
self._widget_default_xform_op_precision = widget
self._update_prim_creation_with_default_xform_ops()
def _update_prim_creation_with_default_xform_ops(self):
settings = carb.settings.get_settings()
if settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/PrimCreationWithDefaultXformOps"):
self._widget_default_xform_op_type.enabled = True
default_xform_ops = settings.get_as_string(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpType"
)
if default_xform_ops == "Scale, Orient, Translate":
self._widget_default_rotation_order.enabled = False
self._widget_default_camera_rotation_order.enabled = False
settings.set_string(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder",
"xformOp:translate, xformOp:orient, xformOp:scale",
)
elif default_xform_ops == "Transform":
self._widget_default_rotation_order.enabled = False
self._widget_default_camera_rotation_order.enabled = False
settings.set_string(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder", "xformOp:transform"
)
else:
self._widget_default_rotation_order.enabled = True
self._widget_default_camera_rotation_order.enabled = True
settings.set_string(
PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/DefaultXformOpOrder",
"xformOp:translate, xformOp:rotate, xformOp:scale",
)
self._widget_default_xform_op_order.enabled = False
self._widget_default_xform_op_precision.enabled = True
else:
self._widget_default_xform_op_type.enabled = False
self._widget_default_rotation_order.enabled = False
self._widget_default_camera_rotation_order.enabled = False
self._widget_default_xform_op_order.enabled = False
self._widget_default_xform_op_precision.enabled = False
| 13,140 | Python | 44.787456 | 123 | 0.563775 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/rendering_page.py | import carb
import carb.settings
import omni.kit.app
import omni.ui as ui
from ..preferences_window import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX
from .developer_page import THREAD_SYNC_PRESETS # kit-extensions/kit-scene extension access this
from typing import Any
from typing import Dict
from typing import Optional
class RenderingPreferences(PreferenceBuilder):
def post_notification(message: str, info: bool = False, duration: int = 3):
import omni.kit.notification_manager as nm
if info:
type = nm.NotificationStatus.INFO
else:
type = nm.NotificationStatus.WARNING
nm.post_notification(message, status=type, duration=duration)
def __init__(self):
super().__init__("Rendering")
self._persistentDistillMaterialPath = PERSISTENT_SETTINGS_PREFIX + "/rtx/mdltranslator/distillMaterial"
self._persistentMultiGPUPath = PERSISTENT_SETTINGS_PREFIX + "/renderer/multiGpu/enabled"
self._persistentOpacityMicromapPath = PERSISTENT_SETTINGS_PREFIX + "/renderer/raytracingOmm/enabled"
settings = carb.settings.get_settings()
if settings.get(self._persistentDistillMaterialPath) is None:
settings.set_default_bool(self._persistentDistillMaterialPath, False)
self._sub_material_distilling_changed = omni.kit.app.SettingChangeSubscription(
self._persistentDistillMaterialPath,
self._on_material_distilling_changed
)
self._sub_opacity_micromap_changed = omni.kit.app.SettingChangeSubscription(
self._persistentOpacityMicromapPath,
self._on_opacity_micromap_changed
)
self._persistentPlaceholderTextureColorPath = PERSISTENT_SETTINGS_PREFIX + "/rtx/resourcemanager/placeholderTextureColor"
if settings.get(self._persistentPlaceholderTextureColorPath) is None:
settings.set_float_array(self._persistentPlaceholderTextureColorPath, [0,1,1])
# Note: No SettingChangeSubscription because it shows the same popup like 6 times when the color is changed
self._enableFabricSceneDelegatePath = "/app/useFabricSceneDelegate"
self._sub_fabric_delegate_changed = omni.kit.app.SettingChangeSubscription(
self._enableFabricSceneDelegatePath,
self._on_fabric_delegate_changed
)
self._fabricMemBudgetPath = "/app/usdrt/scene_delegate/gpuMemoryBudgetPercent"
if settings.get(self._fabricMemBudgetPath) is None:
settings.set_default_float(self._fabricMemBudgetPath, 90)
self._fabricEnableGeometryStreaming = "/app/usdrt/scene_delegate/geometryStreaming/enabled"
if settings.get(self._fabricEnableGeometryStreaming) is None:
settings.set_default_bool(self._fabricEnableGeometryStreaming, True)
self._fabricEnableGeometryStreamingMinSize = "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimit"
if settings.get(self._fabricEnableGeometryStreamingMinSize) is None:
settings.set_default_float(self._fabricEnableGeometryStreamingMinSize, 0.)
self._fabricEnableProxyCubes = "/app/usdrt/scene_delegate/enableProxyCubes"
if settings.get(self._fabricEnableProxyCubes) is None:
settings.set_default_bool(self._fabricEnableProxyCubes, False)
self._fabricMergeSubcomponents = "/app/usdrt/population/utils/mergeSubcomponents"
if settings.get(self._fabricMergeSubcomponents) is None:
settings.set_default_bool(self._fabricMergeSubcomponents, False)
self._fabricMergeInstances = "/app/usdrt/population/utils/mergeInstances"
if settings.get(self._fabricMergeInstances) is None:
settings.set_default_bool(self._fabricMergeInstances, False)
self._fabricMergeMaterials = "/app/usdrt/population/utils/mergeMaterials"
if settings.get(self._fabricMergeMaterials) is None:
settings.set_default_bool(self._fabricMergeMaterials, True)
self._fabricReadMaterials = "/app/usdrt/population/utils/readMaterials"
if settings.get(self._fabricReadMaterials) is None:
settings.set_default_bool(self._fabricReadMaterials, True)
self._fabricReadLights = "/app/usdrt/population/utils/readLights"
if settings.get(self._fabricReadLights) is None:
settings.set_default_bool(self._fabricReadLights, True)
self._fabricReadPrimvars = "/app/usdrt/population/utils/readPrimvars"
if settings.get(self._fabricReadPrimvars) is None:
settings.set_default_bool(self._fabricReadPrimvars, True)
self._fabricInferDisplayColorFromMaterial = "/app/usdrt/population/utils/inferDisplayColorFromMaterial"
if settings.get(self._fabricInferDisplayColorFromMaterial) is None:
settings.set_default_bool(self._fabricInferDisplayColorFromMaterial, False)
self._fabricHandleSceneGraphInstances = "/app/usdrt/population/utils/handleSceneGraphInstances"
if settings.get(self._fabricHandleSceneGraphInstances) is None:
settings.set_default_bool(self._fabricHandleSceneGraphInstances, True)
self._fabricUseHydraBlendShape = "/app/usdrt/scene_delegate/useHydraBlendShape"
if settings.get(self._fabricUseHydraBlendShape) is None:
settings.set_default_bool(self._fabricUseHydraBlendShape, False)
def build(self):
with ui.VStack(height=0):
""" Hydra Scene Delegate """
with self.add_frame("Fabric Scene Delegate"):
with ui.VStack():
self.create_setting_widget("Enable Fabric delegate (preview feature, requires scene reload)",
self._enableFabricSceneDelegatePath,
SettingType.BOOL,
tooltip="Enable Fabric Hydra scene delegate for faster load times on large scenes.\n"
"This is a preview release of this new feature and some scene interactions will be limited.\n"
"You should expect faster load times with geometry streaming, faster playback of USD animation, "
"and GPU memory staying under a predefined budget.")
self.create_setting_widget("Fabric delegate GPU memory budget %",
self._fabricMemBudgetPath,
SettingType.FLOAT,
range_from=0,
range_to=100,
tooltip="Fabric Scene Delegate will stop loading geometry when this threshold of available GPU memory is reached.")
with ui.CollapsableFrame(title="Advanced Fabric Scene Delegate Settings", collapsed=True):
with ui.VStack():
self.create_setting_widget("Enable Geometry Streaming in Fabric Scene Delegate",
self._fabricEnableGeometryStreaming,
SettingType.BOOL,
tooltip="This enables the progressive and sorted loading of geometry, as well as the device memory limit checks.")
self.create_setting_widget("Geo Streaming Minimum Size",
self._fabricEnableGeometryStreamingMinSize,
SettingType.FLOAT,
range_from=0,
range_to=1,
range_step=0.0001,
tooltip="This sets a minimum relative size on screen for objects to be loaded, 0 loads everything.")
self.create_setting_widget("Enable proxy cubes for unloaded prims",
self._fabricEnableProxyCubes,
SettingType.BOOL,
tooltip="This helps visualizing scene content when having low device memory, but can have performance impact for very large scenes.")
self.create_setting_widget("Merge subcomponents",
self._fabricMergeSubcomponents,
SettingType.BOOL,
tooltip="Fabric Scene Delegate will merge all meshes within USD subcomponents.\n"
"This does NOT affect the USD stage, only the Fabric representation.")
self.create_setting_widget("Merge instances",
self._fabricMergeInstances,
SettingType.BOOL,
tooltip="Fabric Scene Delegate will merge all meshes within USD scene graph instances.\n"
"This does NOT affect the USD stage, only the Fabric representation.")
self.create_setting_widget("Merge materials",
self._fabricMergeMaterials,
SettingType.BOOL,
tooltip="Fabric Scene Delegate will identify unique materials and drop all duplicates.\n"
"This does NOT affect the USD stage, only the Fabric representation.")
self.create_setting_widget("Read materials",
self._fabricReadMaterials,
SettingType.BOOL,
tooltip="When off, Fabric Scene Delegate will not read any material from USD, which can speed up load time.\n"
"This does NOT affect the USD stage, only the Fabric representation.")
self.create_setting_widget("Infer displayColor from material",
self._fabricInferDisplayColorFromMaterial,
SettingType.BOOL,
tooltip="When on, Fabric Scene Delegate will read material info to infer mesh displayColor.\n"
"This does NOT affect the USD stage, only the Fabric representation.")
self.create_setting_widget("Read lights",
self._fabricReadLights,
SettingType.BOOL,
tooltip="When off, Fabric Scene Delegate will not read any lights from USD.\n"
"This does NOT affect the USD stage, only the Fabric representation.")
self.create_setting_widget("Read primvars",
self._fabricReadPrimvars,
SettingType.BOOL,
tooltip="When off, Fabric Scene Delegate will not read any mesh primvar from USD.\n"
"This does NOT affect the USD stage, only the Fabric representation.")
self.create_setting_widget("Use Fabric Scene Graph Instancing",
self._fabricHandleSceneGraphInstances,
SettingType.BOOL,
tooltip="When off, Fabric Scene Delegate will ignore USD Scene Graph Instances.\n"
"Each instanced geometry will be duplicated in Fabric.")
self.create_setting_widget("Use Hydra BlendShape",
self._fabricUseHydraBlendShape,
SettingType.BOOL,
tooltip="Fabric Scene Delegate will compute hydra BlendShape.\n"
"This will be effective after next stage loading.")
#define USDRT_POPULATION_UTILS_INFERDISPLAYCOLORFROMMATERIAL "/app/usdrt/population/utils/"
self.spacer()
""" White Mode """
with self.add_frame("White Mode"):
with ui.VStack():
widget = self.create_setting_widget("Material", "/rtx/debugMaterialWhite", SettingType.STRING)
widget.enabled = False
self.create_setting_widget(
"Exceptions (Requires Scene Reload)",
PERSISTENT_SETTINGS_PREFIX + "/app/rendering/whiteModeExceptions",
SettingType.STRING,
)
self.spacer()
""" MDL """
with self.add_frame("MDL"):
with ui.VStack():
self.create_setting_widget(
"Material Distilling (Experimental, requires app restart)",
self._persistentDistillMaterialPath,
SettingType.BOOL,
tooltip="Enables transforming MDL materials of arbitrary complexity to predefined target material models, which can improve material rendering fidelity in RTX Real-Time mode."
"\nImproves rendering fidelity of complex materials such as Clear Coat in RTX Real-Time mode."
"\nRequires app restart to take effect."
)
self.spacer()
""" Texture Streaming """
with self.add_frame("Texture Streaming"):
with ui.VStack():
self.create_setting_widget(
"Placeholder Texture Color (requires app restart)",
self._persistentPlaceholderTextureColorPath,
SettingType.COLOR3,
tooltip="Sets the color of the placeholder texture which is used while actual textures are loaded."
"\nRequires app restart to take effect."
)
self.spacer()
""" Multi-GPU """
with self.add_frame("Multi-GPU"):
with ui.VStack():
with ui.HStack(height=24):
self.label("Multi-GPU")
settings = carb.settings.get_settings()
mgpu = str(settings.get(self._persistentMultiGPUPath))
index = 0
if mgpu == "True":
index = 1
elif mgpu == "False":
index = 2
widget = ui.ComboBox(index, "Auto", "True", "False")
widget.model.add_item_changed_fn(self._on_multigpu_changed)
self.spacer()
""" Opacity MicroMap """
with self.add_frame("Opacity MicroMap"):
with ui.VStack():
self.create_setting_widget(
"Enable Opacity MicroMap",
self._persistentOpacityMicromapPath,
SettingType.BOOL,
tooltip="Opacity MicroMaps improve efficiency of rendering translucent objects."
"\nThis feature requires an Ada Lovelace architecture GPU."
"\nRequires app restart to take effect."
)
def _on_opacity_micromap_changed(self, value: bool, event_type: carb.settings.ChangeEventType):
if event_type == carb.settings.ChangeEventType.CHANGED:
msg = "Opacity MicroMap settings has been changed. You will need to restart Omniverse for this to take effect."
try:
import asyncio
import omni.kit.notification_manager
import omni.kit.app
async def show_msg():
await omni.kit.app.get_app().next_update_async()
omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False)
asyncio.ensure_future(show_msg())
except:
carb.log_warn(msg)
def _on_material_distilling_changed(self, value: bool, event_type: carb.settings.ChangeEventType):
if event_type == carb.settings.ChangeEventType.CHANGED:
msg = "Material distilling settings has been changed. You will need to restart Omniverse for this to take effect."
try:
import asyncio
import omni.kit.notification_manager
import omni.kit.app
async def show_msg():
await omni.kit.app.get_app().next_update_async()
omni.kit.notification_manager.post_notification(msg, hide_after_timeout=False)
asyncio.ensure_future(show_msg())
except:
carb.log_warn(msg)
def _on_fabric_delegate_changed(self, value: str, event_type: carb.settings.ChangeEventType):
import omni.usd
if event_type == carb.settings.ChangeEventType.CHANGED:
stage = omni.usd.get_context().get_stage()
if not stage or stage.GetRootLayer().anonymous:
return
msg = "Hydra scene delegate changed. You will need to reload your stage for this to take effect."
try:
import asyncio
import omni.kit.notification_manager
import omni.kit.app
async def show_msg():
await omni.kit.app.get_app().next_update_async()
omni.kit.notification_manager.post_notification(msg, hide_after_timeout=True, duration=2)
asyncio.ensure_future(show_msg())
except:
carb.log_warn(msg)
def _on_multigpu_changed(self, model, item):
current_index = model.get_item_value_model().as_int
settings = carb.settings.get_settings()
if current_index == 0:
# this is a string not a bool and will have no effect
settings.set_string(self._persistentMultiGPUPath, "auto")
elif current_index == 1:
settings.set_bool(self._persistentMultiGPUPath, True)
elif current_index == 2:
settings.set_bool(self._persistentMultiGPUPath, False)
# print restart message
RenderingPreferences.post_notification(f"You need to restart {omni.kit.app.get_app().get_app_name()} for changes to take effect", info=True)
| 18,315 | Python | 54.335347 | 199 | 0.583347 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/audio_page.py | import os
import platform
import carb.settings
import omni.kit.app
import omni.kit.audiodeviceenum
import omni.usd.audio
from functools import partial
import omni.ui as ui
from omni.kit.audiodeviceenum import Direction, SampleType
from ..preferences_window import PreferenceBuilder, show_file_importer, PERSISTENT_SETTINGS_PREFIX, SettingType
class AudioPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Audio")
self._settings = carb.settings.get_settings()
self._enum = omni.kit.audiodeviceenum.acquire_audio_device_enum_interface()
self._audio = omni.usd.audio.get_stage_audio_interface()
carb.settings.get_settings().set_default_bool(
PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop", False
)
carb.settings.get_settings().set_default_float(PERSISTENT_SETTINGS_PREFIX + "/audio/context/uiVolume", 1.0)
def build(self):
devices = self.get_device_list(Direction.PLAYBACK)
capture_devices = self.get_device_list(Direction.CAPTURE)
speaker_list = [
"auto-detect",
"mono",
"stereo",
"2.1",
"quad",
"4.1 surround",
"5.1 surround",
"7.1 surround",
"7.1.4 surround",
"9.1 surround",
"9.1.4 surround",
"9.1.6 surround",
]
""" Audio Device """
with ui.VStack(height=0):
with self.add_frame("Audio Output"):
with ui.VStack():
self._device_widget = self.create_setting_widget_combo(
"Output Device", PERSISTENT_SETTINGS_PREFIX + "/audio/context/deviceName", devices
)
self._capture_device_widget = self.create_setting_widget_combo(
"Input Device", PERSISTENT_SETTINGS_PREFIX + "/audio/context/captureDeviceName", capture_devices
)
self.create_setting_widget_combo(
"Speaker Configuration", PERSISTENT_SETTINGS_PREFIX + "/audio/context/speakerMode", speaker_list
)
with ui.HStack(height=24):
ui.Button("Refresh", clicked_fn=partial(self._on_refresh_button_fn))
ui.Spacer(width=10)
ui.Button("Apply", clicked_fn=partial(self._on_apply_button_fn))
self.spacer()
""" Audio Parameters """
with self.add_frame("Audio Parameters"):
with ui.VStack():
self.create_setting_widget(
"Auto Stream Threshold (in Kilobytes)",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/autoStreamThreshold",
SettingType.INT,
range_from=0,
range_to=10240,
speed=10,
)
self.spacer()
""" Audio Player Parameters """
with self.add_frame("Audio Player Parameters"):
with ui.VStack():
self.create_setting_widget(
"Auto Stream Threshold (in Kilobytes)",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/audioPlayerAutoStreamThreshold",
SettingType.INT,
range_from=0,
range_to=10240,
speed=10,
)
self.create_setting_widget(
"Close Audio Player on Stop",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/closeAudioPlayerOnStop",
SettingType.BOOL,
)
self.spacer()
""" Volume Levels """
with self.add_frame("Volume Levels"):
with ui.VStack():
self.create_setting_widget(
"Master Volume",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/masterVolume",
SettingType.FLOAT,
range_from=0.0,
range_to=1.0,
speed=0.01,
)
self.create_setting_widget(
"USD Volume",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/usdVolume",
SettingType.FLOAT,
range_from=0.0,
range_to=1.0,
speed=0.01,
)
self.create_setting_widget(
"Spatial Voice Volume",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/spatialVolume",
SettingType.FLOAT,
range_from=0.0,
range_to=1.0,
speed=0.01,
)
self.create_setting_widget(
"Non-spatial Voice Volume",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/nonSpatialVolume",
SettingType.FLOAT,
range_from=0.0,
range_to=1.0,
speed=0.01,
)
self.create_setting_widget(
"UI Audio Volume",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/uiVolume",
SettingType.FLOAT,
range_from=0.0,
range_to=1.0,
speed=0.01,
)
self.spacer()
""" Debug """
with self.add_frame("Debug"):
with ui.VStack():
self.create_setting_widget(
"Stream Dump Filename",
PERSISTENT_SETTINGS_PREFIX + "/audio/context/streamerFile",
SettingType.STRING,
clicked_fn=self._on_browse_button_fn,
)
# checkbox to enable stream dumping. Note that the setting path for
# this is *intentionally* not persistent. This forces the stream
# dumping to need to be toggled on at each launch instead of just
# enabling it on startup and filling up everyone's harddrives.
self.create_setting_widget("Enable Stream Dump", "/audio/context/enableStreamer", SettingType.BOOL)
def _on_browse_button_fn(self, origin):
""" Called when the user picks the Browse button. """
full_path = origin.model.get_value_as_string()
path = os.path.dirname(full_path)
if path == "":
path = "/"
if platform.system().lower() == "windows":
path = "C:/"
filename = os.path.basename(full_path)
if filename == "":
filename = "stream_dump"
# NOTE: navigate_to doesn't work if target file doesn't exist...
navigate_to = self.cleanup_slashes(os.path.join(path, filename))
if not os.path.exists(navigate_to):
navigate_to = self.cleanup_slashes(path)
show_file_importer(
title="Select Filename (Local Files Only)",
file_exts=[("RIFF Files(*.wav)", ""), ("All Files(*)", "")],
click_apply_fn=self._on_file_pick,
filename_url=navigate_to
)
def _on_file_pick(self, full_path):
""" Called when the user accepts filename in the Select Filename dialog. """
path = os.path.dirname(full_path)
if path == "":
path = "/"
if platform.system().lower() == "windows":
path = "C:/"
filename = os.path.basename(full_path)
if filename == "":
filename = "stream_dump.bin"
self._settings.set(
PERSISTENT_SETTINGS_PREFIX + "/audio/context/streamerFile",
self.cleanup_slashes(os.path.join(path, filename)),
)
def _on_refresh_button_fn(self):
""" Called when the user clicks on the 'Refresh' button. """
devices = self.get_device_list(Direction.PLAYBACK)
self._device_widget.model.set_items(devices)
devices = self.get_device_list(Direction.CAPTURE)
self._capture_device_widget.model.set_items(devices)
def _on_apply_button_fn(self):
""" Called when the user clicks on the 'Apply' button. """
deviceId = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/audio/context/deviceName")
self._audio.set_device(deviceId)
def get_device_list(self, direction):
device_count = self._enum.get_device_count(direction)
default_device = self._enum.get_device_name(direction, 0)
if default_device is None:
return {"No audio device is connected": ""}
devices = {"Default Device (" + self._enum.get_device_name(direction, 0) + ")": ""}
for i in range(device_count):
dev_name = self._enum.get_device_description(direction, i)
dev_id = self._enum.get_device_id(direction, i)
if dev_name == None or dev_id == None:
continue
devices[dev_name] = dev_id
return devices
| 9,404 | Python | 39.891304 | 120 | 0.507656 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/scripts/pages/tagging_page.py | import carb.settings
import omni.kit.app
from functools import partial
import omni.ui as ui
from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType
class TaggingPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Tagging")
self._showAdvanced = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showAdvancedTagView"
self._showHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showHiddenTags"
self._modifyHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/modifyHiddenTags"
carb.settings.get_settings().set_default_bool(self._showAdvanced, False)
carb.settings.get_settings().set_default_bool(self._showHidden, False)
carb.settings.get_settings().set_default_bool(self._modifyHidden, False)
def build(self):
# update on setting change
def _on_change(item, event_type, owner):
if event_type == carb.settings.ChangeEventType.CHANGED:
owner._update_visibility()
self._update_setting = omni.kit.app.SettingChangeSubscription(
self._showAdvanced, partial(_on_change, owner=self)
)
self._update_setting2 = omni.kit.app.SettingChangeSubscription(
self._showHidden, partial(_on_change, owner=self)
)
""" Tagging """
with ui.VStack(height=0):
with self.add_frame("Tagging"):
with ui.VStack():
self.create_setting_widget("Allow advanced tag view", self._showAdvanced, SettingType.BOOL)
self._showHiddenWidget = self.create_setting_widget(
"Show hidden tags in advanced view", self._showHidden, SettingType.BOOL
)
self._modifyHiddenWidget = self.create_setting_widget(
"Allow adding and modifying hidden tags directly", self._modifyHidden, SettingType.BOOL
)
self._update_visibility()
def _update_visibility(self):
settings = carb.settings.get_settings()
if settings.get_as_bool(self._showAdvanced):
self._showHiddenWidget.enabled = True
self._modifyHiddenWidget.enabled = settings.get_as_bool(self._showHidden)
else:
self._showHiddenWidget.enabled = False
self._modifyHiddenWidget.enabled = False
| 2,442 | Python | 42.624999 | 111 | 0.643735 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_material_config.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
import omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.kit.window.preferences.scripts.material_config_utils as mc_utils
import os
from pathlib import Path
import posixpath
import shutil
import tempfile
import toml
TEST_PATH_STRS = [
"C:/some/project/materials",
"omniverse://another/project/materials",
"/my/own/materials"
]
def _compare_toml_files(file1, file2):
# the toml module does not preserve the item order in files so can't use
# simple line comparison. needs to compare them as dicts
toml1 = toml.load(file1)
toml2 = toml.load(file2)
return (toml1 == toml2)
class PreferencesTestMaterialConfigUtils(AsyncTestCase):
# run only once at the beginning
@classmethod
def setUpClass(cls):
# test config file path
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
data_tests_dir = Path(ext_path) / "data/tests"
test_config_file_path = data_tests_dir / "material.config.toml"
test_config_carb_file_path = data_tests_dir / "material.config.carb.toml"
# create temp home dir
cls._temp_home = Path(tempfile.mkdtemp())
cls._temp_home = cls._temp_home.as_posix()
# copy test config files to the temp home
cls._temp_kit_shared_dir = posixpath.join(cls._temp_home, "Documents/Kit/shared")
if not os.path.exists(cls._temp_kit_shared_dir):
os.makedirs(cls._temp_kit_shared_dir)
shutil.copy(test_config_file_path, cls._temp_kit_shared_dir)
shutil.copy(test_config_carb_file_path, cls._temp_kit_shared_dir)
# temporary wipe out material config in settings
settings = carb.settings.get_settings()
cls._curr_material_config = settings.get("/materialConfig")
settings.set("/materialConfig", {})
# run only once at the end
@classmethod
def tearDownClass(cls):
# remove settings used in tests
settings = carb.settings.get_settings()
settings.destroy_item("/materialConfigTests")
# restore material config in settings
settings.set("/materialConfig", {})
settings.set("/materialConfig", cls._curr_material_config)
# delete temp home dir
if os.path.exists(cls._temp_home):
shutil.rmtree(cls._temp_home)
# before running each test
async def setUp(self):
# temporary set home path
# replace both variables since Path.home() looks for different env var on Windows
# depends on the Python version
self._curr_profile = os.environ.get("USERPROFILE", "")
if self._curr_profile:
os.environ["USERPROFILE"] = str(self._temp_home)
self._curr_home = os.environ.get("HOME", "")
if self._curr_home:
os.environ["HOME"] = str(self._temp_home)
# after running each test
async def tearDown(self):
# restore env vars
if self._curr_profile:
os.environ["USERPROFILE"] = self._curr_profile
if self._curr_home:
os.environ["HOME"] = self._curr_home
async def test_get_config_file_path(self):
expect = Path(self._temp_home) / "Documents/Kit/shared" / "material.config.toml"
expect = expect.as_posix()
self.assertEqual(expect, mc_utils.get_config_file_path())
async def test_load_config_file(self):
config_file_path = mc_utils.get_config_file_path()
config = mc_utils.load_config_file(config_file_path)
expect = ["my_materials", "my_maps"]
self.assertEqual(expect, config["materialGraph"]["userAllowList"])
expect = ["foo_materials", "bar_maps"]
self.assertEqual(expect, config["materialGraph"]["userBlockList"])
expect = False
self.assertEqual(expect, config["options"]["noStandardPath"])
expect = TEST_PATH_STRS
self.assertEqual(expect, config["searchPaths"]["local"])
async def test_save_config_file(self):
config = {}
config["materialGraph"] = {}
config["materialGraph"]["userAllowList"] = ["my_materials", "my_maps"]
config["materialGraph"]["userBlockList"] = ["foo_materials", "bar_maps"]
config["options"] = {}
config["options"]["noStandardPath"] = False
config["searchPaths"] = {}
config["searchPaths"]["local"] = TEST_PATH_STRS
config["configFilePath"] = "/dummy/path/material.config.toml"
# save new file
new_config_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.saved.toml")
self.assertTrue(mc_utils.save_config_file(config, new_config_file_path))
# compare to the original file
orig_config_file_path = mc_utils.get_config_file_path()
self.assertTrue(_compare_toml_files(new_config_file_path, orig_config_file_path))
async def test_save_carb_setting_to_config_file(self):
test_settings = (
("string", "coffee", False),
("float", 24.0, False),
("bool", True, False),
("paths", ";".join(TEST_PATH_STRS), True)
)
# assign to carb settings
settings = carb.settings.get_settings()
for i in test_settings:
setting_key = posixpath.join("/materialConfigTests", i[0])
settings.set(setting_key, i[1])
# save new file
new_config_carb_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.carb.saved.toml")
for i in test_settings:
carb_key = posixpath.join("/materialConfigTests", i[0])
config_key = posixpath.join("tests", i[0])
mc_utils.save_carb_setting_to_config_file(
carb_key,
config_key,
is_paths=i[2],
non_standard_path=new_config_carb_file_path
)
# compare to the original file
orig_config_carb_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.carb.toml")
self.assertTrue(_compare_toml_files(new_config_carb_file_path, orig_config_carb_file_path))
async def test_save_live_config_to_file(self):
test_settings = (
("materialGraph/userAllowList", ["my_materials", "my_maps"]),
("materialGraph/userBlockList", ["foo_materials", "bar_maps"]),
("options/noStandardPath", False),
("searchPaths/local", TEST_PATH_STRS)
)
# assign to /materialConfig carb settings
settings = carb.settings.get_settings()
for i in test_settings:
setting_key = posixpath.join("/materialConfig", i[0])
settings.set(setting_key, i[1])
# save new file
new_config_file_path = posixpath.join(self._temp_kit_shared_dir, "material.config.saved2.toml")
mc_utils.save_live_config_to_file(non_standard_path=new_config_file_path)
# compare to the original file
orig_config_file_path = mc_utils.get_config_file_path()
self.assertTrue(_compare_toml_files(new_config_file_path, orig_config_file_path))
| 7,577 | Python | 37.467005 | 112 | 0.637455 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_pages.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import carb
import omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
class PreferencesTestPages(AsyncTestCase):
# Before running each test
async def setUp(self):
omni.kit.window.preferences.show_preferences_window()
# After running each test
async def tearDown(self):
omni.kit.window.preferences.hide_preferences_window()
carb.settings.get_settings().set("/app/show_developer_preference_section", False)
async def _change_values(self):
# toggle checkboxes
widgets = ui_test.find_all("Preferences//Frame/**/CheckBox[*]")
if widgets:
for w in widgets:
# don't change audio as it causes exceptions on TC
if not "audio" in w.widget.identifier:
ov = w.model.get_value_as_bool()
w.model.set_value(not ov)
await ui_test.human_delay(10)
w.model.set_value(ov)
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(10)
await self._change_values()
async def test_developer_page(self):
carb.settings.get_settings().set("/app/show_developer_preference_section", True)
await ui_test.human_delay(10)
omni.kit.window.preferences.select_page(omni.kit.window.preferences.get_instance()._developer_preferences)
await ui_test.human_delay(10)
await self._change_values()
| 2,284 | Python | 40.545454 | 114 | 0.672067 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/__init__.py | from .test_preferences import *
from .test_stage import *
from .test_pages import *
| 84 | Python | 20.249995 | 31 | 0.75 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_preferences.py | import os
import unittest
import carb
import omni.kit.test
from omni.kit.window.preferences.scripts.preferences_window import (
PreferenceBuilder,
PERSISTENT_SETTINGS_PREFIX,
)
class TestPreferencesWindow(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_new_preferences_window(self):
called_init = False
called_del = False
class TestPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Test")
def build(self):
nonlocal called_init
called_init = True
def __del__(self):
super().__del__()
nonlocal called_del
called_del = True
self.assertFalse(called_init)
self.assertFalse(called_del)
called_init = False
called_del = False
page = omni.kit.window.preferences.register_page(TestPreferences())
omni.kit.window.preferences.select_page(page)
omni.kit.window.preferences.rebuild_pages()
prefs = omni.kit.window.preferences.get_instance()
self.assertTrue(called_init)
self.assertFalse(called_del)
called_init = False
called_del = False
omni.kit.window.preferences.unregister_page(page)
del page
self.assertFalse(called_init)
self.assertTrue(called_del)
| 1,450 | Python | 25.381818 | 75 | 0.608276 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_material.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 omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
class PreferencesTestDragDropImport(AsyncTestCase):
# Before running each test
async def setUp(self):
from omni.kit import ui_test
carb.settings.get_settings().set("/persistent/app/material/dragDropMaterialPath", "Absolute")
omni.kit.window.preferences.show_preferences_window()
for page in omni.kit.window.preferences.get_page_list():
if page.get_title() == "Material":
omni.kit.window.preferences.select_page(page)
await ui_test.human_delay(50)
break
# After running each test
async def tearDown(self):
carb.settings.get_settings().set("/persistent/app/material/dragDropMaterialPath", "Absolute")
async def test_l1_app_materla_drag_drop_path(self):
from omni.kit import ui_test
frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Material'")
import_combo = frame.find("**/ComboBox[*].identifier=='/persistent/app/material/dragDropMaterialPath'")
index_model = import_combo.model.get_item_value_model(None, 0)
import_list = import_combo.model.get_item_children(None)
for index, item in enumerate(import_list):
index_model.set_value(item.model.value)
await ui_test.human_delay(50)
self.assertEqual(carb.settings.get_settings().get('/persistent/app/material/dragDropMaterialPath'), item.model.as_string)
| 2,000 | Python | 42.499999 | 133 | 0.706 |
omniverse-code/kit/exts/omni.kit.window.preferences/omni/kit/window/preferences/tests/test_stage.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 omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
class PreferencesTestDragDropImport(AsyncTestCase):
# Before running each test
async def setUp(self):
from omni.kit import ui_test
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
omni.kit.window.preferences.show_preferences_window()
for page in omni.kit.window.preferences.get_page_list():
if page.get_title() == "Stage":
omni.kit.window.preferences.select_page(page)
await ui_test.human_delay(50)
break
# After running each test
async def tearDown(self):
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
async def test_l1_app_stage_drag_drop_import(self):
from omni.kit import ui_test
frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Import'")
import_combo = frame.find("**/ComboBox[*]")
import_combo.widget.scroll_here_y(0.5)
await ui_test.human_delay(50)
index_model = import_combo.model.get_item_value_model(None, 0)
import_list = import_combo.model.get_item_children(None)
for index, item in enumerate(import_list):
index_model.set_value(item.model.value)
await ui_test.human_delay(50)
self.assertEqual(carb.settings.get_settings().get('/persistent/app/stage/dragDropImport'), item.model.as_string)
async def test_default_meters_zero(self):
from omni.kit import ui_test
# get widgets
await ui_test.human_delay(10)
frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_New Stage'")
widget = frame.find("**/FloatSlider[*].identifier=='default_meters_per_unit'")
# set to 0.5
widget.model.set_value(0.5)
await ui_test.human_delay(10)
# set to 0.0 - This is not allowed as minimum if 0.01
widget.model.set_value(0.0)
await ui_test.human_delay(10)
# verify
self.assertAlmostEqual(widget.model.get_value_as_float(), 0.5)
| 2,667 | Python | 38.820895 | 124 | 0.674541 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_common.py | ## Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.kit.commands
import omni.timeline
import omni.usd
import carb
import carb.settings
import carb.windowing
import inspect
import pathlib
from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric
from omni.kit.viewport.utility import get_active_viewport_window, next_viewport_frame_async
from omni.kit.viewport.utility.tests.capture import capture_viewport_and_wait
from pxr import Sdf, Gf, Usd, UsdGeom, UsdLux
# This settings should be set before stage opening/creation
testSettings = {
"/app/window/hideUi": True,
"/app/asyncRendering": False,
"/app/docks/disabled": True,
"/app/window/scaleToMonitor": False,
"/app/viewport/forceHideFps": True,
"/app/captureFrame/setAlphaTo1": True,
"/rtx/materialDb/syncLoads": True,
"/omni.kit.plugin/syncUsdLoads": True,
"/rtx/hydra/materialSyncLoads": True,
"/renderer/multiGpu/autoEnable": False,
"/persistent/app/viewport/displayOptions": 0,
"/app/viewport/grid/enabled": False,
"/app/viewport/show/lights": False,
"/persistent/app/primCreation/PrimCreationWithDefaultXformOps": True,
"/rtx-transient/resourcemanager/texturestreaming/async": False,
"/app/viewport/outline/enabled": True
}
# Settings that should override settings that was set on stage opening/creation
postLoadTestSettings = {
"/rtx/post/aa/op": 0,
"/rtx/pathtracing/lightcache/cached/enabled": False,
"/rtx/raytracing/lightcache/spatialCache/enabled": False,
"/rtx/sceneDb/ambientLightIntensity": 1.0,
"/rtx/indirectDiffuse/enabled": False,
}
postLoadSkelTestSettings = {
"/rtx/post/aa/op": 0,
"/rtx/shadows/enabled": False,
"/rtx/reflections/enabled": False,
"/rtx/ambientOcclusion/enabled": False,
"/rtx/post/tonemap/op": 1,
"/renderer/multiGpu/autoEnable": False,
}
RENDER_WIDTH_SETTING = "/app/renderer/resolution/width"
RENDER_HEIGHT_SETTING = "/app/renderer/resolution/height"
OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path())
EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("data/golden")
USD_DIR = EXTENSION_FOLDER_PATH.joinpath("data/usd")
VOLUMES_DIR = EXTENSION_FOLDER_PATH.joinpath("data/volumes")
async def next_resize_async():
"""
Wait for the next event in the resize event stream of IAppWindow::getWindowResizeEventStream.
We need it because the window resize event stream is independent of IApp::getUpdateEventStream. Without this
function it's possible that resize happens several updates after. It's reproducable on Linux Release build.
"""
return await omni.appwindow.get_default_app_window().get_window_resize_event_stream().next_event()
async def wait_for_update(usd_context=omni.usd.get_context(), wait_frames=10):
max_loops = 0
while max_loops < wait_frames:
_, files_loaded, total_files = usd_context.get_stage_loading_status()
await omni.kit.app.get_app().next_update_async()
if files_loaded or total_files:
continue
max_loops = max_loops + 1
def set_cursor_position(pos):
app_window = omni.appwindow.get_default_app_window()
windowing = carb.windowing.acquire_windowing_interface()
os_window = app_window.get_window()
windowing.set_cursor_position(os_window, pos)
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(
"TransformPrimCommand",
path=prim_path,
new_transform_matrix=xform,
)
async def setup_viewport_test_window(resolution_x: int, resolution_y: int, position_x: int = 0, position_y: int = 0):
from omni.kit.viewport.utility import get_active_viewport_window
viewport_window = get_active_viewport_window()
if viewport_window:
viewport_window.position_x = position_x
viewport_window.position_y = position_y
viewport_window.width = resolution_x
viewport_window.height = resolution_y
viewport_window.viewport_api.resolution = (resolution_x, resolution_y)
return viewport_window
class RtxTest(omni.kit.test.AsyncTestCase):
THRESHOLD = 1e-5
WINDOW_SIZE = (640, 480)
def __init__(self, tests=()):
super().__init__(tests)
self._saved_width = None
self._saved_height = None
self._savedSettings = {}
self._failedImages = []
@property
def __test_name(self) -> str:
"""
The full name of the test.
It has the name of the module, class and the current test function. We use the stack to get the name of the test
function and since it's only called from create_test_window and finalize_test, we get the third member.
"""
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
async def create_test_area(self, width: int = 256, height: int = 256):
"""Resize the main window"""
app_window = omni.appwindow.get_default_app_window()
await omni.usd.get_context().new_stage_async()
viewport_window = await setup_viewport_test_window(width, height)
self.assertTrue(viewport_window is not None, "No active viewport window found.")
# Current main window size
current_width = app_window.get_width()
current_height = app_window.get_height()
# If the main window is already has requested size, do nothing
if width == current_width and height == current_height:
self._saved_width = None
self._saved_height = None
else:
# Save the size of the main window to be able to restore it at the end of the test
self._saved_width = current_width
self._saved_height = current_height
app_window.resize(width, height)
# Wait for getWindowResizeEventStream
await next_resize_async()
# Wait until the Viewport has delivered some frames
await next_viewport_frame_async(viewport_window.viewport_api, 0)
async def screenshot_and_diff(self, golden_img_dir: pathlib.Path, output_subdir=None,
golden_img_name=None, threshold=THRESHOLD):
"""
Capture the current frame and compare it with the golden image. Assert if the diff is more than given threshold.
This method differs from capture_and_compare in that it lets callers outside omni.rtx.tests
capture and compare images in their own directories. The screen captures will be placed in a
common place with the rtx.tests output, either in a subdirectory passed in as output_subdir,
or in a directory named for the test module. Golden images will be found in the directory passed
in as golden_img_dir, this is the only required parameter.
"""
if not golden_img_dir:
self.assertTrue(golden_img_dir, "A valid golden image dir is a required parameter")
if not output_subdir:
output_subdir = f"{self.__module__}"
output_img_dir = OUTPUTS_DIR.joinpath(output_subdir)
if not golden_img_name:
golden_img_name = f"{self.__test_name}.png"
return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir)
async def capture_and_compare(self, img_subdir: pathlib.Path = None, golden_img_name=None, threshold=THRESHOLD,
metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED):
"""
Capture current frame and compare it with the golden image. Assert if the diff is more than given threshold.
"""
golden_img_dir = GOLDEN_DIR.joinpath(img_subdir)
output_img_dir = OUTPUTS_DIR.joinpath(img_subdir)
if not golden_img_name:
golden_img_name = f"{self.__test_name}.png"
return await self._capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric)
async def _capture_and_compare(self, golden_img_name, threshold, output_img_dir: pathlib.Path,
golden_img_dir: pathlib.Path,
metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED):
# Capture directly from the Viewport's texture, not from UI swapchain
await capture_viewport_and_wait(golden_img_name, output_img_dir)
# Do the image comparison now
diff = finalize_capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric=metric)
if diff != 0:
carb.log_warn(f"[{self.__test_name}] the generated image {golden_img_name} has max difference {diff}")
if (diff is not None) and diff >= threshold:
self._failedImages.append(golden_img_name)
return diff
def add_dir_light(self):
omni.kit.commands.execute(
"CreatePrimCommand",
prim_path="/World/Light",
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,
)
def add_floor(self):
floor_path = "/World/Floor"
omni.kit.commands.execute(
"CreatePrimCommand",
prim_path=floor_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100},
)
floor_prim = self.ctx.get_stage().GetPrimAtPath(floor_path)
floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(25, 0.1, 25))
floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"])
def open_usd(self, usdSubpath: pathlib.Path):
path = USD_DIR.joinpath(usdSubpath)
omni.usd.get_context().open_stage(str(path))
def get_volumes_path(self, volumeSubPath: pathlib.Path):
return Sdf.AssetPath(str(VOLUMES_DIR.joinpath(volumeSubPath)))
def set_settings(self, newSettings):
settingsAPI = carb.settings.get_settings()
for s, v in newSettings.items():
if s not in self._savedSettings: # Remember old setting only when it was changed first time
self._savedSettings[s] = settingsAPI.get(s)
if v is None: # hideUi sometimes is None and it hangs kit
v = False
settingsAPI.set(s, v)
def set_camera(self, cameraPos=None, targetPos=None):
from omni.kit.viewport.utility.camera_state import ViewportCameraState
camera_state = ViewportCameraState("/OmniverseKit_Persp")
camera_state.set_position_world(cameraPos, True)
camera_state.set_target_world(targetPos, True)
async def setUp_internal(self):
self.ctx = omni.usd.get_context()
await self.create_test_area(self.WINDOW_SIZE[0], self.WINDOW_SIZE[1])
async def setUp(self):
await self.setUp_internal()
async def tearDown(self):
# Restore main window resolution if it was saved
if self._saved_width is not None and self._saved_height is not None:
app_window = omni.appwindow.get_default_app_window()
app_window.resize(self._saved_width, self._saved_height)
# Wait for getWindowResizeEventStream
await next_resize_async()
self.set_settings(self._savedSettings)
self.ctx.close_stage()
for imgName in self._failedImages:
carb.log_warn(f"[{self.__test_name}] The image {imgName} doesn't match the golden")
hasFailed = len(self._failedImages)
self._failedImages = []
self.assertEqual(hasFailed, 0)
| 12,851 | Python | 41.415841 | 142 | 0.668897 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_domelight.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
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
from pxr import UsdGeom, UsdLux, Gf, Sdf
class TestRtxDomelight(RtxTest):
TEST_PATH = "domelight"
DOMELIGHT_PRIM_PATH = "/World/DomeLight"
def create_mesh(self):
box = UsdGeom.Mesh.Define(self.ctx.get_stage(), "/World/box")
box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50),
(-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)])
box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4])
box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5])
box.CreateSubdivisionSchemeAttr("none")
return box
def create_dome_light(self, name=DOMELIGHT_PRIM_PATH):
omni.kit.commands.execute(
"CreatePrim",
prim_path=name,
prim_type="DomeLight",
select_new_prim=False,
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
attributes={
UsdLux.Tokens.inputsIntensity: 1,
UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong,
UsdLux.Tokens.inputsTextureFile: "daytime.hdr",
UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited,
} if hasattr(UsdLux.Tokens, 'inputsIntensity') else
{
UsdLux.Tokens.intensity: 1,
UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong,
UsdLux.Tokens.textureFile: "daytime.hdr",
UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited,
},
create_default_xform=True,
)
dome_light_prim = self.ctx.get_stage().GetPrimAtPath(name)
return dome_light_prim
async def setUp(self):
await self.setUp_internal()
print("RTX DomeLight Tests Setup")
self.set_settings(testSettings)
super().open_usd("hydra/dome_materials.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
my_settings = {
"/rtx/pathtracing/lightcache/cached/enabled": False,
"/rtx/raytracing/lightcache/spatialCache/enabled" : False,
"/rtx-transient/resourcemanager/genMipsForNormalMaps" : False,
"/rtx-transient/resourcemanager/texturestreaming/async" : False,
"/rtx-transient/samplerFeedbackTileSize" : 1,
"/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA
"/rtx/directLighting/sampledLighting/enabled" : False,
"/rtx/reflections/sampledLighting/enabled" : False, # LTC gives consistent lighting
# perMaterialSyncLoads: Very important, otherwise the material updates for the domelight
# materials (MDLs) are not sync-ed and updated properly.
"/rtx/hydra/perMaterialSyncLoads" : True,
}
self.set_settings(my_settings)
async def test_domelight_material_assignment(self):
"""
Test Domelight material assignment
"""
looksPath = "/World/Looks/"
# Scene Setup
self.set_settings({"/rtx/domeLight/baking/resolution": "1024"})
# We could show some minimal mesh but that might create false positives in the lighting.
#self.create_mesh()
dome_prim = self.create_dome_light()
# The loaded domelight had a texture assigned check it:
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(100)
else:
dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(100)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_texture_assigned.png")
# Bind a material to the domelight
# This material shows the emission direction in a color-coded way.
omni.kit.commands.execute('BindMaterial',
material_path=looksPath + "dome_emission_direction",
prim_path=[self.DOMELIGHT_PRIM_PATH],
strength=['weakerThanDescendants'])
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(1)
else:
dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(1)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "02_emission_direction_mat.png")
# Bind a different material to the domelight
omni.kit.commands.execute('BindMaterial',
material_path='/World/Looks/dome_gridspherejulia',
prim_path=['/World/DomeLight'],
strength=['weakerThanDescendants'])
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
dome_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(1)
else:
dome_prim.GetAttribute(UsdLux.Tokens.intensity).Set(1)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "03_gridspherejulia_mat.png")
# Set a different baking resolution
self.set_settings({"/rtx/domeLight/baking/resolution": "256"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "04_baking_resolution.png")
# Testing domelight per pixel evaluation:
# JIRA OM-49492
self.set_settings({
"/rtx/pathtracing/domeLight/primaryRaysEvaluateDomelightMdlDirectly" : True,
"/rtx/rendermode" : 'PathTracing',
"/rtx/pathtracing/spp" : 1,
"/rtx/pathtracing/totalSpp" : 1,
})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "04a_mdl_direct_evaluation.png")
# Create another domelight (JIRA OM-19501)
# The visible domelight can be any domelight if multiple domelights are in the scene.
# Internally it depends which one is in the domelight buffer[0].
# Therefore, we need to explicitly disable the first one to see the result of the second.
self.set_settings({
"/rtx/rendermode" : 'RaytracedLighting',
})
dome2_path = "/World/DomeLight_2"
dome_prim2 = self.create_dome_light(dome2_path)
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
dome_prim2.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(100)
else:
dome_prim2.GetAttribute(UsdLux.Tokens.intensity).Set(100)
omni.kit.commands.execute('ChangeProperty',
prop_path=Sdf.Path('/World/DomeLight_2.xformOp:rotateXYZ'),
value=Gf.Vec3d(270.0, -90.0, 0.0),
prev=Gf.Vec3d(270.0, 0.0, 0.0))
# Disable the first dome light
dome_prim.GetAttribute(UsdGeom.Tokens.visibility).Set(UsdGeom.Tokens.invisible)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_second_domelight.png")
| 7,828 | Python | 47.030675 | 113 | 0.646525 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_material_distilling_toggle.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.undo
import omni.kit.test
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
class TestMaterialDistillingToggle(RtxTest):
"""
rtx test running renderer with material distilling toggle on to ensure renderer correctly loads in neuraylib plugins,
compiles shader cache, inserts preprocessor macro (DISTILLED_MTL_MODE)
"""
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
self.open_usd("material_distilling.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
async def test_material_distilling_toggle(self):
await wait_for_update()
await self.capture_and_compare("material_distilling_toggle", "material_distilling_toggle.png", 1e-3)
| 1,315 | Python | 42.866665 | 121 | 0.752091 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_skel.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.
##
#TODO 02: omnihydra does not support dynamically switch animationsource on skelroot prim bindingAPI (should be a repopulate in this case)
#TODO 03: omnihydra does not support joints/blendshapes change in skelanimation prim
#TODO 04: omnihydra does not support blendshapes (target name) change in skelanimation prim (not in test)
#TODO 05 when skelanimation become invalid, skinning result should retrive restTransform
#TODO 06: after added time ranged control, the render result does not work correct for the specific animation source
import omni.kit.app
import omni.kit.commands
import omni.kit.undo
import omni.kit.test
import omni.timeline
import carb.settings
from .test_hydra_common import RtxHydraTest
from .test_common import testSettings, postLoadSkelTestSettings, set_transform_helper, wait_for_update
from pxr import Gf, Sdf, Usd, UsdGeom, UsdSkel, UsdShade
def _update_animation(animation : UsdSkel.Animation, animation_static : UsdSkel.Animation, timecode : Usd.TimeCode):
trans = animation.GetTranslationsAttr().Get(timecode)
rots = animation.GetRotationsAttr().Get(timecode)
scales = animation.GetScalesAttr().Get(timecode)
bsWeights = animation.GetBlendShapeWeightsAttr().Get(timecode)
animation_static.GetTranslationsAttr().Set(trans)
animation_static.GetRotationsAttr().Set(rots)
animation_static.GetScalesAttr().Set(scales)
animation_static.GetBlendShapeWeightsAttr().Set(bsWeights)
class TestRtxHydraSkel(RtxHydraTest):
TEST_PATH = "hydra/skel"
async def setUp(self):
await super().setUp()
timeline = omni.timeline.get_timeline_interface()
timeline.set_fast_mode(True)
await omni.kit.app.get_app().next_update_async()
async def test_01_skel_anim(self):
"""
Test hydra skel - skel anim
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skelroot_path = "/Root/group1"
skelroot_prim = stage.GetPrimAtPath(skelroot_path)
skelroot = UsdSkel.Root(skelroot_prim)
skeleton_path = "/Root/group1/joint1"
skeleton_prim = stage.GetPrimAtPath(skeleton_path)
skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim)
skeleton = UsdSkel.Skeleton(skeleton_prim)
animation_static_path = "/Root/group1/joint1/Animation_Static"
animation_static_prim = stage.GetPrimAtPath(animation_static_path)
animation_static = UsdSkel.Animation(animation_static_prim)
animation_path = "/Root/group1/joint1/Animation"
animation_prim = stage.GetPrimAtPath(animation_path)
animation = UsdSkel.Animation(animation_prim)
animation_flat_path = "/Root/group1/joint1/Animation_Flat"
animation_flat_prim = stage.GetPrimAtPath(animation_flat_path)
aniamtion_flat = UsdSkel.Animation(animation_flat_prim)
animation_outside_path = "/ZAnimation"
animation_outside_prim = stage.GetPrimAtPath(animation_outside_path)
aniamtion_outside = UsdSkel.Animation(animation_outside_prim)
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
timeline.play()
timeline.set_auto_update(False)
timeline.set_current_time(0.0)
await omni.kit.app.get_app().next_update_async()
# pure skeleton test
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_0_skeleton_0.png")
#Test animation
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path])
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
timeline.set_current_time(0.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_1.png")
timeline.set_current_time(1.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_2.png")
skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False)
self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource())
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_3.png")
#Test animation in session layer (resync)
with Usd.EditContext(stage, session_layer):
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path])
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
timeline.set_current_time(0.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_1.png")
timeline.set_current_time(1.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_2.png")
stage.RemovePrim(skeleton_path)
self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource())
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_1_animation_sessionlayer_3.png")
await wait_for_update()
self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource())
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path])
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
#Test animation switch
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path])
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim)
timeline.set_current_time(0.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_1.png")
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path])
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_2.png")
#Test animation switch in session layer
with Usd.EditContext(stage, session_layer):
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path])
timeline.set_current_time(0.0)
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_1.png")
#TODO 06: after added time ranged control, the render result does not work correct for the specific animation source
stage.RemovePrim(skeleton_path)
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
await wait_for_update()
#await self.capture_and_compare(self.TEST_PATH, "01_skelanim_2_animation_flat_sessionlayer_2.png")
#Test animation switch to outside root animation
await wait_for_update()
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_outside_path])
await wait_for_update()
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_outside_prim)
timeline.set_current_time(0.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_1.png")
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_path])
await wait_for_update()
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
#Test animation switch to outside root animation in session layer
with Usd.EditContext(stage, session_layer):
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_outside_path])
await wait_for_update()
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_outside_prim)
timeline.set_current_time(0.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_sessionlayer_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "01_skelanim_3_animation_outside_sessionlayer_1.png")
stage.RemovePrim(skeleton_path)
##TODO 02: omnihydra does not support dynamically switch animationsource on skelroot prim bindingAPI (should be a repopulate in this case)
##Test animation switch to at skelroot prim
#skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False)
#await wait_for_update()
#self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource())
#skelroot_bindingAPI = UsdSkel.BindingAPI.Apply(skelroot_prim)
#skelroot_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path])
#await wait_for_update()
#self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim)
#timeline.set_current_time(0.0)
#await wait_for_update()
#await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_0.png")
#timeline.set_current_time(0.5)
#await wait_for_update()
#await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_1.png")
#skelroot_bindingAPI.GetAnimationSourceRel().ClearTargets(False)
#self.assertTrue(not skelroot_bindingAPI.GetInheritedAnimationSource())
##Test animation switch to outside root animation in session layer
#with Usd.EditContext(stage, session_layer):
# skelroot_bindingAPI.GetAnimationSourceRel().SetTargets([animation_flat_path])
# await wait_for_update()
# self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_flat_prim)
# await wait_for_update()
# await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_sessionlayer_0.png")
# timeline.set_current_time(0.5)
# await wait_for_update()
# await self.capture_and_compare(self.TEST_PATH, "01_skelanim_4_animation_binding_on_root_sessionlayer_1.png")
# stage.RemovePrim(skeleton_path)
timeline.set_auto_update(True)
timeline.stop()
async def test_02_skel_anim_update(self):
"""
Test hydra skel - skel animation update
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skeleton_path = "/Root/group1/joint1"
skeleton_prim = stage.GetPrimAtPath(skeleton_path)
skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim)
skeleton = UsdSkel.Skeleton(skeleton_prim)
animation_static_path = "/Root/group1/joint1/Animation_Static"
animation_static_prim = stage.GetPrimAtPath(animation_static_path)
animation_static = UsdSkel.Animation(animation_static_prim)
animation_path = "/Root/group1/joint1/Animation"
animation_prim = stage.GetPrimAtPath(animation_path)
animation = UsdSkel.Animation(animation_prim)
animation_flat_path = "/Root/group1/joint1/Animation_Flat"
animation_flat_prim = stage.GetPrimAtPath(animation_flat_path)
aniamtion_flat = UsdSkel.Animation(animation_flat_prim)
animation_outside_path = "/ZAnimation"
animation_outside_prim = stage.GetPrimAtPath(animation_outside_path)
aniamtion_outside = UsdSkel.Animation(animation_outside_prim)
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
#Test SRT/bsweights update
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_static_path])
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_static_prim)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_0.png")
timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond())
with Sdf.ChangeBlock():
_update_animation(animation, animation_static, timecode)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_1.png") #non play test
timeline.play()
timeline.set_auto_update(False)
timeline.set_current_time(1.0)
await omni.kit.app.get_app().next_update_async()
timecode = Usd.TimeCode(timeline.get_current_time() * stage.GetTimeCodesPerSecond())
with Sdf.ChangeBlock():
_update_animation(animation, animation_static, timecode)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_2.png") # play test
timeline.set_auto_update(True)
timeline.stop()
timeline.set_current_time(0.0)
await omni.kit.app.get_app().next_update_async()
with Sdf.ChangeBlock():
_update_animation(animation, animation_static, Usd.TimeCode.Default())
#Test SRT/bsweights update in session layer
with Usd.EditContext(stage, session_layer):
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_static_prim)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_sessionlayer_0.png")
timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond())
with Sdf.ChangeBlock():
_update_animation(animation, animation_static, timecode)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_0_animation_update_sessionlayer_1.png") #non play test
stage.RemovePrim(animation_static_path)
timeline.set_current_time(1.0)
await omni.kit.app.get_app().next_update_async()
timecode = Usd.TimeCode(timeline.get_current_time() * stage.GetTimeCodesPerSecond())
with Sdf.ChangeBlock():
_update_animation(animation, animation_static, timecode)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_2_animation_update_sessionlayer_2.png") # play test
timeline.set_auto_update(True)
timeline.stop()
await omni.kit.app.get_app().next_update_async()
stage.RemovePrim(animation_static_path)
###Test joint change
##TODO 03: omnihydra does not support joints/blendshapes change in skelanimation prim
##TODO 04: omnihydra does not support blendshapes (target name) change in skelanimation prim (not in test)
#with Sdf.ChangeBlock():
#_update_animation(animation, animation_static, Usd.TimeCode.Default())
#await wait_for_update()
#await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_0.png")
#timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond())
#trans = animation.GetTranslationsAttr().Get(timecode)
#rots = animation.GetRotationsAttr().Get(timecode)
#scales = animation.GetScalesAttr().Get(timecode)
#joints = animation.GetJointsAttr().Get()
#new_joints = joints.__getitem__(slice(0,3,1))
#new_trans = trans.__getitem__(slice(0,3,1))
#new_rots = rots.__getitem__(slice(0,3,1))
#new_scales = scales.__getitem__(slice(0,3,1))
#animation_static.GetJointsAttr().Set(new_joints)
#animation_static.GetTranslationsAttr().Set(new_trans)
#animation_static.GetRotationsAttr().Set(new_rots)
#animation_static.GetScalesAttr().Set(new_scales)
#await wait_for_update()
#await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_1.png")
#new_joints = joints.__getitem__(slice(0,2,1))
#new_trans = trans.__getitem__(slice(0,2,1))
#new_rots = rots.__getitem__(slice(0,2,1))
#new_scales = scales.__getitem__(slice(0,2,1))
#animation_static.GetJointsAttr().Set(new_joints)
#animation_static.GetTranslationsAttr().Set(new_trans)
#animation_static.GetRotationsAttr().Set(new_rots)
#animation_static.GetScalesAttr().Set(new_scales)
#await wait_for_update()
#await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_2.png")
#animation_static.GetJointsAttr().Set(joints)
#animation_static.GetTranslationsAttr().Set(trans)
#animation_static.GetRotationsAttr().Set(rots)
#animation_static.GetScalesAttr().Set(scales)
#await wait_for_update()
###Test joint change in session layer
#animation_static.GetJointsAttr().Set(joints)
#with Sdf.ChangeBlock():
#_update_animation(animation, animation_static, Usd.TimeCode.Default())
#await wait_for_update()
#await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_0.png")
#with Usd.EditContext(stage, session_layer):
# timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond())
# trans = animation.GetTranslationsAttr().Get(timecode)
# rots = animation.GetRotationsAttr().Get(timecode)
# scales = animation.GetScalesAttr().Get(timecode)
# joints = animation.GetJointsAttr().Get()
# new_joints = joints.__getitem__(slice(0,3,1))
# new_trans = trans.__getitem__(slice(0,3,1))
# new_rots = rots.__getitem__(slice(0,3,1))
# new_scales = scales.__getitem__(slice(0,3,1))
# animation_static.GetJointsAttr().Set(new_joints)
# animation_static.GetTranslationsAttr().Set(new_trans)
# animation_static.GetRotationsAttr().Set(new_rots)
# animation_static.GetScalesAttr().Set(new_scales)
# await wait_for_update()
# await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_1.png")
# new_joints = joints.__getitem__(slice(0,2,1))
# new_trans = trans.__getitem__(slice(0,2,1))
# new_rots = rots.__getitem__(slice(0,2,1))
# new_scales = scales.__getitem__(slice(0,2,1))
# animation_static.GetJointsAttr().Set(new_joints)
# animation_static.GetTranslationsAttr().Set(new_trans)
# animation_static.GetRotationsAttr().Set(new_rots)
# animation_static.GetScalesAttr().Set(new_scales)
# await wait_for_update()
# await self.capture_and_compare(self.TEST_PATH, "02_skelanim_update_3_joint_update_sessionlayer_2.png")
# animation_static.GetJointsAttr().Set(joints)
# animation_static.GetTranslationsAttr().Set(trans)
# animation_static.GetRotationsAttr().Set(rots)
# animation_static.GetScalesAttr().Set(scales)
# await wait_for_update()
# stage.RemovePrim(animation_static_path)
async def test_03_skel_anim_create_delete(self):
"""
Test hydra skel - skel animation update
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skeleton_path = "/Root/group1/joint1"
skeleton_prim = stage.GetPrimAtPath(skeleton_path)
skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim)
skeleton = UsdSkel.Skeleton(skeleton_prim)
animation_static_path = "/Root/group1/joint1/Animation_Static"
animation_static_prim = stage.GetPrimAtPath(animation_static_path)
animation_static = UsdSkel.Animation(animation_static_prim)
animation_path = "/Root/group1/joint1/Animation"
animation_prim = stage.GetPrimAtPath(animation_path)
animation = UsdSkel.Animation(animation_prim)
animation_flat_path = "/Root/group1/joint1/Animation_Flat"
animation_flat_prim = stage.GetPrimAtPath(animation_flat_path)
aniamtion_flat = UsdSkel.Animation(animation_flat_prim)
animation_outside_path = "/ZAnimation"
animation_outside_prim = stage.GetPrimAtPath(animation_outside_path)
aniamtion_outside = UsdSkel.Animation(animation_outside_prim)
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
timeline.set_current_time(0.0)
await omni.kit.app.get_app().next_update_async()
timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond())
trans = animation.GetTranslationsAttr().Get(timecode)
rots = animation.GetRotationsAttr().Get(timecode)
scales = animation.GetScalesAttr().Get(timecode)
joints = animation.GetJointsAttr().Get()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_0_animation_create_0.png")
animation_new_path = "/ZAnimation_New"
animation_new = UsdSkel.Animation.Define(stage, animation_new_path)
animation_new_prim = animation_new.GetPrim()
await wait_for_update()
self.assertTrue(animation_new_prim)
with Sdf.ChangeBlock():
animation_new.GetJointsAttr().Set(joints)
animation_new.GetTranslationsAttr().Set(trans)
animation_new.GetRotationsAttr().Set(rots)
animation_new.GetScalesAttr().Set(scales)
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_new_path])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_0_animation_create_1.png")
stage.RemovePrim(animation_new_path)
skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #This line should supposed not to be needed #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_1_animation_delete_0.png")
with Usd.EditContext(stage, session_layer):
animation_new = UsdSkel.Animation.Define(stage, animation_new_path)
animation_new_prim = animation_new.GetPrim()
await wait_for_update()
self.assertTrue(animation_new_prim)
with Sdf.ChangeBlock():
animation_new.GetJointsAttr().Set(joints)
animation_new.GetTranslationsAttr().Set(trans)
animation_new.GetRotationsAttr().Set(rots)
animation_new.GetScalesAttr().Set(scales)
skeleton_bindingAPI.GetAnimationSourceRel().SetTargets([animation_new_path])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_2_animation_create_sessionlayer_0.png")
with Sdf.ChangeBlock():
stage.RemovePrim(animation_new_path)
skeleton_bindingAPI.GetAnimationSourceRel().ClearTargets(False) #This line should supposed not to be needed #TODO 05 when skelanimation become invalid, skinning result should retrive restTransform
skel_root_prim = stage.GetPrimAtPath("/Root/group1")
skel_root = UsdSkel.Root(skel_root_prim)
visible = skel_root.GetVisibilityAttr().Set("invisible")
await wait_for_update() # test repopulate crash due to resync by update visibility in skelroot.
skel_root.GetVisibilityAttr().Set("inherited")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "03_skelanim_create_delete_3_animation_delete_with_root_recync_sessionlayer_0.png")
#This test is temporarily since we cannot dynamically update animation source on skelroot's bindAPI in omnihydra yet.
async def test_04_skel_anim_on_skel_root(self):
"""
Test hydra skel - skel anim on root
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder_root.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skelroot_path = "/Root/group1"
skelroot_prim = stage.GetPrimAtPath(skelroot_path)
skelroot = UsdSkel.Root(skelroot_prim)
skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim)
skeleton_path = "/Root/group1/joint1"
skeleton_prim = stage.GetPrimAtPath(skeleton_path)
skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim)
skeleton = UsdSkel.Skeleton(skeleton_prim)
animation_static_path = "/Root/group1/joint1/Animation_Static"
animation_static_prim = stage.GetPrimAtPath(animation_static_path)
animation_static = UsdSkel.Animation(animation_static_prim)
animation_path = "/Root/group1/joint1/Animation"
animation_prim = stage.GetPrimAtPath(animation_path)
animation = UsdSkel.Animation(animation_prim)
animation_flat_path = "/Root/group1/joint1/Animation_Flat"
animation_flat_prim = stage.GetPrimAtPath(animation_flat_path)
aniamtion_flat = UsdSkel.Animation(animation_flat_prim)
animation_outside_path = "/ZAnimation"
animation_outside_prim = stage.GetPrimAtPath(animation_outside_path)
aniamtion_outside = UsdSkel.Animation(animation_outside_prim)
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
timeline.play()
timeline.set_auto_update(False)
timeline.set_current_time(0.0)
await omni.kit.app.get_app().next_update_async()
# pure skeleton test
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_0_skeleton_0.png")
#Test animation
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
timeline.set_current_time(0.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_1.png")
timeline.set_current_time(1.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "04_skelanim_on_root_1_animation_2.png")
timeline.set_auto_update(True)
timeline.stop()
await omni.kit.app.get_app().next_update_async()
async def test_05_skel_anim_update_restTransforms(self):
"""
Test hydra skel - update restTransforms
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder.usda")
# self.set_settings(postLoadSkelTestSettings)
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skelroot_path = "/Root/group1"
skelroot_prim = stage.GetPrimAtPath(skelroot_path)
skelroot = UsdSkel.Root(skelroot_prim)
skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim)
skeleton_path = "/Root/group1/joint1"
skeleton_prim = stage.GetPrimAtPath(skeleton_path)
skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim)
skeleton = UsdSkel.Skeleton(skeleton_prim)
animation_static_path = "/Root/group1/joint1/Animation_Static"
animation_static_prim = stage.GetPrimAtPath(animation_static_path)
animation_static = UsdSkel.Animation(animation_static_prim)
animation_path = "/Root/group1/joint1/Animation"
animation_prim = stage.GetPrimAtPath(animation_path)
animation = UsdSkel.Animation(animation_prim)
animation_flat_path = "/Root/group1/joint1/Animation_Flat"
animation_flat_prim = stage.GetPrimAtPath(animation_flat_path)
aniamtion_flat = UsdSkel.Animation(animation_flat_prim)
animation_outside_path = "/ZAnimation"
animation_outside_prim = stage.GetPrimAtPath(animation_outside_path)
aniamtion_outside = UsdSkel.Animation(animation_outside_prim)
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
timeline.play()
timeline.set_auto_update(False)
timeline.set_current_time(0.0)
await omni.kit.app.get_app().next_update_async()
# pure skeleton test
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_0_skeleton_0.png")
#Test animation
self.assertTrue(not skeleton_bindingAPI.GetInheritedAnimationSource())
timecode = Usd.TimeCode.Default()
poses = animation.GetTransforms(timecode)
skeleton.GetRestTransformsAttr().Set(poses)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_0.png")
timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond())
poses = animation.GetTransforms(timecode)
skeleton.GetRestTransformsAttr().Set(poses)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_1.png")
timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond())
poses = animation.GetTransforms(timecode)
skeleton.GetRestTransformsAttr().Set(poses)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_2.png")
with Usd.EditContext(stage, session_layer):
timecode = Usd.TimeCode.Default()
poses = animation.GetTransforms(timecode)
skeleton.GetRestTransformsAttr().Set(poses)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_0.png")
timecode = Usd.TimeCode(0.5 * stage.GetTimeCodesPerSecond())
poses = animation.GetTransforms(timecode)
skeleton.GetRestTransformsAttr().Set(poses)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_1.png")
timecode = Usd.TimeCode(1.0 * stage.GetTimeCodesPerSecond())
poses = animation.GetTransforms(timecode)
skeleton.GetRestTransformsAttr().Set(poses)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "05_skelanim_update_restTransforms_1_animation_session_layer_2.png")
timeline.set_auto_update(True)
timeline.stop()
await omni.kit.app.get_app().next_update_async()
async def test_06_skel_anim_reference(self):
"""
Test hydra skel - skel anim reference
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder_ref.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skelroot_path = "/Root/group1"
skelroot_prim = stage.GetPrimAtPath(skelroot_path)
skelroot = UsdSkel.Root(skelroot_prim)
skelroot_bindingAPI = UsdSkel.BindingAPI(skelroot_prim)
skeleton_path = "/Root/group1/joint1"
skeleton_prim = stage.GetPrimAtPath(skeleton_path)
skeleton_bindingAPI = UsdSkel.BindingAPI(skeleton_prim)
skeleton = UsdSkel.Skeleton(skeleton_prim)
animation_static_path = "/Root/group1/joint1/Animation_Static"
animation_static_prim = stage.GetPrimAtPath(animation_static_path)
animation_static = UsdSkel.Animation(animation_static_prim)
animation_path = "/Root/group1/joint1/Animation"
animation_prim = stage.GetPrimAtPath(animation_path)
animation = UsdSkel.Animation(animation_prim)
animation_flat_path = "/Root/group1/joint1/Animation_Flat"
animation_flat_prim = stage.GetPrimAtPath(animation_flat_path)
aniamtion_flat = UsdSkel.Animation(animation_flat_prim)
animation_outside_path = "/ZAnimation"
animation_outside_prim = stage.GetPrimAtPath(animation_outside_path)
aniamtion_outside = UsdSkel.Animation(animation_outside_prim)
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
timeline.play()
timeline.set_auto_update(False)
timeline.set_current_time(0.0)
await omni.kit.app.get_app().next_update_async()
# pure skeleton tests
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_0_skeleton_0.png")
# Test animation
self.assertTrue(skeleton_bindingAPI.GetInheritedAnimationSource() == animation_prim)
refs = animation_prim.GetReferences()
refs.SetReferences([Sdf.Reference(assetPath="./assets/skelcylinder_anim_flat.usda")])
timeline.set_current_time(0.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_0.png")
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_1.png")
timeline.set_current_time(1.0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "06_skelanim_reference_1_animation_reference_2.png")
timeline.set_auto_update(True)
timeline.stop()
async def test_07_skel_mesh_material_switch(self):
"""
Test hydra skel - skel anim reference
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder_material_test.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skelmesh1_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder1"
skelmesh1_prim = stage.GetPrimAtPath(skelmesh1_path)
skelmesh2_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder2"
skelmesh2_prim = stage.GetPrimAtPath(skelmesh2_path)
print(skelmesh2_prim)
material_red_path = "/Root/Looks/PreviewSurface_Red"
material_blue_path = "/Root/Looks/PreviewSurface_Blue"
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
timeline.play()
timeline.set_auto_update(False)
timeline.set_current_time(0.0)
await wait_for_update()
# pure skeleton tests
timeline.set_current_time(0.1)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_0.png")
# Test animations
omni.kit.commands.execute(
"BindMaterial",
prim_path=Sdf.Path(skelmesh1_path),
material_path=Sdf.Path(material_blue_path),
strength=UsdShade.Tokens.weakerThanDescendants,
)
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_1.png")
omni.kit.commands.execute(
"BindMaterial",
prim_path=Sdf.Path(skelmesh2_path),
material_path=Sdf.Path(material_red_path),
strength=UsdShade.Tokens.weakerThanDescendants,
)
timeline.set_current_time(0.6)
await wait_for_update()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_2.png")
imageable = UsdGeom.Imageable(skelmesh2_prim)
imageable.MakeInvisible()
timeline.set_current_time(0.7)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "07_skel_mesh_material_switch_3.png")
timeline.set_auto_update(True)
timeline.stop()
async def test_08_skel_mesh_animation_rename(self):
"""
Test hydra skel - skel anim reference
"""
self.set_settings(testSettings)
super().open_usd("hydra/skel/skelcylinder_material_test.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadSkelTestSettings)
stage = self.ctx.get_stage()
skelmesh1_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder1"
skelmesh1_prim = stage.GetPrimAtPath(skelmesh1_path)
skelmesh2_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_pCylinder2"
skelmesh2_prim = stage.GetPrimAtPath(skelmesh2_path)
animation_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_joint1/Animation"
animation_prim = stage.GetPrimAtPath(animation_path)
new_animation_path = "/Root/BLENDWEIGHT_group1/BLENDWEIGHT_joint1/Animation2"
session_layer = stage.GetSessionLayer()
timeline = omni.timeline.get_timeline_interface()
timeline.play()
timeline.set_auto_update(False)
timeline.set_current_time(0.0)
await wait_for_update()
# pure skeleton tests
timeline.set_current_time(0.5)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_0.png")
old_prim_name = Sdf.Path(animation_path)
move_dict = {old_prim_name: new_animation_path}
omni.kit.commands.execute("MovePrims", paths_to_move=move_dict, destructive=False)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_1.png")
omni.kit.undo.undo()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_2.png")
# Test animations
omni.kit.commands.execute(
"DeletePrims",
paths=[Sdf.Path(animation_path)]
)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_3.png")
omni.kit.undo.undo()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "08_skel_mesh_animation_rename_4.png")
timeline.set_auto_update(True)
timeline.stop()
| 40,592 | Python | 50.448669 | 212 | 0.674985 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_light_collections.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.commands
import omni.kit.undo
from .test_hydra_common import RtxHydraTest
from .test_common import wait_for_update
class TestRtxHydraLightCollections(RtxHydraTest):
""" To run:
from omni.kit.test import unittests
from omni.rtx.tests import test_hydra_light_collections
unittests.run_tests_in_modules([test_hydra_light_collections])
"""
TEST_PATH = "hydra/lightCollections"
LIGHT_PATH = "/World/defaultLight"
LIGHT_VIS_PATH = LIGHT_PATH + ".visibility"
LIGHT_SHADOW_EXCLUDE_PATH = LIGHT_PATH + ".collection:shadowLink:excludes"
LIGHT_LINK_INCLUDE_PATH = LIGHT_PATH + ".collection:lightLink:includeRoot"
CUBE_PATH = "/World/Cube"
SHADOW_LINK_INCLUDE_PATH = LIGHT_PATH + ".collection:shadowLink:includeRoot"
async def test_UNSTABLE_light_collection_undo(self):
"""
Regression test for usdImaging refresh issue when undoing light deletion
"""
self.open_usd("hydra/LightLink.usda")
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-4)
omni.kit.commands.execute("DeletePrims", paths=[self.LIGHT_PATH])
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-4)
omni.kit.undo.undo()
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-4)
# OM-56283, CI-1655 - Sporadic crash/unreliable image output
async def test_UNSTABLE_light_collection_toggle_crash_UNSTABLE(self):
"""
Regression test for crash in Light Collection toggle
"""
self.open_usd("hydra/LightLink.usda")
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3)
omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=True, prev=False)
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionInactive.png", 1e-3)
omni.kit.commands.execute("ChangeProperty", prop_path=self.SHADOW_LINK_INCLUDE_PATH, value=False, prev=True)
await wait_for_update(wait_frames=1)
omni.kit.commands.execute("ChangeProperty", prop_path=self.SHADOW_LINK_INCLUDE_PATH, value=True, prev=False)
await wait_for_update(wait_frames=1)
omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=False, prev=True)
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3)
async def test_UNSTABLE_light_collection_lightvistoggle(self):
"""
Regression test for refresh issue when toggling light visibility
"""
self.open_usd("hydra/LightLink.usda")
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3)
omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_VIS_PATH, value="invisible", prev="inherited")
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-3)
omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_VIS_PATH, value="inherited", prev="invisible")
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionWorking.png", 1e-3)
# OM-53278 - occasionally produces pitch black image
async def test_UNSTABLE_light_collection_refresh_issue_when_light_and_shadow_are_the_same_UNSTABLE(self):
"""
Regression test for refresh issue when the light and shadow collections become the same
This is a regression test for OM-48040 Light Linking: light goes off after toggling Include Root on/off
"""
self.open_usd("hydra/LightLinkSimple.usda")
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoLight.png", 1e-3)
omni.kit.commands.execute(
"AddRelationshipTarget",
relationship=omni.usd.get_context().get_stage().GetPropertyAtPath(self.LIGHT_SHADOW_EXCLUDE_PATH),
target=self.CUBE_PATH
)
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoShadow.png", 1e-3)
omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=False, prev=True)
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionBlack.png", 1e-3)
omni.kit.commands.execute("ChangeProperty", prop_path=self.LIGHT_LINK_INCLUDE_PATH, value=True, prev=False)
await wait_for_update(wait_frames=25)
await self.capture_and_compare(self.TEST_PATH, "lightCollectionSimpleCubeNoShadow.png", 1e-3)
| 5,550 | Python | 43.766129 | 119 | 0.709369 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_postprocessing_tonemapper.py | ## Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.test
import omni.kit.commands
import carb
import pathlib
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
from .test_common import USD_DIR, EXTENSION_FOLDER_PATH
from pxr import Gf, Sdf, Usd
from pxr import UsdGeom, UsdLux
class TestRtxPostprocessingTonemapper(RtxTest):
TEST_PATH = "tonemapping"
def open_usd_scene(self, path : pathlib.Path):
omni.usd.get_context().open_stage(str(path))
def create_dome_light(self, name="/Xform/DomeLight"):
omni.kit.commands.execute(
"CreatePrim",
prim_path=name,
prim_type="DomeLight",
select_new_prim=False,
attributes={
UsdLux.Tokens.inputsIntensity: 1,
UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong,
UsdLux.Tokens.inputsTextureFile: str(EXTENSION_FOLDER_PATH.joinpath("data/usd/hydra/daytime.hdr")),
UsdGeom.Tokens.visibility: "inherited",
} if hasattr(UsdLux.Tokens, 'inputsIntensity') else {
UsdLux.Tokens.intensity: 1,
UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong,
UsdLux.Tokens.textureFile: str(EXTENSION_FOLDER_PATH.joinpath("data/usd/hydra/daytime.hdr")),
UsdGeom.Tokens.visibility: "inherited",
},
create_default_xform=True,
)
dome_light_prim = self.ctx.get_stage().GetPrimAtPath(name)
return dome_light_prim
async def setUp(self):
await self.setUp_internal()
carb.log_info("Setting up scene for RTX postprocessing tonemapping tests.")
# Setting that should be set before opening a new stage
self.set_settings(testSettings)
rtxDataPath = EXTENSION_FOLDER_PATH.joinpath("../../../../../data/usd/tests")
self.open_usd_scene(rtxDataPath.joinpath("BallCluster/ballcluster_stage.usda"))
# Settings that should be set after opening a new stage
self.set_settings(postLoadTestSettings)
# camera setup:
omni.kit.commands.execute('CreatePrimWithDefaultXform',
prim_path='/Ballcluster_set/Camera',
prim_type='Camera',
attributes={'focusDistance': 400, 'focalLength': 24, 'clippingRange': (1, 10000000)},
create_default_xform=False)
omni.kit.commands.execute('TransformPrimCommand',
path=Sdf.Path('/Ballcluster_set/Camera'),
new_transform_matrix=Gf.Matrix4d(-0.6550639249522971, 0.7555734605093614, 6.112664085837494e-16, 0.0,
0.008064090705444693, 0.006991371699474781, 0.9999430439594318, 0.0,
0.7555304260366915, 0.6550266151048126, -0.010672808306432642, 0.0,
543.7716131933593, 536.4127523809548, 92.10006955095595, 1.0),
old_transform_matrix=Gf.Matrix4d(-0.7071067811865474, 0.7071067811865478, 5.551115215516806e-17, 0.0,
-0.4082482839677534, -0.4082482839677533, 0.8164965874238357, 0.0,
0.5773502737830692, 0.5773502737830688, 0.5773502600027394, 0.0,
500.0, 500.0, 500.0, 1.0),
time_code=Usd.TimeCode.Default(),
had_transform_at_key=False,
usd_context_name='')
# Create a domelight to get some high dynamic range going:
self.domelight_prim = self.create_dome_light()
# Disable this object so that the dome light is actually visible:
omni.kit.commands.execute('DeletePrims', paths=['/Xform/sky_sphere_emiss'], destructive=False)
await wait_for_update()
# Activate the new camera:
viewport_api = omni.kit.viewport.utility.get_active_viewport()
viewport_api.set_active_camera("/Ballcluster_set/Camera")
await omni.kit.app.get_app().next_update_async()
my_settings = {
"/app/hydraEngine/waitIdle" : True,
"/app/renderer/waitIdle" : True,
"/app/asyncRenderingLowLatency" : False,
"/rtx-transient/resourcemanager/genMipsForNormalMaps" : False,
"/rtx-transient/resourcemanager/texturestreaming/async" : False,
"/rtx-transient/samplerFeedbackTileSize" : 1,
"/rtx/hydra/perMaterialSyncLoads" : True,
"/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA
"/renderer/multiGpu/maxGpuCount" : 1,
"/rtx/gatherColorToDisplayDevice" : True,
"/rtx/rendermode" : 'PathTracing',
"/rtx/raytracing/lightcache/spatialCache/enabled" : False,
"/rtx/pathtracing/lightcache/cached/enabled" : False,
"/rtx/pathtracing/cached/enabled" : False,
"/rtx/pathtracing/optixDenoiser/enabled" : False,
"/rtx/pathtracing/spp" : 1,
"/rtx/pathtracing/totalSpp" : 1,
"/rtx/pathtracing/maxBounces" : 2,
"/rtx/hydra/perMaterialSyncLoads" : True,
}
self.set_settings(my_settings)
await wait_for_update()
# Marking unstable due to OM-86613
async def test_UNSTABLE_postprocessing_tonemappers_UNSTABLE(self):
"""
Test RTX Postprocessing Tonemappers
"""
self.set_settings({"/rtx/post/tonemap/op" : "0"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "0_tonemapper_test_clamp.png")
# Make the domelight 'visible' for all non-clamp tonemappers
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
self.domelight_prim.GetAttribute(UsdLux.Tokens.inputsIntensity).Set(200)
else:
self.domelight_prim.GetAttribute(UsdLux.Tokens.intensity).Set(200)
self.set_settings({"/rtx/post/tonemap/op" : "1"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "1_tonemapper_test_linear.png")
self.set_settings({"/rtx/post/tonemap/op" : "2"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "2_tonemapper_test_reinhard.png")
self.set_settings({"/rtx/post/tonemap/op" : "3"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "3_tonemapper_test_reinhard_modified.png")
self.set_settings({"/rtx/post/tonemap/op" : "4"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "4_tonemapper_test_hejlhablealu.png")
self.set_settings({"/rtx/post/tonemap/op" : "5"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "5_tonemapper_test_hableuc2.png")
self.set_settings({"/rtx/post/tonemap/op" : "6"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "6_tonemapper_test_aces.png")
self.set_settings({"/rtx/post/tonemap/op" : "7"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "7_tonemapper_test_iray.png")
| 7,492 | Python | 44.689024 | 115 | 0.645889 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/__init__.py | import sys
if sys.platform == "win32":
from .test_example import TestRtxExample1, TestRtxExample2
from .test_selectionoutline import TestRtxSelectionOutline
from .test_hydra_mesh import *
from .test_hydra_points import *
from .test_hydra_basis_curves import *
from .test_hydra_skel import *
from .test_hydra_materials import *
from .test_scenedb import TestRtxSceneDb
from .test_hydra_light_collections import *
from .test_hydra_volume import *
from .test_domelight import TestRtxDomelight
from .test_postprocessing_tonemapper import *
from .test_light_toggling import *
from .test_usdlux_schema_compat import *
from .test_hydra_scene_delegate_omni_imaging import *
from .test_picking import *
from .test_material_distilling_toggle import *
# Enable other extensions to use these test classes
from .test_common import RtxTest, testSettings, postLoadTestSettings, OUTPUTS_DIR
| 944 | Python | 40.086955 | 81 | 0.745763 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_light_toggling.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.app
import omni.kit.test
import omni.kit.commands
import carb
import pathlib
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
from .test_common import EXTENSION_FOLDER_PATH
from pxr import Gf, Sdf, Usd
class TestRtxLightToggling(RtxTest):
TEST_PATH = "light_toggling"
def open_usd_scene(self, path : pathlib.Path):
omni.usd.get_context().open_stage(str(path))
async def setUp(self):
await self.setUp_internal()
carb.log_info("Setting up scene for RTX postprocessing tonemapping tests.")
self.set_settings(testSettings)
rtxDataPath = EXTENSION_FOLDER_PATH.joinpath("../../../../../data/usd/tests")
self.open_usd_scene(rtxDataPath.joinpath("KitchenSet/Kitchen_set.usda"))
# camera setup:
omni.kit.commands.execute('CreatePrimWithDefaultXform',
prim_path='/Kitchen_set/Camera',
prim_type='Camera',
attributes={'focusDistance': 400, 'focalLength': 24, 'clippingRange': (1, 10000000)},
create_default_xform=False)
omni.kit.commands.execute('TransformPrimCommand',
path=Sdf.Path('/Kitchen_set/Camera'),
new_transform_matrix=Gf.Matrix4d(
0.929103525371008, 0.36981973871491086, 9.165845166192454e-16, 0.0,
-0.07453993201486002, 0.18726775876424714, 0.9794766893921647, 0.0,
0.3622298133483562, -0.9100352451329841, 0.201557473037752, 0.0,
273.5074607559941, -621.0054603487383, 221.75447008156692, 1.0),
old_transform_matrix=Gf.Matrix4d(
0.9305632067779971, 0.36613128545789503, 9.159340032886883e-16, 0.0,
-0.09015111941855866, 0.22912905319151347, 0.9692123877928621, 0.0,
0.35485897742431627, -0.9019133876334855, 0.24622621174208614, 0.0,
328.2529492634561, -760.1471818173628, 259.74075506441545, 1.0),
time_code=Usd.TimeCode.Default(),
had_transform_at_key=False,
usd_context_name='')
# remove any selection, not sure why this happens, but otherwise weird bounding
# boxes appear
selection = omni.usd.get_context().get_selection()
selection.clear_selected_prim_paths()
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
my_settings = {
"/rtx/pathtracing/lightcache/cached/enabled": False,
"/rtx/raytracing/lightcache/spatialCache/enabled" : False,
"/rtx-transient/resourcemanager/genMipsForNormalMaps" : False,
"/rtx-transient/resourcemanager/texturestreaming/async" : False,
"/rtx-transient/samplerFeedbackTileSize" : 1,
"/rtx/post/aa/op" : 0, # 0 = None, 2 = FXAA
"/rtx/directLighting/sampledLighting/enabled" : False, # LTC gives consistent lighting
"/rtx/reflections/enabled" : False, # Disabling reflections.
"/rtx/reflections/sampledLighting/enabled" : False, # LTC gives consistent lighting
"/rtx/sceneDb/ambientLightIntensity" : float(0.0),
"/rtx/ambientOcclusion/enabled" : False,
"/rtx/indirectDiffuse/enabled" : False,
"/app/viewport/grid/enabled" : False, # Disable Kit Grid
"/app/viewport/grid/showOrigin" : False, # Disable Kit Origin
"/app/viewport/outline/enabled" : False, # Disable Selection drawing
}
self.set_settings(my_settings)
async def test_light_toggling(self):
"""
Test RTX Light Toggling
"""
LIGHT_VIS_PATH = ".visibility"
# Activate the main camera:
viewport_api = omni.kit.viewport.utility.get_active_viewport()
viewport_api.set_active_camera("/Kitchen_set/Camera")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "0_all_light_sources.png")
# Disable SphereLight
omni.kit.commands.execute("ChangeProperty", prop_path="/SphereLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "1_spherelight_off.png")
# Disable DiskLight
omni.kit.commands.execute("ChangeProperty", prop_path="/DiskLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "2_disklight_off.png")
# Disable DistantLight
# Disable RectLightLight
omni.kit.commands.execute("ChangeProperty", prop_path="/DistantLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited")
omni.kit.commands.execute("ChangeProperty", prop_path="/RectLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited")
omni.kit.commands.execute("ChangeProperty", prop_path="/DiskLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "3_two_lights_off_one_light_on.png")
# Enable Sphere Light
# Enable Rect Light
# Disable Cylinder Light
omni.kit.commands.execute("ChangeProperty", prop_path="/SphereLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible")
omni.kit.commands.execute("ChangeProperty", prop_path="/RectLight" + LIGHT_VIS_PATH, value="inherited", prev="invisible")
omni.kit.commands.execute("ChangeProperty", prop_path="/CylinderLight" + LIGHT_VIS_PATH, value="invisible", prev="inherited")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "4_one_light_off_two_lights_on.png")
| 6,132 | Python | 48.861788 | 133 | 0.664547 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_picking.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.undo
import omni.kit.test
import omni.usd
import carb
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
class TestRtxPicking(RtxTest):
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage.
await omni.kit.app.get_app().next_update_async() # Wait stage loading
self.set_settings(postLoadTestSettings)
async def test_picking_queue(self):
"""
Verify picking/query requests are successfully queued
"""
super().add_floor()
await wait_for_update()
# OM-80470: Verify all picking requests requested in consecutive frames are all queued and executed successfully
counter = 0
def query_complete(path, pos, *args, **kwargs):
nonlocal counter
counter += 1
import omni.kit.viewport
viewport = omni.kit.viewport.utility.get_active_viewport()
if hasattr(viewport, 'legacy_window'):
return
# Queue multiple query requests interrupted by a pick
center = [int(v * 0.5) for v in viewport.resolution]
viewport.request_query(center, query_complete, query_name="test_1")
viewport.request_query(center, query_complete, query_name="test_2")
viewport.request_pick(center, center, omni.usd.PickingMode.RESET_AND_SELECT)
viewport.request_query(center, query_complete, query_name="test_3")
viewport.request_query(center, query_complete, query_name="test_4")
await wait_for_update(wait_frames=40)
# All queries should complete
self.assertEqual(counter, 4)
| 2,268 | Python | 39.517856 | 130 | 0.694444 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_materials.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from sys import path
import omni.kit.app
import omni.kit.commands
import omni.kit.undo
import omni.kit.test
import omni.timeline
import carb.settings
from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest
from .test_common import testSettings, postLoadTestSettings, wait_for_update, USD_DIR
from pxr import Gf, Sdf, UsdGeom, UsdRender, UsdShade
import shutil, os, pathlib
class RtxHydraMaterialTest(RtxHydraTest):
TEST_PATH = "hydra/materials"
PRIM_PATH = "/World/box"
DATA_PATH = "hydra/materials/reload"
TEST_CLASS = ""
# need to use the real path in order to have the filewatching work properly
# -> client library ticket: https://nvidia-omniverse.atlassian.net/browse/CC-168
def getDataPath(self, relativePath) -> str:
data_path : str = USD_DIR.joinpath(self.DATA_PATH, relativePath)
return pathlib.Path(os.path.normpath(data_path)).resolve()
# helper to override the test files
# in case we want to do more or use another function
def copyTestFile(self, source : str, target : str):
shutil.copy(self.getDataPath(source), self.getDataPath(target))
# delete the temporary file created
def cleanupTestFile(self, target : str):
os.remove(self.getDataPath(target))
# basic structure of a test case init
async def initTest(self, caseName: str):
goldenImage = f"reload-{self.TEST_CLASS}-{caseName}.png"
# compare
await wait_for_update(wait_frames=10)
await self.capture_and_compare(self.TEST_PATH, goldenImage)
# basic structure of a test case
async def changeMdlAndTest(self, caseName: str, moduleToChange: str, threshold=None):
sourceFile = f"{self.TEST_CLASS}/{caseName}.mdl"
targetFile = f"{self.TEST_CLASS}/{moduleToChange}.mdl"
goldenImage = f"reload-{self.TEST_CLASS}-{caseName}.png"
if threshold is None:
threshold = self.THRESHOLD
# change MDL
self.copyTestFile(sourceFile, targetFile)
# compare
await wait_for_update(wait_frames=10)
await self.capture_and_compare(self.TEST_PATH, goldenImage, threshold)
class TestRtxHydraMaterialsReloadBasic(RtxHydraMaterialTest):
MEDIUM_THRESHOLD = 3.0e-5
async def setUp(self):
self.TEST_CLASS = "basic"
await self.setUp_internal()
self.set_settings(testSettings)
# prepare initial MDL module
self.copyTestFile("basic/A_init.mdl", "basic/A.mdl")
# load the test scene
scenePath = self.getDataPath("basic/XYZ.usda")
print(f"Scene Path: {scenePath}")
super().open_usd(scenePath)
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
async def test_touch_no_change(self):
"""
Test hydra materials - reload basic - touch, no change
"""
# make sure we start with the right material
await self.initTest("A_init")
# touch the file by copying the same file again
await self.changeMdlAndTest("A_init", "A", self.MEDIUM_THRESHOLD)
# remove the temp file
self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl")
async def test_change_body(self):
"""
Test hydra materials - reload basic - change body
"""
# make sure we start with the right material
await self.initTest("A_init")
# make multiple changes in a row
await self.changeMdlAndTest("A_change_body_1", "A", self.MEDIUM_THRESHOLD)
await self.changeMdlAndTest("A_change_body_2", "A", self.MEDIUM_THRESHOLD)
# remove the temp file
self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl")
class TestRtxHydraMaterialsReloadSignature(RtxHydraMaterialTest):
async def setUp(self):
self.TEST_CLASS = "signature"
await self.setUp_internal()
self.set_settings(testSettings)
# prepare initial MDL module
self.copyTestFile("signature/A_init.mdl", "signature/A.mdl")
# load the test scene
scenePath = self.getDataPath("signature/A.usda")
print(f"Scene Path: {scenePath}")
super().open_usd(scenePath)
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
async def test_change_signature(self):
"""
Test hydra materials - reload signature - change signature
"""
# make sure we start with the right material
await self.initTest("A_init")
# run test cases
await self.changeMdlAndTest("A_add_parameter", "A")
await self.changeMdlAndTest("A_rename_parameter", "A")
await self.changeMdlAndTest("A_move_parameter", "A")
await self.changeMdlAndTest("A_change_parameter_default", "A")
await self.changeMdlAndTest("A_change_parameter_type", "A")
await self.changeMdlAndTest("A_remove_parameter", "A")
# remove the temp file
self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl")
class TestRtxHydraMaterialsReloadGraph(RtxHydraMaterialTest):
async def setUp(self):
self.TEST_CLASS = "graph"
await self.setUp_internal()
self.set_settings(testSettings)
# prepare initial MDL module
self.copyTestFile("graph/A_init.mdl", "graph/A.mdl")
# load the test scene
scenePath = self.getDataPath("graph/GraphA.usda")
print(f"Scene Path: {scenePath}")
super().open_usd(scenePath)
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
# Unstable via OM-53607
async def test_UNSTABLE_change_function_body_UNSTABLE(self):
"""
Test hydra materials - reload graph - change function body
"""
# make sure we start with the right material
await self.initTest("A_init")
# run test cases
await self.changeMdlAndTest("A_change_function_body", "A")
await self.changeMdlAndTest("A_change_function_param_defaults", "A")
await self.changeMdlAndTest("A_add_function_param", "A")
await self.changeMdlAndTest("A_move_function_param", "A")
await self.changeMdlAndTest("A_remove_function_param", "A")
# remove the temp file
self.cleanupTestFile(f"{self.TEST_CLASS}/A.mdl")
class TestRtxHydraMaterialsDebugMode(RtxHydraMaterialTest):
async def setUp(self):
self.TEST_CLASS = "debugMode"
await self.setUp_internal()
self.set_settings(testSettings)
async def test_whiteMode(self):
"""
Test hydra materials - toggling white mode
"""
super().open_usd("hydra/materials/two_spheres.usda")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_off.png", 1e-4)
self.set_settings({"/rtx/debugMaterialType": 0})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on.png", 1e-4)
shader = self.ctx.get_stage().GetPrimAtPath("/World/Looks/PreviewSurface/Shader")
attr = shader.GetAttribute("inputs:excludeFromWhiteMode")
attr.Set(1)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on_withExclude.png", 1e-4)
attr.Set(0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_on_withoutExclude.png", 1e-4)
self.set_settings({"/rtx/debugMaterialType": -1})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "materials_whiteMode_off_again.png", 1e-4)
class TestRtxHydraMaterialStdModules(RtxHydraTest):
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
super().open_usd("hydra/materials/stdmodules/test_std_modules.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
async def test_load_stdmodules(self):
await wait_for_update(wait_frames=10)
await self.capture_and_compare("hydra/materials", "stdmodules.png")
| 8,611 | Python | 37.446428 | 105 | 0.66926 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_basis_curves.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.timeline
from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest
from .test_common import wait_for_update, postLoadTestSettings
from pxr import Sdf, Vt, UsdGeom, UsdShade
simplePts = [(0, -100, 0), (50, -50, 0), (-50, 50, 0), (0, 100, 0)]
simpleCnt = len(simplePts)
linearPts = [(0, -100, 0), (50, 0, 0), (0, 100, 0)]
linearCnt = len(linearPts)
bezierPts = [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)]
bezierCnt = len(bezierPts)
bsplinePts = [(0, -200, 0), (25, -25, 0), (-25, 0, 0), (50, 25, 0), (0, 200, 0)]
bsplineCnt = len(bsplinePts)
catromPts = [(0, -200, 0), (25, -50, 0), (-25, -15, 0), (-25, 15, 0), (50, 50, 0), (0, 200, 0)]
catromCnt = len(catromPts)
periodicPts = [(-200, -200, 0), (200, -200, 0), (200, 200, 0), (-200, 200, 0)]
periodicCnt = len(periodicPts)
bezierPeriodicPts = [(0, -200, 0), (-100, -200, 0), (-200, -100, 0), (-200, 0, 0), (-200, 100, 0), (-100, 200, 0), (0, 200, 0), (100, 200, 0), (200, 100, 0)]
bezierPeriodicCnt = len(bezierPeriodicPts)
class TestRtxHydraBasisCurves(RtxHydraTest):
TEST_PATH = "hydra/basisCurves"
PRIM_PATH = "/World/curve"
async def setUp(self):
await super().setUp()
timeline = omni.timeline.get_timeline_interface()
self.set_settings({"/rtx/hydra/curves/enabled": True,
"/rtx/hydra/curves/splits": 1})
def _create_geometry(self, cnt, v, widthInterpolation="constant", width=None, basis="bezier", type="cubic", wrap="nonperiodic", name=PRIM_PATH):
curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name)
curve.CreateCurveVertexCountsAttr(cnt)
curve.CreatePointsAttr(v)
curve.SetWidthsInterpolation(widthInterpolation)
curve.CreateWidthsAttr(width if width else [20])
curve.CreateBasisAttr(basis)
curve.CreateTypeAttr(type)
curve.CreateWrapAttr(wrap)
return curve
async def create_geometry_and_test(self, golden, *args, **kwargs):
self._create_geometry(*args, **kwargs)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, golden)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
async def create_geometry_and_test_primvar(self, golden, pvName, pvType, pvInterp, pvData, *args, **kwargs):
self._create_geometry(*args, **kwargs)
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar(pvName, pvType, pvInterp)
attr.Set(pvData)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, golden)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
def create_geometry(self, name=PRIM_PATH):
curve = self._create_geometry([simpleCnt], simplePts, name=name)
return curve
async def test_visibility(self):
"""
Test hydra basis curves - visibility
"""
await self.visibility()
async def test_doNotCastShadow(self):
"""
Test hydra basis curves - doNotCastShadow toggle
"""
self.create_geometry_with_floor()
await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows")
async def test_matteObject(self):
"""
Test hydra basis curves - isMatteObject toggle
"""
self.create_geometry_with_floor()
await self.matte()
async def test_hideForCamera(self):
"""
Test hydra basis curves - hideForCamera toggle
"""
self.create_geometry_with_floor()
await self.toggle_primvar(self.PRIM_PATH, "hideForCamera")
async def test_transform(self):
"""
Test hydra basis curves - tranform
"""
await self.transform_all()
async def test_display_color(self):
"""
Test hydra basis curves - change display color
"""
# Constant
geom = self.create_geometry()
geom.CreateDisplayColorPrimvar("constant").Set([(0, 1, 0)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "displayColorConstant.png")
return geom
async def test_widths(self):
"""
Test hydra basis curves - change width
"""
await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts, "constant", [20, 19])
await self.create_geometry_and_test("widthDefault.png", [bezierCnt], bezierPts, "constant", [])
await self.create_geometry_and_test("widthLinear.png", [linearCnt], linearPts, "vertex", [0, 30, 0], type="linear")
await self.create_geometry_and_test("widthVertex.png", [bezierCnt], bezierPts, "vertex", [0, 10, 20, 30, 20, 10, 0])
await self.create_geometry_and_test("widthBsplineVertex.png", [bsplineCnt], bsplinePts, "vertex", [0, 10, 30, 10, 0], "bspline")
await self.create_geometry_and_test("widthLinear.png", [linearCnt], linearPts, "varying", [0, 30, 0], type="linear")
await self.create_geometry_and_test("widthVarying.png", [bezierCnt], bezierPts, "varying", [10, 30, 50])
await self.create_geometry_and_test("widthBsplineVarying.png", [bsplineCnt], bsplinePts, "varying", [10, 30, 10], "bspline")
pts2 = bezierPts + [(p[0], p[1], 50) for p in bezierPts]
await self.create_geometry_and_test("widthConstant.png", [bezierCnt, bezierCnt], pts2, "constant", [30])
await self.create_geometry_and_test("widthUniform.png", [bezierCnt, bezierCnt], pts2, "uniform", [10, 30])
lPts2 = linearPts + [(p[0], p[1], 50) for p in linearPts]
await self.create_geometry_and_test("widthLinear2.png", [linearCnt, linearCnt], lPts2, "varying", [10, 30, 50, 5, 35, 5], type="linear")
await self.create_geometry_and_test("widthVarying2.png", [bezierCnt, bezierCnt], pts2, "varying", [10, 30, 50, 5, 35, 5])
bsPts2 = bsplinePts + [(p[0], p[1], 50) for p in bsplinePts]
await self.create_geometry_and_test("widthBsplineVarying2.png", [bsplineCnt, bsplineCnt], bsPts2, "varying", [10, 30, 50, 5, 35, 5], "bspline")
async def test_points(self):
"""
Test hydra basis curves - update points
"""
pts = [simplePts, simplePts.copy()]
pts[1][1] = (-50, -50, 0)
pts[1][2] = (50, 50, 0)
await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"])
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# TODO fix curves for delayed points assignments
# curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), self.PRIM_PATH)
# curve.CreateWidthsAttr([20])
# await wait_for_update()
# await self.capture_and_compare(self.TEST_PATH, "empty.png")
# curve.CreateCurveVertexCountsAttr([simpleCnt])
# curve.CreatePointsAttr(simplePts)
# await wait_for_update()
# await self.capture_and_compare(self.TEST_PATH, "empty.png")
async def test_skip_processing(self):
"""
Test hydra basis curves - skipProcessing attribute
"""
geom = self.create_geometry()
geom.GetPrim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool).Set(True)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "empty.png")
async def test_topology_wrap(self):
"""
Test hydra basis curves - wrap
"""
# bspline:
await self.create_geometry_and_test("bsplinePinned.png", [bsplineCnt], bsplinePts, "constant", [20], "bspline", "cubic", "pinned")
await self.create_geometry_and_test("bsplinePinned2.png", [bsplineCnt, bsplineCnt],
bsplinePts + [(p[0], p[1], 50) for p in bsplinePts], "constant", [20], "bspline", "cubic", "pinned")
# catmullRom
await self.create_geometry_and_test("catmullRomPinned.png", [catromCnt], catromPts, "constant", [20], "catmullRom", "cubic", "pinned")
await self.create_geometry_and_test("catmullRomPinned2.png", [catromCnt, catromCnt],
catromPts + [(p[0], p[1], 50) for p in catromPts], "constant", [20], "catmullRom", "cubic", "pinned")
# bspline:
await self.create_geometry_and_test("bsplinePeriodic.png", [periodicCnt], periodicPts, "constant", [20], "bspline", "cubic", "periodic")
await self.create_geometry_and_test("bsplinePeriodic2.png", [periodicCnt, periodicCnt],
periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "bspline", "cubic", "periodic")
# catmullRom
await self.create_geometry_and_test("catmullRomPeriodic.png", [periodicCnt], periodicPts, "constant", [20], "catmullRom", "cubic", "periodic")
await self.create_geometry_and_test("catmullRomPeriodic2.png", [periodicCnt, periodicCnt],
periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "catmullRom", "cubic", "periodic")
# bezier
await self.create_geometry_and_test("bezierPeriodic.png", [bezierPeriodicCnt], bezierPeriodicPts, "constant", [20], "bezier", "cubic", "periodic")
# linear
await self.create_geometry_and_test("linearPeriodic.png", [periodicCnt], periodicPts, type="linear", wrap="periodic")
async def test_topology_basis(self):
"""
Test hydra basis curves - topology basis
"""
# linear: 2 + (n - 1)
await self.create_geometry_and_test("linear.png", [linearCnt], linearPts, type="linear")
await self.create_geometry_and_test("linear2.png", [linearCnt, linearCnt], linearPts + [(p[0], p[1], 50) for p in linearPts], type="linear", wrap="nonperiodic")
# bezier: 4 + 3 * (n - 1) pts
await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts, "constant", [20], "bezier", "cubic", "nonperiodic")
# # more points than needed, but this is ok
await self.create_geometry_and_test("bezier.png", [bezierCnt], bezierPts + [(0, 0, 0)])
# # indices - ibychkov: is this supported? How it can be set?
# bspline: 4 + (n - 1) pts
await self.create_geometry_and_test("bspline.png", [bsplineCnt], bsplinePts, "constant", [20], "bspline", "cubic", "nonperiodic")
# catmullRom
await self.create_geometry_and_test("catmullRom.png", [catromCnt], catromPts, "constant", [20], "catmullRom", "cubic", "nonperiodic")
# Ribbons - Not supported - OM-36882
async def test_topology_incorrect(self):
"""
Test hydra basis curves - incorrect topology
"""
efn = "empty.png"
# test incorrect number of points
# linear
await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], type="linear")
await self.create_geometry_and_test(efn, [2], [(0, -100, 0), (-100, 0, 0)], type="linear", wrap="periodic")
# bezier
await self.create_geometry_and_test(efn, [0], [])
await self.create_geometry_and_test(efn, [4], [])
await self.create_geometry_and_test(efn, [1], [(0, -100, 0), (50, -50, 0), (0, 0, 0), (-50, 50, 0), (0, 100, 0)])
await self.create_geometry_and_test(efn, [1], [(0, -100, 0)])
await self.create_geometry_and_test(efn, [2], [(0, -100, 0), (50, -50, 0)])
await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)])
await self.create_geometry_and_test(efn, [4], [(0, -100, 0)])
await self.create_geometry_and_test(efn, [5], [(0, -100, 0), (50, -50, 0), (0, 0, 0), (-50, 50, 0), (0, 100, 0), (50, 150, 0)])
await self.create_geometry_and_test(efn, [7], [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)], "constant", [20], "bezier", "cubic", "periodic")
await self.create_geometry_and_test(efn, [7, 7], [(0, -100, 0), (25, -25, 0), (50, 0, 0), (0, 25, 0), (-50, 50, 0), (-25, 75, 0), (0, 100, 0)])
# bspline
await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)], basis="bspline")
await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "bspline", "cubic", "periodic")
await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "bspline", "cubic", "pinned")
# catmullRom
await self.create_geometry_and_test(efn, [3], [(0, -100, 0), (50, -50, 0), (0, 0, 0)], basis="catmullRom")
await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "catmullRom", "cubic", "periodic")
await self.create_geometry_and_test(efn, [1], [(0, -100, 0)], "constant", [20], "catmullRom", "cubic", "pinned")
# pinned wrap, bezier
await self.create_geometry_and_test("empty.png", [bezierCnt], bezierPts, "constant", [20], "bezier", "cubic", "pinned")
# test incorrect number of widths
pts2 = bezierPts + [(p[0], p[1], 50) for p in bezierPts]
await self.create_geometry_and_test(efn, [bezierCnt], bezierPts, "vertex", [0, 10, 20, 30, 20, 10])
await self.create_geometry_and_test(efn, [bezierCnt], bezierPts, "varying", [20])
await self.create_geometry_and_test(efn, [bezierCnt, bezierCnt], pts2, "uniform", [20])
# test incorrect number of display color
async def test_normal_and_tangents(self):
"""
Test hydra basis curves - normal and tangents
"""
self.set_settings({"/rtx/debugView/target": "normal"})
await self.create_geometry_and_test("normalLinear.png", [linearCnt], linearPts, "constant", [40], type="linear")
await self.create_geometry_and_test("normal.png", [bezierCnt], bezierPts, "constant", [40])
await self.create_geometry_and_test("normalBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline")
await self.create_geometry_and_test("normalCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom")
self.set_settings({"/rtx/debugView/target": "tangentu"})
await self.create_geometry_and_test("tangentuLinear.png", [linearCnt], linearPts, "constant", [40], type="linear")
await self.create_geometry_and_test("tangentu.png", [bezierCnt], bezierPts, "constant", [40])
await self.create_geometry_and_test("tangentuBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline")
await self.create_geometry_and_test("tangentuCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom")
self.set_settings({"/rtx/debugView/target": "tangentv"})
await self.create_geometry_and_test("tangentvLinear.png", [linearCnt], linearPts, "constant", [40], type="linear")
await self.create_geometry_and_test("tangentv.png", [bezierCnt], bezierPts, "constant", [40])
await self.create_geometry_and_test("tangentvBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline")
await self.create_geometry_and_test("tangentvCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom")
async def test_texCoords(self):
"""
Test hydra basis curves - texCoords (UVs)
"""
self.set_settings({"/rtx/debugView/target": "texcoord0"})
await self.create_geometry_and_test("texCoordsLinear.png", [linearCnt], linearPts, "vertex", [10, 30, 50], type="linear")
await self.create_geometry_and_test("texCoords.png", [bezierCnt], bezierPts, "varying", [10, 30, 50])
await self.create_geometry_and_test("texCoordsBspline.png", [bsplineCnt], bsplinePts, "constant", [40], "bspline")
await self.create_geometry_and_test("texCoordsCatrom.png", [catromCnt], catromPts, "constant", [40], "catmullRom")
async def test_texCoords2(self):
"""
Test hydra basis curves - texCoords (UVs) set 2. Defined by asset.
"""
self.set_settings({"/rtx/debugView/target": "texcoord1"})
await self.create_geometry_and_test_primvar("texCoords2Vertex.png",
"uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex,
[(0, 0), (0.15, 0), (0.3, 0), (0.5, 0), (0.7, 0), (0.85, 0), (1, 0)],
[bezierCnt], bezierPts, "varying", [10, 30, 50])
await self.create_geometry_and_test_primvar("texCoords2Uniform.png",
"uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform,
[(0, 0.5), (1, 0)],
[bezierCnt, bezierCnt], bezierPts + [(p[0], p[1], 50) for p in bezierPts])
# Pinned wrap
await self.create_geometry_and_test_primvar("texCoords2VertexPinned.png",
"uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex,
[(0, 0), (0.3, 0), (0.5, 0), (0.7, 0), (1, 0)],
[bsplineCnt], bsplinePts, "constant", [30], "bspline", "cubic", "pinned")
await self.create_geometry_and_test_primvar("texCoords2UniformPinned.png",
"uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform,
[(0, 0.5), (1, 0)],
[bsplineCnt, bsplineCnt], bsplinePts + [(p[0], p[1], 50) for p in bsplinePts], "constant", [20], "bspline", "cubic", "pinned")
# Peropdic wrap
await self.create_geometry_and_test_primvar("texCoords2VertexPeriodic.png",
"uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex,
[(0, 0), (0.3, 0), (0.5, 0), (1, 0)],
[periodicCnt], periodicPts, "constant", [30], "bspline", "cubic", "periodic")
await self.create_geometry_and_test_primvar("texCoords2UniformPeriodic.png",
"uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.uniform,
[(0, 0.5), (1, 0)],
[periodicCnt, periodicCnt], periodicPts + [(p[0], p[1], 50) for p in periodicPts], "constant", [20], "bspline", "cubic", "periodic")
async def test_endcaps(self):
"""
Test hydra basis curves - endcaps.
For cubic curves - flat and open
For linear curves - only round
"""
self._create_geometry([bezierCnt], bezierPts, "varying", [30, 30, 50])
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
pv = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("endcaps", Sdf.ValueTypeNames.Int)
# Flat
pv.Set(1)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "endcapFlat.png")
# Open
pv.Set(0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "endcapOpen.png")
# OM-55978: Discontinuity along curves or hair fibers when the endcaps option set to open
self.set_camera((1.25, 1.25, 1.25), (0, 0, 0))
self.set_settings({"/rtx/debugView/target": "normal"})
self._create_geometry([4], [(0, -10, 0), (0, 0, 0), (0, 10, 0), (0, 20, 0)], "constant", [1], "bspline", "cubic", "pinned")
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
pv = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("endcaps", Sdf.ValueTypeNames.Int)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "om55978.png")
async def test_numsplits(self):
"""
Test hydra basis curves - numSplits.
For cubic curves only
"""
self.set_settings({"/rtx/wireframe/enabled": True})
self.set_settings({"/rtx/wireframe/wireframeThickness": 5})
self.set_settings({"/rtx/wireframe/mode": 2})
# Global setting
self._create_geometry([bezierCnt], bezierPts, "constant", [20])
self.set_settings({"/rtx/hydra/curves/splits": 4})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "bezier4Splits.png")
# Update global setting
self.set_settings({"/rtx/hydra/curves/splits": 1})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "bezier1Splits.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Primvar with overrided
self._create_geometry([bezierCnt], bezierPts, "constant", [20])
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplitsOverride", Sdf.ValueTypeNames.Bool).Set(True)
UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "bezier2Splits.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Primvar without override (it should get num splits from global setting == 1)
self._create_geometry([bezierCnt], bezierPts, "constant", [20])
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "bezier1Splits.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Bspline
self._create_geometry([bsplineCnt], bsplinePts, "constant", [20], "bspline")
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplits", Sdf.ValueTypeNames.Int).Set(2)
UsdGeom.PrimvarsAPI(prim).CreatePrimvar("numSplitsOverride", Sdf.ValueTypeNames.Bool).Set(True)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "bspline2Splits.png")
async def test_timeSampled(self):
"""
Test hydra basis curves - verify time sample animation works.
"""
super().open_usd("hydra/curves_timeSampled_001.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
timeline = omni.timeline.get_timeline_interface()
# Regression test for OM-96462, where time-sampled xform was impairing update of time-sampled points
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "curves_timeSampled_frame0.png")
# Advance a few frames and capture another frame
for t in range(12):
timeline.forward_one_frame()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "curves_timeSampled_frame12.png")
class TestRtxHydraBasisCurvesInstancer(RtxHydraInstancerTest):
# TODO full cover scene instancer with tests
TEST_PATH = "hydra/basisCurves/instancer"
GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/curve"
def create_geometry(self, name=GEOM_PATH):
curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name)
curve.CreateCurveVertexCountsAttr([simpleCnt])
curve.CreatePointsAttr(simplePts)
curve.CreateWidthsAttr([0, 20, 20, 0])
return curve
async def test_sceneInstancer(self):
"""
Test hydra basis curves - scene instancer
"""
await self.si_all()
async def test_pointInstancer(self):
"""
Test hydra basis curves - point instancer
"""
await self.pi_all()
class TestRtxHydraBasisCurvesMaterials(RtxHydraMaterialsTest):
TEST_PATH = "hydra/basisCurves/material"
PRIM_PATH = "/World/curve"
def create_geometry(self, name=PRIM_PATH):
curve = UsdGeom.BasisCurves.Define(self.ctx.get_stage(), name)
curve.CreateCurveVertexCountsAttr([simpleCnt])
curve.CreatePointsAttr(simplePts)
curve.CreateWidthsAttr([10, 30, 30, 10])
return curve
# Unstable via OM-53604
async def test_UNSTABLE_materials_UNSTABLE(self):
"""
Test hydra basis curves - materials
"""
materials = ["Green", "Red"]
looksPath = "/World/Looks/"
# Set and change material
geomPrim = self.create_geometry().GetPrim()
for m in materials:
self.bind_material(geomPrim, looksPath + m)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m))
# Unbind material it should fallback to basic material
UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_base.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
| 24,695 | Python | 50.665272 | 197 | 0.626443 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_common.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.undo
import omni.kit.test
import omni.timeline
from .test_common import RtxTest, testSettings, postLoadTestSettings, set_transform_helper, wait_for_update
from pxr import Sdf, Gf, UsdGeom, UsdShade
class RtxHydraTest(RtxTest):
"""
Base class for hydra tests
"""
# override resolution
WINDOW_SIZE = (512, 512)
TEST_PATH = "hydra"
PRIM_PATH = ""
async def setUp(self):
await self.setUp_internal()
self.set_settings(testSettings)
omni.usd.get_context().new_stage()
self.add_dir_light()
await omni.kit.app.get_app().next_update_async() # Wait stage loading
self.set_settings(postLoadTestSettings)
def create_geometry(self, name=PRIM_PATH):
pass
def create_geometry_with_floor(self):
self.add_floor()
self.create_geometry()
set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 100, 0))
async def geometry_with_attribute(self, attrName, attrType, attrVal, shouldWait=False):
geom = self.create_geometry()
if shouldWait:
await wait_for_update()
attr = geom.GetPrim().CreateAttribute(attrName, attrType)
self.assertTrue(attr)
attr.Set(attrVal)
await wait_for_update()
return geom
async def set_attribute_timesampled(self, geom, attrName, attrType, attrVals, goldens):
attr = geom.GetPrim().CreateAttribute(attrName, attrType)
self.assertTrue(attr)
for i, v in enumerate(attrVals):
attr.Set(v, i)
self.assertTrue(len(attrVals) == len(goldens))
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
timeline.play()
timeline.set_auto_update(False)
for i, g in enumerate(goldens):
timeline.set_current_time(i)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, g)
timeline.set_auto_update(True)
timeline.stop()
async def attribute_test_case(self, createGeom, attrName, attrType, attrVals, goldens):
self.assertTrue(len(attrVals) > 1)
self.assertTrue(len(attrVals) == len(goldens))
geom = createGeom()
attr = geom.GetPrim().CreateAttribute(attrName, attrType)
self.assertTrue(attr)
# Test updating attribute
for i, g in enumerate(goldens):
attr.Set(attrVals[i])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, g)
# Test timesampled attribute
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
geom = createGeom()
await self.set_attribute_timesampled(geom, attrName, attrType, attrVals, goldens)
async def toggle_primvar(self, geomPath, primvarName, primvarType=Sdf.ValueTypeNames.Bool, primvarVal=True,
baseGoldenName="boxAndFloor.png", threshould=1e-5):
prim = self.ctx.get_stage().GetPrimAtPath(geomPath)
attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar(primvarName, primvarType)
self.assertTrue(attr)
await wait_for_update()
self.assertFalse(attr.Get() == primvarVal)
await self.capture_and_compare(self.TEST_PATH, baseGoldenName)
attr.Set(primvarVal)
await wait_for_update()
self.assertTrue(attr.Get() == primvarVal)
await self.capture_and_compare(self.TEST_PATH, primvarName + ".png", threshould)
async def visibility(self):
prim = self.create_geometry()
attr = prim.GetVisibilityAttr()
self.assertTrue(attr)
for i in range(2):
attr.Set(UsdGeom.Tokens.inherited)
await wait_for_update()
self.assertTrue(attr.Get() == UsdGeom.Tokens.inherited)
await self.capture_and_compare(self.TEST_PATH, "geom.png")
attr.Set(UsdGeom.Tokens.invisible)
await wait_for_update()
self.assertTrue(attr.Get() == UsdGeom.Tokens.invisible)
await self.capture_and_compare(self.TEST_PATH, "empty.png")
async def cull_style(self):
# Not yet supported by hydra
pass
async def double_sided(self):
pass
async def single_sided(self):
self.set_settings({"/rtx/debugView/target": "normal",
"/rtx/hydra/faceCulling/enabled": True})
geom = self.create_geometry()
attr = geom.GetPrim().CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool)
self.assertTrue(attr)
self.set_camera(cameraPos=(0, 0, 0), targetPos=(-500, -500, -500))
await wait_for_update()
self.assertFalse(attr.Get())
await self.capture_and_compare(self.TEST_PATH, "doubleSided.png")
attr.Set(True)
await wait_for_update()
self.assertTrue(attr.Get())
await self.capture_and_compare(self.TEST_PATH, "singleSided.png")
async def matte(self):
self.set_settings({"/rtx/matteObject/enabled": True,
"/rtx/post/backgroundZeroAlpha/enabled": True,
"/rtx/post/backgroundZeroAlpha/backgroundComposite": True,
"/rtx/post/backgroundZeroAlpha/backgroundDefaultColor": (0, 0, 0)})
await self.toggle_primvar("/World/Floor", "isMatteObject")
async def is_picked(self):
# This is not worked when kit is not focused. Skip tests while solution wouldn't be found
self.skipTest("Test is not worked correctly yet!")
#viewport = omni.kit.viewport_legacy.acquire_viewport_interface().get_viewport_window(None)
#isPicked = False
# for i in range(10):
# set_cursor_position((int(self.WINDOW_SIZE[0] / 2), int(self.WINDOW_SIZE[1] / 2)))
# await omni.kit.app.get_app().next_update_async()
# ret = viewport.get_hovered_world_position()
# isPicked |= ret[0]
#return isPicked
async def pickable(self):
geom = self.create_geometry()
self.assertTrue(await self.is_picked())
self.ctx.set_pickable(self.PRIM_PATH, False)
# set_pickable is not catched correctly by hydra yet. So we need to update any primvar to force update instance
attr = geom.GetPrim().CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool)
attr.Set(True)
await wait_for_update()
self.assertFalse(await self.is_picked())
async def transform_translate(self):
self.create_geometry()
set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 0, 150))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "translateZ.png")
async def transform_rotate(self):
self.create_geometry()
set_transform_helper(self.PRIM_PATH, euler=Gf.Vec3d(0, 45, 0))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "rotateY.png")
async def transform_scale(self):
self.create_geometry()
set_transform_helper(self.PRIM_PATH, scale=Gf.Vec3d(2, 1, 1))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "scaleX.png")
async def transform_combined(self, shouldWait=False):
self.create_geometry()
if shouldWait:
await wait_for_update()
set_transform_helper(self.PRIM_PATH, translate=Gf.Vec3d(0, 0, 150), euler=Gf.Vec3d(0, 45, 0),
scale=Gf.Vec3d(2, 1, 1))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tranlateZrotateYscaleX.png")
async def transform_all(self):
await self.transform_translate()
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
await self.transform_rotate()
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
await self.transform_scale()
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
await self.transform_combined(shouldWait=True)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
await wait_for_update()
await self.transform_combined(shouldWait=False)
class RtxHydraMaterialsTest(RtxHydraTest):
TEST_PATH = ""
PRIM_PATH = ""
async def setUp(self):
await self.setUp_internal()
self.set_settings(testSettings)
super().open_usd("hydra/UsdShade.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
def create_geometry(self, name):
pass
def bind_material(self, geom, material_path):
binding_api = UsdShade.MaterialBindingAPI(geom)
material_prim = self.ctx.get_stage().GetPrimAtPath(material_path)
material = UsdShade.Material(material_prim)
binding_api.Bind(material, UsdShade.Tokens.weakerThanDescendants)
class RtxHydraInstancerTest(RtxHydraTest):
# TODO full cover scene instancer with tests
TEST_PATH = ""
GEOM_PATH = ""
PRIM_PATH = "/World/instance"
PRIM1_PATH = "/World/instance1"
PRIM2_PATH = "/World/instance2"
def create_geometry(self, name):
pass
def create_scene_instancer(self):
prim = UsdGeom.Xform.Define(self.ctx.get_stage(), self.PRIM_PATH).GetPrim()
self.create_geometry(self.GEOM_PATH)
prim1 = UsdGeom.Xform.Define(self.ctx.get_stage(), self.PRIM1_PATH).GetPrim()
prim1.GetReferences().AddInternalReference(self.PRIM_PATH)
prim1.SetInstanceable(True)
omni.kit.commands.execute("CopyPrimCommand", path_from=self.PRIM1_PATH, path_to=self.PRIM2_PATH)
self.ctx.get_selection().clear_selected_prim_paths()
prim2 = self.ctx.get_stage().GetPrimAtPath(self.PRIM2_PATH)
set_transform_helper(self.PRIM2_PATH, translate=Gf.Vec3d(0, 200, 0))
return prim, prim2
def remove_scene_instancer(self):
# Teardown in reverse order of creation, to avoid temporarily leaving dangling references.
# Alternatively, we could implement this in Sdf with a change block to batch all the removals.
self.ctx.get_stage().RemovePrim(self.PRIM2_PATH)
self.ctx.get_stage().RemovePrim(self.PRIM1_PATH)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
self.ctx.get_stage().RemovePrim(self.GEOM_PATH)
def create_point_instancer(self):
instancer = UsdGeom.PointInstancer.Define(self.ctx.get_stage(), self.PRIM_PATH)
instancer.CreatePositionsAttr([(-150, 0, 0), (150, 0, 0)])
instancer.CreateProtoIndicesAttr([0, 0])
self.create_geometry(self.GEOM_PATH)
attr = instancer.CreatePrototypesRel()
attr.AddTarget(self.GEOM_PATH)
return instancer
def remove_point_instancer(self):
self.ctx.get_stage().RemovePrim(self.GEOM_PATH)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
async def si_create(self):
self.create_scene_instancer()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "sceneinstancer.png", 1e-4)
async def si_rotate(self):
self.create_scene_instancer()
set_transform_helper(self.GEOM_PATH, euler=Gf.Vec3d(0, 0, 45))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "si_rotate_mesh.png", 1e-4)
async def si_all(self):
await self.si_create()
self.remove_scene_instancer()
await self.si_rotate()
self.remove_scene_instancer()
async def pi_create(self):
self.create_point_instancer()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pointinstancer.png", 1e-4)
async def pi_protoIndices(self):
instancer = self.create_point_instancer()
sphere = UsdGeom.Sphere.Define(self.ctx.get_stage(), self.PRIM_PATH + "/sphere")
sphere.CreateRadiusAttr(50)
instancer.GetPrototypesRel().AddTarget(self.PRIM_PATH + "/sphere")
instancer.GetProtoIndicesAttr().Set([1, 0])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_2meshes.png", 1e-4)
# Regression test for OM-32503
instancer.GetProtoIndicesAttr().Set([1, 0, 1])
instancer.GetPositionsAttr().Set([(-150, 0, 0), (0, 0, 0), (150, 0, 0)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_3meshes.png", 1e-4)
async def pi_invisibleIds(self):
instancer = self.create_point_instancer()
attr = instancer.CreateInvisibleIdsAttr()
attr.Set([0])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_invisibleIds.png", 1e-4)
attr.Set([])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pointinstancer.png", 1e-4)
async def pi_orientations(self):
instancer = self.create_point_instancer()
attr = instancer.CreateOrientationsAttr()
attr.Set([Gf.Quath(0., 0., 0.5, 1), Gf.Quath(0., 0.5, 0., 1)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_orientations.png", 1e-4)
async def pi_scales(self):
instancer = self.create_point_instancer()
attr = instancer.CreateScalesAttr()
attr.Set([(1., 2., 1), (1., 1., 2)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_scales.png", 1e-4)
# OM-30814 - verify proper refresh when authoring xforms on prototype gprims and ancestors
async def pi_protoXform(self):
instancer = self.create_point_instancer()
await wait_for_update()
# TODO: Figure out why the bug does not repro via scripting, only via TransformGizmo;
# even scripting the entire operation within an Sdf.ChangeBlock does not trigger the
# bug, with the fixes reverted.
set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(2, 1, 2))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_protoXform.png", 1e-4)
set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(1, 1, 1))
await wait_for_update()
geomPath = Sdf.Path(self.GEOM_PATH)
xformPath = geomPath.GetParentPath().AppendChild('Xform')
UsdGeom.Xform.Define(self.ctx.get_stage(), xformPath)
newGeomPath = xformPath.AppendChild(geomPath.name)
omni.kit.commands.execute("MovePrimCommand", path_from=self.GEOM_PATH, path_to=newGeomPath)
instancer.GetPrototypesRel().ClearTargets(removeSpec=True)
instancer.GetPrototypesRel().AddTarget(xformPath)
await wait_for_update()
set_transform_helper(xformPath, scale=Gf.Vec3d(1, 2, 1))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_ancestralProtoXform.png", 1e-4)
omni.kit.commands.execute("MovePrimCommand", path_from=newGeomPath, path_to=self.GEOM_PATH)
instancer.GetPrototypesRel().ClearTargets(removeSpec=True)
instancer.GetPrototypesRel().AddTarget(geomPath)
self.ctx.get_stage().RemovePrim(xformPath)
# OM-81682 - verify the prototype transform does not include the transform above the prototype root
set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(1, 1, 1))
await wait_for_update()
parentXformPath = geomPath.GetParentPath().AppendChild('Parent')
UsdGeom.Xform.Define(self.ctx.get_stage(), parentXformPath)
newXformPath = parentXformPath.AppendChild('Xform')
UsdGeom.Xform.Define(self.ctx.get_stage(), newXformPath)
newGeomPath = newXformPath.AppendChild(geomPath.name)
omni.kit.commands.execute("MovePrimCommand", path_from=self.GEOM_PATH, path_to=newGeomPath)
set_transform_helper(newXformPath, scale=Gf.Vec3d(1, 2, 1))
set_transform_helper(parentXformPath, scale=Gf.Vec3d(2, 2, 2))
instancer.GetPrototypesRel().ClearTargets(removeSpec=True)
instancer.GetPrototypesRel().AddTarget(newXformPath)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pi_ancestralProtoXform.png")
omni.kit.commands.execute("MovePrimCommand", path_from=newGeomPath, path_to=self.GEOM_PATH)
self.ctx.get_stage().RemovePrim(parentXformPath)
set_transform_helper(self.GEOM_PATH, scale=Gf.Vec3d(2, 1, 2))
instancer.GetPrototypesRel().ClearTargets(removeSpec=True)
instancer.GetPrototypesRel().AddTarget(self.GEOM_PATH)
async def pi_all(self):
await self.pi_create()
self.remove_point_instancer()
await self.pi_protoIndices()
self.remove_point_instancer()
await self.pi_invisibleIds()
self.remove_point_instancer()
# Transforms
await self.pi_orientations()
self.remove_point_instancer()
await self.pi_scales()
self.remove_point_instancer()
self.create_point_instancer()
await self.transform_translate()
self.remove_point_instancer()
self.create_point_instancer()
await self.transform_rotate()
self.remove_point_instancer()
self.create_point_instancer()
await self.transform_scale()
self.remove_point_instancer()
await self.pi_protoXform()
self.remove_point_instancer()
| 17,803 | Python | 41.901205 | 119 | 0.652587 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_points.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.timeline
from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest
from .test_common import wait_for_update, postLoadTestSettings
from pxr import Sdf, UsdGeom, UsdShade
DEFAULT_POINTS = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]
class TestRtxHydraPoints(RtxHydraTest):
TEST_PATH = "hydra/points"
PRIM_PATH = "/World/pts"
async def display_color(self):
# Constant
geom = self.create_geometry()
geom.CreateDisplayColorPrimvar("constant").Set([(0, 1, 0)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "displayColorConstant.png")
return geom
async def widths(self):
# Default
geom = self.create_geometry()
geom.GetWidthsAttr().Clear()
self.set_settings({"/persistent/rtx/hydra/points/defaultWidth": 35})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "widthDefault.png")
self.set_settings({"/persistent/rtx/hydra/points/defaultWidth": 45})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "widthDefault2.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Constant
geom = self.create_geometry()
geom.SetWidthsInterpolation("constant")
geom.CreateWidthsAttr().Set([20])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "widthConstant.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Vertex
geom = self.create_geometry()
geom.CreateWidthsAttr().Set([20, 15, 10, 25, 30, 35, 40, 45])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "widthVertex.png")
async def points(self):
pts = [DEFAULT_POINTS,
[(-50, -50, -50), (150, -50, -50), (-50, -50, 50), (50, -50, 50), (-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]]
await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts, ["geom.png", "points.png"])
async def skipProcessing(self):
geom = self.create_geometry()
geom.GetPrim().CreateAttribute("omni:rtx:skip", Sdf.ValueTypeNames.Bool).Set(True)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "empty.png")
class TestRtxHydraPrimitiveDrawingPoints(TestRtxHydraPoints):
TEST_PATH = "hydra/points/primitivedrawing"
PRIM_PATH = "/World/pts"
def create_geometry(self, name=PRIM_PATH):
pts = UsdGeom.Points.Define(self.ctx.get_stage(), name)
pts.CreatePointsAttr(DEFAULT_POINTS)
pts.CreateWidthsAttr([10, 10, 10, 10, 5, 5, 15, 15])
UsdGeom.PrimvarsAPI(pts).CreatePrimvar("usePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True)
UsdGeom.PrimvarsAPI(pts).CreatePrimvar("screenSpacePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True)
return pts
async def test_visibility(self):
"""
Test hydra points - visibility
"""
await self.visibility()
async def test_transform(self):
"""
Test hydra points - tranform
"""
await self.transform_all()
async def test_displayColor(self):
"""
Test hydra points - change display color
"""
geom = await self.display_color()
# Vertex
geom.CreateDisplayColorPrimvar("vertex").Set([(0, 1, 0), (1, 1, 0), (0, 1, 1), (1, 0, 1), (1, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 0)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "displayColorVertex.png")
async def test_widths(self):
"""
Test hydra points - change widths
"""
await self.widths()
async def test_points(self):
"""
Test hydra points - update points
"""
await self.points()
async def test_skipProcessing(self):
"""
Test hydra points - skipProcessing attribute
"""
await self.skipProcessing()
class TestRtxHydraPrimitiveDrawingPointsInstancer(RtxHydraInstancerTest):
# TODO full cover scene instancer with tests
TEST_PATH = "hydra/points/primitivedrawing/instancer"
GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/pts"
def create_geometry(self, name=GEOM_PATH):
pts = UsdGeom.Points.Define(self.ctx.get_stage(), name)
pts.CreatePointsAttr(DEFAULT_POINTS)
pts.CreateWidthsAttr([10, 10, 10, 10, 5, 5, 15, 15])
UsdGeom.PrimvarsAPI(pts).CreatePrimvar("usePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True)
UsdGeom.PrimvarsAPI(pts).CreatePrimvar("screenSpacePrimitiveDrawing", Sdf.ValueTypeNames.Bool).Set(True)
return pts
async def test_sceneInstancer(self):
"""
Test hydra points scene instancer
"""
await self.si_all()
async def test_pointInstancer(self):
"""
Test hydra points point instancer
"""
await self.pi_all()
class UNSTABLE_TestRtxHydraProceduralPoints_UNSTABLE(TestRtxHydraPoints):
TEST_PATH = "hydra/points/procedural"
PRIM_PATH = "/World/pts"
def create_geometry(self, name=PRIM_PATH):
pts = UsdGeom.Points.Define(self.ctx.get_stage(), name)
pts.CreatePointsAttr(DEFAULT_POINTS)
pts.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35])
return pts
async def test_visibility(self):
"""
Test hydra points - visibility
"""
await self.visibility()
async def test_doNotCastShadow(self):
"""
Test hydra points - doNotCastShadow toggle
"""
self.create_geometry_with_floor()
await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows")
async def test_matteObject(self):
"""
Test hydra points - isMatteObject toggle
"""
self.create_geometry_with_floor()
await self.matte()
async def test_hideForCamera(self):
"""
Test hydra points - hideForCamera toggle
"""
self.create_geometry_with_floor()
await self.toggle_primvar(self.PRIM_PATH, "hideForCamera")
async def test_transform(self):
"""
Test hydra points - tranform
"""
await self.transform_all()
async def test_displayColor(self):
"""
Test hydra points - change display color
"""
await self.display_color()
async def test_widths(self):
"""
Test hydra points - change widths
"""
await self.widths()
async def test_points(self):
"""
Test hydra points - update points
"""
await self.points()
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# OM-45604, OM-43655
# Delayed points assignment
geom = UsdGeom.Points.Define(self.ctx.get_stage(), self.PRIM_PATH)
geom.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "empty.png", 1e-4)
attr = geom.CreatePointsAttr(DEFAULT_POINTS)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "geom.png", 1e-4)
# OM-43655 - remove point
attr.Set(DEFAULT_POINTS[:-1])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "pointsRemovedOne.png", 1e-4)
async def test_skip_processing(self):
"""
Test hydra points - skipProcessing attribute
"""
await self.skipProcessing()
async def test_texCoords(self):
self.set_settings({"/rtx/debugView/target": "texcoord1"})
self.create_geometry()
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
attr = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("uv1", Sdf.ValueTypeNames.Float2Array, UsdGeom.Tokens.vertex)
uvVertexSet = [(1, 0), (0.15, 0.5), (0.3, 0.5), (0.5, 0.5), (0.7, 0.5), (0.85, 0.5), (1, 0.5), (1, 1)]
attr.Set(uvVertexSet)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "texCoords.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
async def test_timeSampled(self):
"""
Test hydra points - verify time sample animation works.
"""
super().open_usd("hydra/points_timeSampled_001.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
timeline = omni.timeline.get_timeline_interface()
# Regression test for OM-96462, where time-sampled xform was impairing update of time-sampled points
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "points_timeSampled_frame0.png")
# Advance a few frames and capture another frame
for t in range(12):
timeline.forward_one_frame()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "points_timeSampled_frame12.png")
class UNSTABLE_TestRtxHydraProceduralPointsInstancer_UNSTABLE(RtxHydraInstancerTest):
# TODO full cover scene instancer with tests
TEST_PATH = "hydra/points/procedural/instancer"
GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/pts"
def create_geometry(self, name=GEOM_PATH):
pts = UsdGeom.Points.Define(self.ctx.get_stage(), name)
pts.CreatePointsAttr(DEFAULT_POINTS)
pts.CreateWidthsAttr([40, 30, 30, 20, 15, 15, 35, 35])
return pts
async def test_sceneInstancer(self):
"""
Test hydra points - scene instancer
"""
await self.si_all()
async def test_pointInstancer(self):
"""
Test hydra points - point instancer
"""
await self.pi_all()
class UNSTABLE_TestRtxHydraProceduralPointsMaterials_UNSTABLE(RtxHydraMaterialsTest):
TEST_PATH = "hydra/points/procedural/material"
PRIM_PATH = "/World/pts"
def create_geometry(self, name=PRIM_PATH):
pts = UsdGeom.Points.Define(self.ctx.get_stage(), name)
pts.CreatePointsAttr([(-50, 0, 0), (50, 0, 0)])
pts.CreateWidthsAttr([50, 25])
return pts
async def test_materials(self):
"""
Test hydra points - materials
"""
materials = ["Green", "Red"]
looksPath = "/World/Looks/"
# Set and change material
geomPrim = self.create_geometry().GetPrim()
for m in materials:
self.bind_material(geomPrim, looksPath + m)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m))
# Unbind material it should fallback to basic material
UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_base.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
| 11,487 | Python | 35.820513 | 142 | 0.630278 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_volume.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
from .test_hydra_common import RtxHydraTest
from .test_common import set_transform_helper, wait_for_update
from pxr import Gf, UsdVol
class TestRtxHydraVolume(RtxHydraTest):
TEST_PATH = "hydra/volume"
PRIM_PATH = "/World/volume"
def create_geometry(self, name=PRIM_PATH):
open_vdb_asset = UsdVol.OpenVDBAsset.Define(self.ctx.get_stage(), name + "/OpenVDBAsset")
open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("sphere.vdb"))
open_vdb_asset.GetFieldNameAttr().Set("density")
volume = UsdVol.Volume.Define(self.ctx.get_stage(), name)
volume.CreateFieldRelationship("density", open_vdb_asset.GetPath())
set_transform_helper(volume.GetPath(), translate=Gf.Vec3d(0, 150, 0), scale=Gf.Vec3d(20.0, 20.0, 20.0))
return volume
# simple test, create a volume with a OpenVDB asset
# Unstable via OM-54845
async def test_UNSTABLE_create_UNSTABLE(self):
self.add_floor()
self.create_geometry()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "create_sphere.png", threshold=1e-3)
# test changing the OpenVDBAsset file path
# Unstable via OM-54845
async def test_UNSTABLE_change_to_torus_UNSTABLE(self):
self.add_floor()
self.create_geometry()
open_vdb_asset = UsdVol.OpenVDBAsset(self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH + "/OpenVDBAsset"))
open_vdb_asset.GetFilePathAttr().Set(self.get_volumes_path("torus.vdb"))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "change_to_torus.png", threshold=1e-3)
| 2,088 | Python | 44.413043 | 114 | 0.70977 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_example.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.undo
import omni.kit.test
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
from pxr import UsdGeom
class TestRtxExample1(RtxTest):
"""
Example of rtx test which creates box and capture screenshot
Hints: for python debug insert line below and attach to kit process in VS Code
omni.kit.debug.python.breakpoint()
"""
# override resolution
WINDOW_SIZE = (512, 512)
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage.
self.add_dir_light()
await omni.kit.app.get_app().next_update_async() # Wait stage loading
self.set_settings(postLoadTestSettings)
def create_mesh(self):
box = UsdGeom.Mesh.Define(self.ctx.get_stage(), "/World/box")
box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50),
(-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)])
box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4])
box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5])
box.CreateSubdivisionSchemeAttr("none")
return box
# Unstable via OM-58681
async def test_UNSTABLE_rtx_example_create_mesh_UNSTABLE(self):
"""
Test example - create mesh
"""
self.create_mesh()
await wait_for_update()
await self.capture_and_compare("example", "mesh.png")
async def test_rtx_example_check_mesh(self):
"""
Test example - check mesh
"""
box = self.create_mesh()
points = box.GetPointsAttr().Get()
face_indices = box.GetFaceVertexIndicesAttr().Get()
unique_indices = set(face_indices)
self.assertTrue(len(points) == len(unique_indices))
class TestRtxExample2(RtxTest):
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
self.open_usd("bunny.obj.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
self.set_camera((6.969233739993722, 6.969233739993723, 6.969233739993719), (0, 0, 0))
async def test_UNSTABLE_rtx_example_open_usd_UNSTABLE(self):
"""
Test example - open usd file
"""
await wait_for_update()
await self.capture_and_compare("example", "usd.png", 1e-4)
| 3,058 | Python | 37.721519 | 130 | 0.642904 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_usdlux_schema_compat.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
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
from pxr import UsdGeom, UsdLux
class TestUsdLuxSchemaCompat(RtxTest):
TEST_PATH = "hydra/usdlux"
async def test_usdlux_inputs_prefix(self):
"""
Test that the compatibility workaround for UsdLux schema changes that requires an inputs: prefix on attributes works.
"""
test_file_path = "hydra/simpleSphereLightUnprefixed.usda"
super().open_usd(test_file_path)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "lightAttributes.png")
async def test_usdlux_light_with_both_attributes(self):
"""
Test that the delegate chooses inputs: attributes when both inputs and non-inputs are authored.
The usda for this test has these properties defined:
float inputs:intensity = 30000
float intensity = 90000000
"""
test_file_path = "hydra/simpleSphereLightBothAttributes.usda"
super().open_usd(test_file_path)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "lightAttributes.png") | 1,633 | Python | 44.388888 | 125 | 0.71831 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_mesh.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.undo
import omni.kit.test
import omni.timeline
import carb.settings
from .test_hydra_common import RtxHydraTest, RtxHydraMaterialsTest, RtxHydraInstancerTest
from .test_common import postLoadTestSettings, set_transform_helper, wait_for_update
from pxr import Vt, Gf, Sdf, UsdGeom, UsdShade
cubePts = [(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50),
(-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)]
cubeFaceVCount = [4, 4, 4, 4, 4, 4]
cubeIndices = [0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5]
class TestRtxHydraMesh(RtxHydraTest):
TEST_PATH = "hydra/mesh"
PRIM_PATH = "/World/box"
async def setUp(self):
await super().setUp()
timeline = omni.timeline.get_timeline_interface()
timeline.set_target_framerate(timeline.get_time_codes_per_seconds())
def create_geometry(self, name=PRIM_PATH):
box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name)
box.CreatePointsAttr(cubePts)
box.CreateFaceVertexCountsAttr(cubeFaceVCount)
box.CreateFaceVertexIndicesAttr(cubeIndices)
box.CreateSubdivisionSchemeAttr("none")
return box
#
# Common tests for mesh
#
async def test_visibility(self):
"""
Test hydra mesh - visibility
"""
await self.visibility()
# OM-34158
# Verify proper refresh when points are moved while the mesh is invisible.
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
mesh = UsdGeom.Mesh(prim)
points = mesh.GetPointsAttr().Get()
for idx, p in enumerate(points):
points[idx] = p + Gf.Vec3f(100, 0, 0)
mesh.GetPointsAttr().Set(points)
await wait_for_update()
mesh.GetVisibilityAttr().Set(UsdGeom.Tokens.inherited)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "boxPtsMovedWhileInvisible.png")
async def test_doNotCastShadow(self):
"""
Test hydra mesh - doNotCastShadow toggle
"""
self.create_geometry_with_floor()
# OM-58993: Properly cast shadows.
await self.toggle_primvar(self.PRIM_PATH, "doNotCastShadows")
# TODO setup scene which shows the difference
# async def test_shadowTerminatorFix(self):
# """
# Test hydra mesh - enableShadowTerminatorFix toggle
# """
# self.create_geometry_with_floor()
# await self.toggle_primvar(self.PRIM_PATH, "enableShadowTerminatorFix")
async def test_matteObject(self):
"""
Test hydra mesh - isMatteObject toggle
"""
self.create_geometry_with_floor()
await self.matte()
async def test_hideForCamera(self):
"""
Test hydra mesh - hideForCamera toggle
"""
self.create_geometry_with_floor()
await self.toggle_primvar(self.PRIM_PATH, "hideForCamera")
async def test_wireframe(self):
"""
Test hydra mesh - wireframe toggle
"""
self.create_geometry()
self.set_settings({"/rtx/wireframe/wireframeThickness": 10})
await self.toggle_primvar(self.PRIM_PATH, "wireframe", baseGoldenName="geom.png", threshould=1e-7)
async def test_singleSided(self):
"""
Test hydra mesh - singleSided toggle
"""
await self.single_sided()
async def test_pickable(self):
"""
Test hydra mesh - pickable flag toggle
"""
await self.pickable()
# OM-3262 Verify proper refresh when authoring purpose
async def test_purpose(self):
"""
Test hydra mesh - purpose toggle
"""
self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False})
self.create_geometry()
geom = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
UsdGeom.Imageable(geom).CreatePurposeAttr().Set(UsdGeom.Tokens.guide)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "purpose.png")
# OM-62070
# Verify mesh visibility updates when changing global setting
self.set_settings({'/persistent/app/hydra/displayPurpose/guide': True})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "guideVisEnable.png")
self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "guideVisDisable.png")
# Verify inherited purpose authoring
self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False})
super().open_usd("hydra/inheritedPurpose.usda")
scope = self.ctx.get_stage().GetPrimAtPath('/World/Scope')
UsdGeom.Imageable(scope).CreatePurposeAttr().Set(UsdGeom.Tokens.guide)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "inheritedGuidePurpose.png")
UsdGeom.Imageable(scope).GetPurposeAttr().Clear()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "inheritedDefaultPurpose.png", 5e-5)
# OM-32623
# Verify proper population of new repr when toggling saved guide purpose to default.
self.set_settings({'/persistent/app/hydra/displayPurpose/guide': False})
super().open_usd("hydra/guideRepr.usda")
geom = self.ctx.get_stage().GetPrimAtPath('/World/Cube')
UsdGeom.Imageable(geom).GetPurposeAttr().Clear()
await wait_for_update()
# Allow for a bit of noise between local run and TC
await self.capture_and_compare(self.TEST_PATH, "guideRepr.png", 1e-4)
async def test_transform(self):
"""
Test hydra mesh - tranform
"""
await self.transform_all()
# OM-26055
# Verify that fallback xform values are properly initialized.
super().open_usd("hydra/OM-26055_scene.usda")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "OM-26055_scene.png")
# OM-34447
# Verify that xforms properly resync when initially present with no value.
super().open_usd("hydra/empty_xform_mtx.usda")
stage = self.ctx.get_stage()
set_transform_helper("/World/Mesh", translate=Gf.Vec3d(200, 0, 0))
await wait_for_update()
# Looser threshold, as the test is somewhat noisy on Linux TC
await self.capture_and_compare(self.TEST_PATH, "resync-empty_xform_mtx.png", 1e-4)
# Verify that ancestral xforms properly affect invisible geometry.
super().open_usd("hydra/simpleCubeAncestralXforms.usda")
stage = self.ctx.get_stage()
await wait_for_update()
intermediateXform = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Xform/Xform_01"))
intermediateXform.MakeVisible(False)
await wait_for_update()
ancestralXform = UsdGeom.XformCommonAPI(stage.GetPrimAtPath("/World/Xform"))
ancestralXform.SetTranslate((100,0,0))
await wait_for_update()
intermediateXform.MakeVisible(True)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "postVisAncestralXform.png")
async def test_backfaceCulling(self):
"""
Test hydra mesh - verify toggling of backface culling is correctly propagated
"""
# Scene loads without backface culling: a green place partially covers a gray sphere
super().open_usd("hydra/backFaceCulling.usda")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_off.png")
self.set_settings({"/rtx/hydra/faceCulling/enabled": True})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_on.png")
stage = self.ctx.get_stage()
prim = stage.GetPrimAtPath("/World/Plane")
attr = prim.GetAttribute("singleSided")
attr.Set(False)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "backfaceCulling_doublesided.png")
async def test_displayColor(self):
"""
Test hydra mesh - change display color
"""
await self.geometry_with_attribute("primvars:displayColor", Sdf.ValueTypeNames.Color3f, [(0, 1, 0)])
await self.capture_and_compare(self.TEST_PATH, "displayColor.png")
# OM-58993 - Changing only display color should work
prim = self.ctx.get_stage().GetPrimAtPath(self.PRIM_PATH)
mesh = UsdGeom.Mesh(prim)
displayColorAttr = mesh.GetDisplayColorAttr()
displayColorAttr.Set([(0, 0, 1)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "displayColorChange.png")
stage = self.ctx.get_stage()
prim = stage.GetPrimAtPath(self.PRIM_PATH)
mesh = UsdGeom.Mesh(prim)
attr = prim.GetAttribute("primvars:displayColor")
primvar = UsdGeom.Primvar(attr)
primvar.SetInterpolation(UsdGeom.Tokens.uniform)
colors = [(1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 1, 1), (0, 0, 1), (1, 0, 1)]
attr.Set(colors)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "displayColorUniform.png")
primvar.SetInterpolation(UsdGeom.Tokens.vertex)
colors = [(1, 0, 0), (1, 0, 1), (1, 1, 1), (1, 1, 0), (0, 0, 0), (0, 0, 1), (0, 1, 1), (0, 1, 0)]
attr.Set(colors)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "displayColorVertex.png")
async def test_primvarBinding(self):
"""
Test hydra mesh - varify effects of material edits to geometry primvar binding
"""
# OM-83102 - the file should open with a material lookup pointing to no primvar. It should render
# a default magenta color
super().open_usd("hydra/primvars_edit.usda")
await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_magenta.png")
# changing the default lookup color to yellow
prim = self.ctx.get_stage().GetPrimAtPath("/World/Looks/mtl_emissive/data_lookup_color")
attr = prim.GetAttribute("inputs:default_value")
attr.Set((1, 1, 0))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_yellow.png")
# specify an existing primvar to lookup
attr = prim.GetAttribute("inputs:name")
attr.Set("blue")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "primvarFound_blue.png")
# change to a different existing primvar to lookup
attr = prim.GetAttribute("inputs:name")
attr.Set("green")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "primvarFound_green.png")
# change the default value to red now should have no effect
attr = prim.GetAttribute("inputs:default_value")
attr.Set((1, 0, 0))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "primvarFound_still_green.png")
# change to a different not-existing primvar to lookup, now it should render the default color set in previous step
attr = prim.GetAttribute("inputs:name")
attr.Set("foo_bar")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "primvarNotFound_red.png")
#
# Mesh specific tests
#
async def test_topology(self):
"""
Test hydra mesh - topology changes - transform cube to wedge
"""
box = self.create_geometry()
await wait_for_update() # Wait 5 frames to be sure that we update topology
box.CreateFaceVertexCountsAttr([4, 3, 4, 3, 4])
box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 1, 0, 2, 7, 4, 2, 3, 7, 1, 4, 7, 3])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "topology.png")
async def subdiv_default(self, shouldWait=False):
box = self.create_geometry()
if shouldWait:
await wait_for_update()
subdivAttr = box.GetSubdivisionSchemeAttr()
subdivAttr.Set("catmullClark")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivDefault.png")
async def test_subdiv(self):
"""
Test hydra mesh - subdiv
"""
await self.subdiv_default(shouldWait=True)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
await wait_for_update()
await self.subdiv_default(shouldWait=False)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Set refinement level with setting
self.set_settings({"/rtx/hydra/subdivision/refinementLevel": 2})
geom = self.create_geometry()
subdivAttr = geom.GetSubdivisionSchemeAttr()
subdivAttr.Set("catmullClark")
geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivRefinementLevel.png", 1e-4)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Set refinement level override from usd
self.set_settings({"/rtx/hydra/subdivision/refinementLevel": 0})
geom = self.create_geometry()
subdivAttr = geom.GetSubdivisionSchemeAttr()
subdivAttr.Set("catmullClark")
geom.GetPrim().CreateAttribute("refinementEnableOverride", Sdf.ValueTypeNames.Bool).Set(True)
geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(2)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivRefinementLevel.png", 1e-4)
# OM-21340 Verify that load of refined geometry does not crash.
super().open_usd("hydra/cone_sbdv.usda")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "cone_sbdv.png", 1e-4)
async def test_subdiv_toggle(self):
"""
Test hydra mesh - subdiv toggle on/off, this test verifies that change between regular polygons and subdiv
geometry doesn't leave the mesh in a corrupt internal state.
"""
# OM-88053: toggle on/off sudivision surfaces on a mesh *with authored normals*.
# Begin with checking the input geometry: a primitve cube with authored normals.
super().open_usd("hydra/cube_subdiv.usda")
geom = self.ctx.get_stage().GetPrimAtPath("/World/Cube")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivToggle_off.png", 1e-4)
# Enabling Catmull-Clark subdivision without changing any other option would simply
# discard the authored normals, but still render the polygonal cage.
subdivAttr = geom.GetAttribute("subdivisionScheme")
subdivAttr.Set("catmullClark")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_smoothNormals.png", 1e-4)
# This should produce a subdivided smooth mesh.
geom.CreateAttribute("refinementEnableOverride", Sdf.ValueTypeNames.Bool).Set(True)
geom.CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(2)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_subdivided.png", 1e-4)
# Deform by moving a point.
mesh = UsdGeom.Mesh(geom)
points = mesh.GetPointsAttr().Get()
points[7] = points[7] + Gf.Vec3f(0, 40, 0)
mesh.GetPointsAttr().Set(points)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_deformed.png", 1e-4)
# Also test bilinear subdivision
subdivAttr.Set("bilinear")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivToggle_on_bilinear.png", 1e-4)
# Finally this should go back to the original mesh with authored normals.
subdivAttr.Set("none")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "subdivToggle_off_again.png", 1e-4)
async def test_handedness(self):
"""
Test hydra mesh - toggle orintation between right and left handed, in a combination
of triangulated mesh and quadrangulated mesh, with and without subdivision surfaces.
"""
# OM-113941: toggle handedness. A custom material front-facing green and back-facing red.
super().open_usd("hydra/handedness_001.usda")
await wait_for_update()
self.set_settings(postLoadTestSettings)
# This triangulated mesh is left-handed and has subdivision surface on. It also has broken normals
# (a vector of zero entries) that would have resulted in a crash when toggling subdivision surfaces off.
geomT = self.ctx.get_stage().GetPrimAtPath("/World/glasst_mod/SH000254198100001_Tube/SH000254198100001_Tube")
# This is a mesh made of quads and right-handed
geomQ = self.ctx.get_stage().GetPrimAtPath("/World/glassq/SH000254198100001_Tube/SH000254198100001_Tube")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "handedness_001_subdiv_green.png", 1e-4)
# Toggle handedness
geomT.GetAttribute("orientation").Set("leftHanded") # This edit would not render red in OM-113941
geomQ.GetAttribute("orientation").Set("rightHanded")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "handedness_001_subdiv_red.png", 1e-4)
# Toggle subdivision surface
geomT.GetAttribute("subdivisionScheme").Set("none") # This edit would crash OM-113941
geomQ.GetAttribute("subdivisionScheme").Set("catmullClark")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "handedness_001_mesh_red.png", 1e-4)
# Toggle handedness again
geomT.GetAttribute("orientation").Set("rightHanded")
geomQ.GetAttribute("orientation").Set("leftHanded")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "handedness_001_mesh_green.png", 1e-4)
async def test_points(self):
"""
Test hydra mesh - update points
"""
pts = [cubePts, cubePts.copy()]
pts[1][1] = (150, -50, -50)
await self.attribute_test_case(self.create_geometry, "points", Sdf.ValueTypeNames.Point3f, pts,
["geom.png", "points.png"])
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# OM-76321: this set of tests [interleavedPointsEdit_*] verifies intermittent primvar edits during
# regular points edit. Special care is due because of the minimal updates we do to mesh VBs
# Interleaved points edit - initial state, this should render a blue cube.
geom = self.create_geometry()
mesh = UsdGeom.Mesh(geom)
displayColorAttr = mesh.GetDisplayColorAttr()
displayColorAttr.Set([(0, 0, 1)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_0.png", 1e-4)
# Interleaved points edit - first edit, the cube is slightly deformed and still blue.
# This first edit goes through full mesh update to create mutable buffers (not deduplicated).
pts[1][1] = (60, -50, -50)
geom.GetPointsAttr().Set(pts[1])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_1.png", 1e-4)
# Interleaved points edit - second edit, the cube is deformed again and is now set to green
# The second edit goes through meshUpdateVertices and creates a second VB.
pts[1][1] = (70, -50, -50)
geom.GetPointsAttr().Set(pts[1])
displayColorAttr.Set([(0, 1, 0)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_2.png", 1e-4)
# Interleaved points edit - third edit, the cube is more deformed and should still be green
# The last edit verifies that the previous edit to primvars need to be propagated to The
# VB ping-pong swap. If this fails the cube will be blue (as in previous frame) instead of green.
pts[1][1] = (80, -50, -50)
geom.GetPointsAttr().Set(pts[1])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "interleavedPointsEdit_3.png", 1e-4)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
async def test_normals(self):
"""
Test hydra mesh - update normals
"""
self.set_settings({"/rtx/debugView/target": "normal"})
# Authored face varying interpolation
normals = [[(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1),
(1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1),
(-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)],
[(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1),
(0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0), (0.5, 0.5, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1),
(-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)]]
def createGeom():
geom = self.create_geometry()
geom.CreateNormalsAttr()
geom.SetNormalsInterpolation("faceVarying")
return geom
await self.attribute_test_case(createGeom, "normals", Sdf.ValueTypeNames.Point3f, normals,
["normals.png", "normalsAuthoredFaceVarying.png"])
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Authored vertex interpolation
geom = self.create_geometry()
geom.GetNormalsAttr().Set([(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
geom.SetNormalsInterpolation("vertex")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "normalsAuthoredVertex.png", 1e-4)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Authored uniform interpolation
geom = self.create_geometry()
geom.GetNormalsAttr().Set([(0, -1, 0), (0, 0, -1), (1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 1, 0)])
geom.SetNormalsInterpolation("uniform")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "normals.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Authored constant interpolation
geom = self.create_geometry()
geom.GetNormalsAttr().Set([(0, 1, 0)])
geom.SetNormalsInterpolation("constant")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "normalsAuthoredConstant.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Generated smooth
geom = self.create_geometry()
geom.GetSubdivisionSchemeAttr().Set("catmullClark")
geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "normalsGeneratedSmooth.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Generated flat
self.create_geometry()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "normals.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# TBN Frame mode - generate normals on gpu
self.set_settings({"/rtx/hydra/TBNFrameMode": 2})
geom = self.create_geometry()
geom.GetSubdivisionSchemeAttr().Set("catmullClark")
geom.GetPrim().CreateAttribute("refinementLevel", Sdf.ValueTypeNames.Int).Set(0)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "normalsGeneratedSmooth-gpu.png", 5e-5)
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# OM-94303: Unstable due to golden image mismatch
async def test_UNSTABLE_gpu_normals(self):
"""
Test hydra mesh - gpu normals
"""
super().open_usd("hydra/normals_gen_001.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
self.set_settings({"/rtx/hydra/TBNFrameMode": 2})
self.set_settings({"/rtx/debugView/target": "materialGeometryNormal"})
await self.capture_and_compare(self.TEST_PATH, "gpu_normals_creation.png")
# Generated on GPU with reference normals
stage = self.ctx.get_stage()
prim = stage.GetPrimAtPath("/World/pSphere2")
mesh = UsdGeom.Mesh(prim)
points = mesh.GetPointsAttr().Get()
# By moving a point we force the generation of normals. Regression test for OM-90364 / MR !24845
points[16] = Gf.Vec3f(0, 11, 0)
mesh.GetPointsAttr().Set(points)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "gpu_normals_editing.png")
async def test_texCoords(self):
"""
Test hydra mesh - update tex coords
"""
self.set_settings({"/rtx/debugView/target": "texcoord0"})
# faceVarying
geom = self.create_geometry()
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(
[(1, 0), (0, 0), (0, 1), (1, 1)])
geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set(
[0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "texCoordsFaceVarying.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# vertex or varying (they are the same for a mesh geometry)
geom = self.create_geometry()
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set(
[(0, 0), (0.1, 0), (0.2, 0), (0.3, 0), (0.4, 0), (0.5, 0), (0.6, 0), (0.7, 0)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "texCoordsVertex.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# uniform
geom = self.create_geometry()
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.uniform).Set(
[(0, 0), (0, 0.1), (0, 0.2), (0, 0.3), (0, 0.4), (0, 0.5)])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "texCoordsUniform.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
async def test_tangents(self):
"""
Test hydra mesh - update tangents
"""
self.set_settings({"/rtx/debugView/target": "tangentu"})
# default - gpu
geom = self.create_geometry()
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(
[(1, 0), (0, 0), (0, 1), (1, 1)])
geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set(
[0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsU.png")
self.set_settings({"/rtx/debugView/target": "tangentv"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsV.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# cpu - uniform
geom = self.create_geometry()
geom.GetNormalsAttr().Set([(0, -1, 0), (0, 0, -1), (1, 0, 0), (0, 0, 1), (-1, 0, 0), (0, 1, 0)])
geom.SetNormalsInterpolation("uniform")
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(
[(1, 0), (0, 0), (0, 1), (1, 1)])
geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set(
[0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1])
self.set_settings({"/rtx/debugView/target": "tangentu"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsU.png")
self.set_settings({"/rtx/debugView/target": "tangentv"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsV.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# cpu - vertex
geom = self.create_geometry()
geom.GetNormalsAttr().Set([(-0.57735, -0.57735, -0.57735), (0.57735, -0.57735, -0.57735), (-0.57735, -0.57735, 0.57735), (0.57735, -0.57735, 0.57735),
(-0.57735, 0.57735, -0.57735), (0.57735, 0.57735, -0.57735), (0.57735, 0.57735, 0.57735), (-0.57735, 0.57735, 0.57735)])
geom.SetNormalsInterpolation("vertex")
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(
[(1, 0), (0, 0), (0, 1), (1, 1)])
geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set(
[0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1])
self.set_settings({"/rtx/debugView/target": "tangentu"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsVertexU.png")
self.set_settings({"/rtx/debugView/target": "tangentv"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsVertexV.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# cpu - facevarying
geom = self.create_geometry()
geom.GetNormalsAttr().Set([(0, -1, 0), (0, -1, 0), (0, -1, 0), (0, -1, 0), (0, 0, -1), (0, 0, -1), (0, 0, -1), (0, 0, -1),
(1, 0, 0), (1, 0, 0), (1, 0, 0), (1, 0, 0), (0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1),
(-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
geom.SetNormalsInterpolation("faceVarying")
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
UsdGeom.PrimvarsAPI(geom.GetPrim()).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(
[(1, 0), (0, 0), (0, 1), (1, 1)])
geom.GetPrim().CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False).Set(
[0, 1, 2, 3, 0, 3, 2, 1, 0, 1, 2, 3, 0, 1, 2, 3, 0, 3, 2, 1, 0, 3, 2, 1])
self.set_settings({"/rtx/debugView/target": "tangentu"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsFacevaryingU.png")
self.set_settings({"/rtx/debugView/target": "tangentv"})
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tangentsFacevaryingV.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
async def test_skeleton(self):
"""
Test hydra mesh - skeleton
"""
super().open_usd("hydra/skelcylinder.usda")
# self.set_settings(postLoadTestSettings)
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
# create
timeline = omni.timeline.get_timeline_interface()
timeline.play()
timeline.set_auto_update(False)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "skeleton0.png")
timeline.set_current_time(1)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "skeleton1.png")
timeline.set_auto_update(True)
timeline.stop()
# TODO remove, update
# create many instances
# SkinningMethod: eDualQuaternion, eClassicLinear, eWeightedBlend
async def test_mesh_with_api_schemas(self):
"""
Verify proper population and refresh when apiSchemas are present
"""
# OM-24223: Verify proper mesh population when duplicating with apiSchemas present
stage = self.ctx.get_stage()
cube = UsdGeom.Cube.Define(stage, "/Cube")
cube.GetSizeAttr().Set(50.0)
# Doesn't matter which API schema is applied, just use one from core, to avoid depending on physics.
# https://github.com/PixarAnimationStudios/USD/commit/6f0ce585bf5d06ca929584b515cd3bdf05d78eb3
# https://github.com/PixarAnimationStudios/USD/commit/1222ea7cd2478e576f4fc32936f781d2a7f61cd5
# https://github.com/PixarAnimationStudios/USD/commit/61fcc34d8555bb269fae49af90eab5154989392c
if hasattr(UsdGeom, 'VisibilityAPI'):
UsdGeom.VisibilityAPI.Apply(cube.GetPrim())
else:
from pxr import UsdRender
UsdRender.SettingsAPI.Apply(cube.GetPrim())
await wait_for_update()
omni.kit.commands.execute("CopyPrim", path_from="/Cube", path_to="/DupeCube")
self.ctx.get_selection().clear_selected_prim_paths()
set_transform_helper("/DupeCube", translate=Gf.Vec3d(200, 0, 0))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "dupeWithApiSchema.png")
self.ctx.get_stage().RemovePrim("/Cube")
self.ctx.get_stage().RemovePrim("/DupeCube")
await wait_for_update()
# OM-29819: Verify proper normals after applying an API schema
super().open_usd("hydra/torus_mesh.usda")
await wait_for_update()
stage = self.ctx.get_stage()
# Doesn't matter which API schema is applied, just use one from core, to avoid depending on physics.
# https://github.com/PixarAnimationStudios/USD/commit/6f0ce585bf5d06ca929584b515cd3bdf05d78eb3
# https://github.com/PixarAnimationStudios/USD/commit/1222ea7cd2478e576f4fc32936f781d2a7f61cd5
# https://github.com/PixarAnimationStudios/USD/commit/61fcc34d8555bb269fae49af90eab5154989392c
if hasattr(UsdGeom, 'VisibilityAPI'):
UsdGeom.VisibilityAPI.Apply(stage.GetPrimAtPath("/World/Torus"))
else:
from pxr import UsdRender
UsdRender.SettingsAPI.Apply(stage.GetPrimAtPath("/World/Torus"))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "normalsWithApiSchema.png", 3e-4)
async def test_UNSTABLE_tetMesh_UNSTABLE(self):
"""
Test hydra tetmesh
"""
# Eventually this should live in the physics repo, when omni hydra supports plugin adapters.
super().open_usd("hydra/tetmesh_teddy.usda")
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "tetmesh_teddy.png", 3e-4)
async def test_mesh_dedup(self):
"""
Verify hash collisions in mesh dedup do not crash
"""
# OM-64181: Verify hash collisions in mesh dedup do not crash
timeline = omni.timeline.get_timeline_interface()
timeline.set_current_time(0)
super().open_usd("hydra/AlternatingCubePlane.usda")
await wait_for_update()
N = 50
while N > 0:
N = N - 1
timeline.forward_one_frame()
await wait_for_update()
timeline.rewind_one_frame()
await wait_for_update()
class TestRtxHydraMeshMaterials(RtxHydraMaterialsTest):
TEST_PATH = "hydra/mesh/material"
PRIM_PATH = "/World/box"
def create_geometry(self, name=PRIM_PATH):
box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name)
box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50),
(-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)])
box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4])
box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5])
box.CreateSubdivisionSchemeAttr("none")
return box
async def test_materials(self):
"""
Test hydra mesh - materials
"""
materials = ["Green", "Red"]
looksPath = "/World/Looks/"
# Set and change material
geomPrim = self.create_geometry().GetPrim()
for m in materials:
self.bind_material(geomPrim, looksPath + m)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_{}.png".format(m))
# Unbind material it should fallback to basic material
UsdShade.MaterialBindingAPI(geomPrim).UnbindAllBindings()
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_base.png")
self.ctx.get_stage().RemovePrim(self.PRIM_PATH)
# Subsets
subsetPath = self.PRIM_PATH + "/subset"
geomPrim = self.create_geometry().GetPrim()
subset = UsdGeom.Subset.Define(self.ctx.get_stage(), subsetPath)
# https://github.com/PixarAnimationStudios/USD/commit/c1cdbbaa8a2dd8ecbb9722de517ef44c1a680352
# Family name required for subset material bindingas as of USD 21.11+;
# has been available on subsets from the firsrt public release of USD.
subset.CreateFamilyNameAttr().Set(UsdShade.Tokens.materialBind)
attr = subset.CreateIndicesAttr()
attr.Set([5])
self.bind_material(geomPrim, looksPath + materials[0])
self.bind_material(subset.GetPrim(), looksPath + materials[1])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_subsets.png")
# Update subset
attr.Set([3])
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_subsets2.png")
# Remove subset
self.ctx.get_stage().RemovePrim(subsetPath)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "mat_Green.png")
class TestRtxHydraMeshInstancer(RtxHydraInstancerTest):
# TODO full cover scene instancer with tests
TEST_PATH = "hydra/mesh/instancer"
GEOM_PATH = RtxHydraInstancerTest.PRIM_PATH + "/box"
def create_geometry(self, name=GEOM_PATH):
box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name)
box.CreatePointsAttr([(-50, -50, -50), (50, -50, -50), (-50, -50, 50), (50, -50, 50),
(-50, 50, -50), (50, 50, -50), (50, 50, 50), (-50, 50, 50)])
box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4])
box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5])
box.CreateSubdivisionSchemeAttr("none")
return box
async def test_sceneInstancer(self):
"""
Test hydra mesh scene instancer
"""
await self.si_all()
sgInstSettingsKey = "/persistent/omnihydra/useSceneGraphInstancing"
useSceneGraphInstancing = carb.settings.get_settings().get_as_bool(sgInstSettingsKey)
try:
async def nest_ptinst_in_sginst_test(self, enableOmniHydraScenegraphInstancing):
carb.settings.get_settings().set_bool(sgInstSettingsKey, enableOmniHydraScenegraphInstancing)
# OM-34669
# Verify that turning on instanceable on a hierarchy that contains
# a point instancer does not corrupt parent xforms.
super().open_usd("hydra/ptinst_inside_sginst.usda")
await wait_for_update()
stage = self.ctx.get_stage()
instance = stage.GetPrimAtPath('/World/Instance')
instance.SetInstanceable(True)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "ptinst_inside_sginst.png")
# Verify that authoring xforms on instances over internal references refreshes properly.
set_transform_helper(instance.GetPath(), translate=Gf.Vec3d(200,0,0), euler=Gf.Vec3f(0, 0, -120))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "ptinst_inside_sginst_rotated.png")
# Verify that authoring xforms on instances over external references refreshes properly.
super().open_usd("hydra/ref_ptinst_inside_sginst.usda")
await wait_for_update()
stage = self.ctx.get_stage()
instance = stage.GetPrimAtPath('/World/Instance')
set_transform_helper(instance.GetPath(), euler=Gf.Vec3f(0, 0, -30))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "ref_ptinst_inside_sginst_rotated.png")
await nest_ptinst_in_sginst_test(self, False)
await nest_ptinst_in_sginst_test(self, True)
finally:
carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing)
# OM-35643
# Verify xforms above scenegraph instance roots are honored by omni hydra scenegraph instancing.
try:
carb.settings.get_settings().set_bool(sgInstSettingsKey, True)
super().open_usd("hydra/CubeWorld.usda")
await wait_for_update()
stage = self.ctx.get_stage()
cubeInstance = stage.GetPrimAtPath("/CubeWorld/CubeInstance")
cubeInstance.SetInstanceable(True)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "sginst_parent_xform.png", 1e-4)
cubeInstance.SetInstanceable(False)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "sginst_parent_xform.png", 1e-4)
finally:
carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing)
# OM-36724
# Verify xforms in the presence of nested scenegraph instancing with omni hydra scenegraph instancing enabled
for testFile in ["hydra/nestedScenegraphInstances.usda", "hydra/nestedScenegraphInstancesOff.usda"]:
try:
carb.settings.get_settings().set_bool(sgInstSettingsKey, True)
super().open_usd(testFile)
await wait_for_update()
stage = self.ctx.get_stage()
cubeInstance = stage.GetPrimAtPath("/World/threeCubes")
cubeInstance.SetInstanceable(True)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "nested_sginst_toggle.png", 1e-4)
cubeInstance.SetInstanceable(False)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "nested_sginst_toggle.png", 1e-4)
set_transform_helper(cubeInstance.GetPath(), translate=Gf.Vec3d(200,0,0))
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "nested_sginst_xform_refresh.png", 1e-4)
finally:
carb.settings.get_settings().set_bool(sgInstSettingsKey, useSceneGraphInstancing)
async def test_pointInstancer(self):
"""
Test hydra mesh point instancer
"""
await self.pi_all()
# OM-30658 Verify proper population when prototype is not nested under point instancer
super().open_usd("hydra/ptinst_unnested_proto.usda")
await wait_for_update()
# Raise threshold a bit to account for noise between local runs and TC
await self.capture_and_compare(self.TEST_PATH, "ptinst_unnested_proto.png", 3e-4)
# OM-32571 Verify proper population after creating an empty instancer.
super().open_usd("hydra/cube_ptinst_unpopulated.usda")
await wait_for_update()
stage = self.ctx.get_stage()
p = stage.GetPrimAtPath('/World/output')
pos = p.GetAttribute('positions1').Get()
ori = p.GetAttribute('orientations1').Get()
scl = p.GetAttribute('scales1').Get()
pi = p.GetAttribute('protoIndices1').Get()
with Sdf.ChangeBlock():
p.GetAttribute('positions').Set(pos)
p.GetAttribute('orientations').Set(ori)
p.GetAttribute('scales').Set(scl)
p.GetAttribute('protoIndices').Set(pi)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "cube_ptinst_unpopulated.png")
# OM-35779 Verify proper refresh of nested point instancers
super().open_usd("hydra/nested_ptinst.usda")
await wait_for_update()
stage = self.ctx.get_stage()
prim = stage.GetPrimAtPath("/World/PointInstancer_parent")
pos = prim.GetAttribute('positions').Get()
new_pos = list(pos)
new_pos[0] = Gf.Vec3d(300,300,0)
prim.GetAttribute('positions').Set(new_pos)
await wait_for_update()
await self.capture_and_compare(self.TEST_PATH, "nested_ptinst.png")
# OM-38291 Verify no crash with full update from Nucleus
super().open_usd("hydra/OM-38291-one_ptinst.usda")
await wait_for_update()
stage = self.ctx.get_stage()
# Mock a full update from Nucleus live edit by clearing and reloading the layer.
stage.GetRootLayer().Clear()
await wait_for_update()
stage.GetRootLayer().Reload(True)
await wait_for_update()
# OM-110897 Verify no crash with nested point instancers with different dimensions
super().open_usd("hydra/nested_ptinst_extradim.usda")
await wait_for_update()
stage = self.ctx.get_stage()
await wait_for_update()
| 47,596 | Python | 46.980847 | 158 | 0.631272 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_selectionoutline.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
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
from pxr import UsdGeom
spherePath = '/World/Sphere'
cylinderPath = '/World/Cylinder'
defaultColor0 = [0, 0, 0, 0]
defaultColor1 = [0.7, 0.7, 0, 1]
defaultColor2 = [0.7, 0, 1, 1]
displayOptionSetting = "/persistent/app/viewport/displayOptions"
outlineWidthSetting = "/persistent/app/viewport/outline/width"
outlineColorSetting = "/persistent/app/viewport/outline/color"
shadeColorSetting = "/persistent/app/viewport/outline/shadeColor"
intersectionColorSetting = "/persistent/app/viewport/outline/intersection/color"
outlineEnabledSetting = "/app/viewport/outline/enabled"
class TestRtxSelectionOutline(RtxTest):
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
self.set_settings({displayOptionSetting: (1 << 7)})
omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings
# and stage.
await omni.kit.app.get_app().next_update_async() # Wait stage loading
self.set_settings(postLoadTestSettings)
self.set_settings({
outlineWidthSetting: 2,
outlineColorSetting: defaultColor0,
shadeColorSetting: defaultColor0,
intersectionColorSetting: defaultColor0,
"/app/transform/operation": "select"
})
self.create_scene()
self.ctx.set_selection_group_outline_color(255, defaultColor1)
def set_selected(self, path, select=True):
self.ctx.get_selection().set_prim_path_selected(path, select, True, False, True)
def create_scene(self):
stage = self.ctx.get_stage()
sphere = UsdGeom.Sphere.Define(stage, spherePath)
sphere.CreateRadiusAttr(100)
cylinder = UsdGeom.Cylinder.Define(stage, cylinderPath)
cylinder.CreateHeightAttr(200)
cylinder.CreateRadiusAttr(75)
async def test_rtx_selectionoutline_outline1(self):
"""
Test SelectionOutline - Outline sphere
"""
self.set_selected(spherePath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Outline1.png")
async def test_rtx_selectionoutline_outline2(self):
"""
Test SelectionOutline - Outline cylinder
"""
self.set_selected(cylinderPath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Outline2.png")
async def test_rtx_selectionoutline_outline12(self):
"""
Test SelectionOutline - Outline sphere & cylinder
"""
self.set_selected(spherePath)
self.set_selected(cylinderPath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Outline12.png")
async def test_rtx_selectionoutline_intersection(self):
"""
Test SelectionOutline - Intersection
"""
self.set_settings({intersectionColorSetting: defaultColor2})
self.set_selected(spherePath)
self.set_selected(cylinderPath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Intersection.png", 4e-5)
async def test_UNSTABLE_rtx_selectionoutline_thick(self):
"""
Test SelectionOutline - Outline sphere & cylinder, thick
"""
self.set_settings({outlineWidthSetting: 15})
self.set_selected(spherePath)
self.set_selected(cylinderPath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Thick.png")
async def test_rtx_selectionoutline_blend(self):
"""
Test SelectionOutline - Outline cylinder with blended color
"""
self.set_settings({outlineWidthSetting: 15})
c = defaultColor1[:3]
c.append(0.5)
self.ctx.set_selection_group_outline_color(255, c)
self.set_selected(cylinderPath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Blend.png")
async def test_rtx_selectionoutline_multicolored(self):
"""
Test SelectionOutline - Outline sphere & cylinder with different colors
"""
self.set_settings({outlineWidthSetting: 4})
self.ctx.set_selection_group(1, spherePath)
self.ctx.set_selection_group(2, cylinderPath)
self.ctx.set_selection_group_outline_color(1, defaultColor1)
self.ctx.set_selection_group_outline_color(2, defaultColor2)
self.ctx.set_selection_group_shade_color(1, defaultColor0)
self.ctx.set_selection_group_shade_color(2, defaultColor0)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Multicolored.png")
async def test_rtx_selectionoutline_shade(self):
"""
Test SelectionOutline - Shade sphere
"""
self.set_settings({outlineWidthSetting: 4})
self.ctx.set_selection_group(1, spherePath)
self.ctx.set_selection_group(2, cylinderPath)
self.ctx.set_selection_group_shade_color(1, defaultColor1)
self.ctx.set_selection_group_shade_color(2, defaultColor0)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Shade.png")
async def test_UNSTABLE_rtx_selectionoutline_shade_multicolored_UNSTABLE(self):
"""
Test SelectionOutline - Shade sphere & cylinder with different colors
"""
self.set_settings({outlineWidthSetting: 4})
self.ctx.set_selection_group(1, spherePath)
self.ctx.set_selection_group(2, cylinderPath)
self.ctx.set_selection_group_shade_color(1, defaultColor1)
self.ctx.set_selection_group_shade_color(2, defaultColor2)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "ShadeMulticolored.png")
async def test_rtx_selectionoutline_disabled(self):
"""
Test SelectionOutline - Disabled
"""
self.set_settings({outlineEnabledSetting: False, displayOptionSetting: 0})
self.set_selected(spherePath)
self.set_selected(cylinderPath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Disabled.png")
# OM-102267 - unreliable in 105.1 branch
async def test_UNSTABLE_rtx_selectionoutline_disabledByMetadata_UNSTABLE(self):
"""
Test SelectionOutline - Disabled by metadata.
OM-34048
"""
self.ctx.get_stage().GetPrimAtPath(spherePath).SetMetadata('no_selection_outline', True)
self.set_selected(spherePath)
self.set_selected(cylinderPath)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "Outline2.png", 2e-5)
# OM-102267 - unreliable in 105.1 branch
async def test_UNSTABLE_rtx_selectionoutline_instances_UNSTABLE(self):
"""
Test Selection Outline - Instances
"""
self.open_usd("hydra/CubeWorld.usda")
PRIM_PATH = '/CubeWorld/CubeInstance'
cubeInstance = self.ctx.get_stage().GetPrimAtPath(PRIM_PATH)
cubeInstance.SetInstanceable(False)
self.set_selected(PRIM_PATH)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "InstanceableFalse.png", 4e-5)
self.set_selected(PRIM_PATH, False) # Unselect
cubeInstance.SetInstanceable(True)
self.set_selected(PRIM_PATH)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "InstanceableTrue.png", 4e-5)
async def test_rtx_selectionoutline_mouse_select(self):
"""Test mouse selection works in Viewport."""
from omni.kit import ui_test
from omni.kit.ui_test.vec2 import Vec2
self.open_usd("hydra/CubeInstance.usda")
omni.usd.get_context().get_selection().set_selected_prim_paths([], True)
await wait_for_update()
await ui_test.emulate_mouse_move_and_click(Vec2(256, 256))
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "MouseSelect.png", 4e-5)
async def test_rtx_selectionoutline_mouse_select_aov_changed(self):
"""Test mouse selection works in Viewport before and after AOV change."""
from omni.kit import ui_test
from omni.kit.ui_test.vec2 import Vec2
mouse_pos = Vec2(256, 256)
self.open_usd("hydra/CubeInstance.usda")
usd_context = omni.usd.get_context()
usd_context.get_selection().set_selected_prim_paths([], True)
await wait_for_update()
await ui_test.emulate_mouse_move_and_click(mouse_pos)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "MouseSelectAOVA.png", 4e-5)
# Reset selection to nothing
usd_context.get_selection().set_selected_prim_paths([], True)
# Add additional AOVs
from omni.kit.viewport.utility import get_active_viewport
from pxr import Sdf, Usd, UsdRender
stage = usd_context.get_stage()
render_product_path = Sdf.Path(get_active_viewport().render_product_path)
render_product = UsdRender.Product(stage.GetPrimAtPath(render_product_path))
ordered_vars_rel = render_product.GetOrderedVarsRel()
start_aov_len = len(ordered_vars_rel.GetForwardedTargets())
# Targets need to be adde don session-layer as other prims live there
with Usd.EditContext(stage, stage.GetSessionLayer()):
aov_name = "Depth"
render_var = UsdRender.Var.Define(stage, Sdf.Path(f"/Render/Vars/{aov_name}"))
render_var.GetSourceNameAttr().Set(aov_name)
render_var.GetDataTypeAttr().Set("float")
ordered_vars_rel.AddTarget(render_var.GetPath())
end_aov_len = len(render_product.GetOrderedVarsRel().GetForwardedTargets())
self.assertNotEqual(start_aov_len, end_aov_len)
# Re-select the object
await ui_test.emulate_mouse_move_and_click(mouse_pos)
await wait_for_update()
await self.capture_and_compare("SelectionOutline", "MouseSelectAOVB.png", 4e-5)
| 10,699 | Python | 40.960784 | 119 | 0.670904 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_hydra_scene_delegate_omni_imaging.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from sys import path
import omni.kit.app
import omni.kit.commands
import omni.kit.undo
import omni.kit.test
import omni.timeline
import carb.settings
from .test_hydra_common import RtxHydraTest
from .test_common import testSettings, postLoadTestSettings, wait_for_update
from pxr import Gf, UsdShade
import shutil, os, pathlib
class TestRtxHydraSceneDelegateOmniImagingSetEmissionColor(RtxHydraTest):
# OM-73180
# Prior to the update in this ticket the OmniImagingDelegate ignored
# certain parameters, "emission_color" being one of them. This test
# validates that is no longer the case.
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
super().open_usd("hydra/scene_delegate/emission_color/test.usda")
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
async def test_set_emission_color(self):
'''
Test OmniImagingDelegate don't ignore 'emission_color'
'''
await wait_for_update(wait_frames=10)
prim = self.ctx.get_stage().GetPrimAtPath("/World/Looks/mtl_emission/emission")
shader_prim = UsdShade.Shader(prim)
shader_prim.GetInput("emission_color").Set(Gf.Vec3f(1.0, 0.0, 0.0))
await wait_for_update(wait_frames=10)
await self.capture_and_compare("hydra/scene_delegate", "set_emission_color.png") | 1,865 | Python | 40.466666 | 88 | 0.723324 |
omniverse-code/kit/exts/omni.rtx.tests/omni/rtx/tests/test_scenedb.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
from .test_common import RtxTest, testSettings, postLoadTestSettings, wait_for_update
from pxr import UsdGeom, Sdf
import numpy as np
class TestRtxSceneDb(RtxTest):
TEST_PATH = "scenedb"
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
omni.usd.get_context().new_stage() # Important: it should be called before `setUp` method as it reset settings and stage.
self.add_dir_light()
await omni.kit.app.get_app().next_update_async() # Wait stage loading
self.set_settings(postLoadTestSettings)
def create_geometry(self, name):
sphere = UsdGeom.Sphere.Define(self.ctx.get_stage(), name)
sphere.CreateRadiusAttr(10)
def create_instancer(self, name, N):
pts = []
indices = []
sp = 250.
dx = 500. / N[0]
dy = 500. / N[1]
dz = 500. / N[2]
for i in np.arange(-sp, sp, dx):
for j in np.arange(-sp, sp, dy):
for k in np.arange(-sp, sp, dz):
pts.append((i, j, k))
indices.append(0)
print("Generated points: ", len(indices))
lyr = self.ctx.get_stage().GetRootLayer()
with Sdf.ChangeBlock():
instancer = lyr.GetPrimAtPath("/World/Instancer") or \
Sdf.PrimSpec(lyr.GetPrimAtPath("/World"), "Instancer", Sdf.SpecifierDef, "PointInstancer")
pos = lyr.GetAttributeAtPath("/World/Instancer.positions") or \
Sdf.AttributeSpec(instancer, "positions", Sdf.ValueTypeNames.Point3fArray)
pos.default = pts
protoIndices = lyr.GetAttributeAtPath("/World/Instancer.protoIndices") or \
Sdf.AttributeSpec(instancer, "protoIndices", Sdf.ValueTypeNames.IntArray)
protoIndices.default = indices
rel = lyr.GetRelationshipAtPath("/World/Instancer.prototypes") or \
Sdf.RelationshipSpec(instancer, "prototypes")
rel.targetPathList.prependedItems = [name]
async def test_sphere_PI_1M(self):
id = "/World/Sphere"
self.create_geometry(id)
self.create_instancer(id, (100, 100, 100))
await wait_for_update(self.ctx, 25) # Wait 25 frames before capture.
await self.capture_and_compare(self.TEST_PATH, "sphere1M.png", threshold=5e-5)
# Unstable due to crashes in SceneDB: OM-49598
async def test_UNSTABLE_sphere_PI_1M_Recreate_UNSTABLE(self):
id = "/World/Sphere"
self.create_geometry(id)
self.create_instancer(id, (100, 100, 100))
await wait_for_update(self.ctx, 25) # Wait 25 frames before capture.
self.ctx.get_stage().RemovePrim("/World/instancer")
self.create_instancer(id, (100, 100, 100))
await self.capture_and_compare(self.TEST_PATH, "sphere1M.png")
| 3,313 | Python | 43.783783 | 130 | 0.644431 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/peer_user_shared_data.py | import carb
import omni.usd
import omni.kit.usd.layers as layers
from pxr import Sdf, Usd, Tf, UsdGeom
from typing import List
from .constants import *
from .utils import (
get_user_shared_root_path, get_bound_camera_property_path,
get_following_user_property_path, get_selection_property_path
)
class PeerUserSharedData:
"""
Data abstraction to manage peer user data inside presence layer.
"""
def __init__(
self, usd_context: omni.usd.UsdContext,
shared_stage: Usd.Stage,
user_info: layers.LiveSessionUser
):
# Shared stage is the one in the live session folder with name users.live that holds all
# shared data for all users. Peer users camera will be replicated into the local session layer
# with path self.session_layer_camera_path if peer user is bound to the builtin camera.
self.shared_stage = shared_stage
self.user_info = user_info
self.usd_context = usd_context
user_name_identifier = Tf.MakeValidIdentifier(user_info.user_name.split('@')[0])
self.__replication_root_path = LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH.AppendElementString(
f"{user_name_identifier}_{user_info.user_id}"
)
self.__replication_camera_path = self.__replication_root_path.AppendElementString(
f"{user_name_identifier}_Camera_{user_info.user_id}"
)
# Creates corresponding replication inside local session layer.
stage = self.usd_context.get_stage()
target_layer = stage.GetSessionLayer()
with Usd.EditContext(stage, target_layer):
prim = stage.DefinePrim(self.__replication_root_path, "Scope")
omni.usd.editor.set_hide_in_stage_window(prim, True)
omni.usd.editor.set_hide_in_ui(prim, True)
# Creates user namespace inside shared stage
self.shared_root_path = get_user_shared_root_path(self.user_id)
prim_spec = Sdf.CreatePrimInLayer(self.shared_stage.GetRootLayer(), SESSION_SHARED_LAYER_ROOT_PATH)
prim_spec.specifier = Sdf.SpecifierDef
prim_spec = Sdf.CreatePrimInLayer(self.shared_stage.GetRootLayer(), self.shared_root_path)
prim_spec.specifier = Sdf.SpecifierDef
# The property that can be used to check which camera the user is bound to.
# Every user can bind two kinds of cameras:
# 1. Builtin cameras.
# 2. Cameras in the USD.
# If it's builtin cameras, the property value must be in the list of SHARED_BUILT_IN_CAMERA_LIST.
# If it's camera in the USD, the property value points to the camera path in the stage.
self.__bound_camera_property_path = get_bound_camera_property_path(self.user_id)
self.__selections_property_path = get_selection_property_path(self.user_id)
self.__following_user_property_path = get_following_user_property_path(self.user_id)
self.__shared_stage_builtin_camera_paths = {}
for camera_name in SHARED_BUILT_IN_CAMERA_LIST:
self.__shared_stage_builtin_camera_paths[camera_name] = self.shared_root_path.AppendElementString(camera_name)
self.__current_bound_camera_property_value: str = None
self.__current_selection_paths: List[Sdf.Path] = []
self.__current_following_user: str = None
self.update_bound_camera()
@property
def user_id(self):
return self.user_info.user_id
@property
def user_name(self):
return self.user_info.user_name
def destroy(self):
if self.usd_context.get_stage():
layers.LayerUtils.remove_prim_spec(
self.usd_context.get_stage().GetSessionLayer(),
self.__replication_root_path
)
self.shared_stage = None
self.usd_context = None
def update_bound_camera(self):
latest_bound_camera_path = self.__get_bound_camera_path_from_usd()
if latest_bound_camera_path != self.__current_bound_camera_property_value:
self.__current_bound_camera_property_value = latest_bound_camera_path
if not self.is_bound_to_builtin_camera():
layers.LayerUtils.remove_prim_spec(
self.usd_context.get_stage().GetSessionLayer(),
self.__replication_camera_path
)
else:
self.replicate_bound_camera_to_local()
with Sdf.ChangeBlock():
self.__hide_prim_and_set_display_name()
return True
return False
def update_selections(self):
latest_selections = self.__get_selections_from_usd()
if latest_selections != self.__current_selection_paths:
self.__current_selection_paths = latest_selections
return True
return False
def update_following_user(self):
latest_following_user = self.__get_following_user_from_usd()
if latest_following_user != self.__current_following_user:
self.__current_following_user = latest_following_user
return True
return False
@carb.profiler.profile
def replicate_bound_camera_to_local(self, property_names: List[str] = []):
builtin_camera_name = self.__bound_camera_property_value
path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None)
if not path:
return
shared_data_stage = self.shared_stage
stage = self.usd_context.get_stage()
bound_camera_prim = self.shared_stage.GetPrimAtPath(path)
if not bound_camera_prim:
return
bound_camera_path = bound_camera_prim.GetPath()
target_path = self.__replication_camera_path
target_layer = stage.GetSessionLayer()
with Sdf.ChangeBlock():
Sdf.CreatePrimInLayer(target_layer, target_path)
if property_names:
for property_name in property_names:
source_property_path = bound_camera_path.AppendProperty(property_name)
target_property_path = target_path.AppendProperty(property_name)
Sdf.CopySpec(
shared_data_stage.GetRootLayer(), source_property_path,
target_layer, target_property_path
)
else:
Sdf.CopySpec(shared_data_stage.GetRootLayer(), bound_camera_path, target_layer, target_path)
def is_bound_to_builtin_camera(self):
if self.__current_following_user:
return False
builtin_camera_name = self.__bound_camera_property_value
path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None)
return path is not None
def is_bound_camera_property_affected(self, changed_path: Sdf.Path):
changed_path = Sdf.Path(changed_path)
return changed_path == self.__bound_camera_property_path
def is_selection_property_affected(self, changed_path: Sdf.Path):
changed_path = Sdf.Path(changed_path)
return changed_path == self.__selections_property_path
def is_following_user_property_affected(self, changed_path: Sdf.Path):
changed_path = Sdf.Path(changed_path)
return changed_path == self.__following_user_property_path
def is_builtin_camera_affected(self, changed_path: Sdf.Path):
"""Checkes if the changes to path will influence the builtin camera prim if user is bound to builtin camera."""
changed_path = Sdf.Path(changed_path)
builtin_camera_name = self.__bound_camera_property_value
path = self.__shared_stage_builtin_camera_paths.get(builtin_camera_name, None)
# Not bound to builtin camera
if not path:
return False
return changed_path.GetPrimPath() == path
def get_bound_camera_prim(self) -> Usd.Prim:
"""Returns the bound camera in the local stage. It will return None if it's following other user."""
if self.__current_following_user:
return None
if self.is_bound_to_builtin_camera():
camera_path = self.__replication_camera_path
elif Sdf.Path.IsValidPathString(self.__bound_camera_property_value):
camera_path = Sdf.Path(self.__bound_camera_property_value)
else:
camera_path = None
if not camera_path:
return None
stage = self.usd_context.get_stage()
return stage.GetPrimAtPath(camera_path)
@property
def __bound_camera_property_value(self) -> str:
"""
Returns property value of bound camera path in shared stage. In order to support binding to both builtin cameras
and non-builtin cameras. The property value can be builtin camera name listed in the SHARED_BUILT_IN_CAMERA_LIST,
or the prim path in the local stage.
"""
if self.__current_bound_camera_property_value is None:
self.__current_bound_camera_property_value = self.__get_bound_camera_path_from_usd()
return self.__current_bound_camera_property_value
@property
def following_user_id(self) -> str:
"""The user id that this user is currently following."""
if self.__current_following_user is None:
self.__current_following_user = self.__get_following_user_from_usd()
return self.__current_following_user
@property
def selections(self) -> List[Sdf.Path]:
if self.__current_selection_paths is None:
self.__current_selection_paths = self.__get_selections_from_usd()
return self.__current_selection_paths
def __get_following_user_from_usd(self):
following_user_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__following_user_property_path)
if not following_user_property:
return ""
return str(following_user_property.default).strip()
def __get_bound_camera_path_from_usd(self):
camera_path_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__bound_camera_property_path)
if not camera_path_property:
return ""
return str(camera_path_property.default).strip()
def __get_selections_from_usd(self):
selections_property = self.shared_stage.GetRootLayer().GetAttributeAtPath(self.__selections_property_path)
if not selections_property:
return []
selections = selections_property.default
selections = [Sdf.Path(selection) for selection in selections if Sdf.Path.IsValidPathString(str(selection))]
return selections
def __hide_prim_and_set_display_name(self):
stage = self.usd_context.get_stage()
prim = self.get_bound_camera_prim()
if not prim:
return
prim = prim.GetPrim()
with Sdf.ChangeBlock():
with Usd.EditContext(stage, stage.GetSessionLayer()):
omni.usd.editor.set_hide_in_stage_window(prim, True)
omni.usd.editor.set_hide_in_ui(prim, True)
omni.usd.editor.set_display_name(prim, self.user_info.user_name)
prim.CreateAttribute("omni:kit:cameraLock", Sdf.ValueTypeNames.Bool).Set(True)
| 11,222 | Python | 39.225806 | 122 | 0.642132 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/event.py | __all__ = ["PresenceLayerEventType", "PresenceLayerEventPayload", "get_presence_layer_event_payload"]
import carb
from enum import IntEnum
from typing import Set, List
EVENT_PAYLOAD_KEY = "payload"
class PresenceLayerEventType(IntEnum):
# Emitted when local user enters/quits follow mode to other peer users.
# REMIND: this event only applies to local user. In order to get the following status of other peer user,
# you need to listen for BOUND_CAMERA_CHANGED below and PresenceLayerAPI.is_in_following_mode to check
# if peer user is following other users.
LOCAL_FOLLOW_MODE_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@local_follow_mode")
# Emitted when peer user switched its bound camera or the the user that is following switches the bound camera.
BOUND_CAMERA_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@bound_camera")
# Emitted when peer user switched its selections.
SELECTIONS_CHANGED = carb.events.type_from_string("omni.kit.collaboration.presence_layer@selections")
# Emitted when the bound camera if peer user is builtin camera, and its properties are changed.
BOUND_CAMERA_PROPERTIES_CHANGED = carb.events.type_from_string(
"omni.kit.collaboration.presence_layer@bound_camera_properties"
)
# Emitted when the bound camera of peer user is resynced. This is the same as prim resync of USD.
BOUND_CAMERA_RESYNCED = carb.events.type_from_string(
"omni.kit.collaboration.presence_layer@bound_camera_resynced"
)
class PresenceLayerEventPayload:
def __init__(self, event: carb.events.IEvent) -> None:
carb_dict = carb.dictionary.get_dictionary()
if event.type and event.type in iter(PresenceLayerEventType):
self.event_type = PresenceLayerEventType(event.type)
if self.event_type == PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED:
self.__changed_users = carb_dict.get_dict_copy(event.payload)
elif EVENT_PAYLOAD_KEY in event.payload:
self.__changed_users = {}.fromkeys(event.payload[EVENT_PAYLOAD_KEY])
else:
self.__changed_users = {}
else:
self.event_type = None
self.__changed_users = {}
@property
def changed_user_ids(self) -> List[str]:
return self.__changed_users.keys()
def get_changed_camera_properties(self, user_id: str) -> Set[str]:
"""Gets the changed properties of bound builtin camera if event_type is BOUND_CAMERA_PROPERTIES_CHANGED."""
return self.__changed_users.get(user_id, set())
def __str__(self):
return f"Event Type: {str(self.event_type)}, Changes: {self.__changed_users}"
def get_presence_layer_event_payload(event: carb.events.IEvent) -> PresenceLayerEventPayload:
try:
return PresenceLayerEventPayload(event)
except Exception as e:
carb.log_error(f"Failed to convert event: {str(e)}")
return None
| 3,026 | Python | 42.869565 | 119 | 0.697951 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/constants.py | from pxr import Sdf
SESSION_SHARED_USER_LAYER = "shared_data/users.live"
SESSION_SHARED_LAYER_ROOT_PATH = Sdf.Path("/__session_shared_data__")
SESSION_SHARED_PERSPECTIVE_CAMERA_NAME = "perspective"
SESSION_SHARED_FRONT_CAMERA_NAME = "front"
SESSION_SHARED_LEFT_CAMERA_NAME = "left"
SESSION_SHARED_RIGHT_CAMERA_NAME = "right"
SESSION_SHARED_BOUND_CAMERA_PROPERTY_NAME = "bound_camera"
SESSION_SHARED_FOLLOWING_USER_PROPERTY_NAME = "following_user"
SESSION_SHARED_SELECTION_PROPERTY_NAME = "selected_prim_paths"
SHARED_BUILT_IN_CAMERA_LIST = [
SESSION_SHARED_PERSPECTIVE_CAMERA_NAME,
SESSION_SHARED_FRONT_CAMERA_NAME,
SESSION_SHARED_LEFT_CAMERA_NAME,
SESSION_SHARED_RIGHT_CAMERA_NAME
]
LOCAL_BUILT_IN_CAMERA_PATH_TO_SHARED_NAME = {
Sdf.Path("/OmniverseKit_Persp"): SESSION_SHARED_PERSPECTIVE_CAMERA_NAME,
Sdf.Path("/OmniverseKit_Top"): SESSION_SHARED_FRONT_CAMERA_NAME,
Sdf.Path("/OmniverseKit_Front"): SESSION_SHARED_LEFT_CAMERA_NAME,
Sdf.Path("/OmniverseKit_Right"): SESSION_SHARED_RIGHT_CAMERA_NAME,
}
SHARED_NAME_TO_LOCAL_BUILT_IN_CAMERA_PATH = {
SESSION_SHARED_PERSPECTIVE_CAMERA_NAME: Sdf.Path("/OmniverseKit_Persp"),
SESSION_SHARED_FRONT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Top"),
SESSION_SHARED_LEFT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Front"),
SESSION_SHARED_RIGHT_CAMERA_NAME: Sdf.Path("/OmniverseKit_Right"),
}
LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH = Sdf.Path("/OmniverseLiveSessionSharedData")
LAYER_SUBSCRIPTION_ORDER = -1 << 31 # make sure this runs before anything else
| 1,544 | Python | 40.756756 | 87 | 0.750648 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/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.
#
__all__ = ["PresenceLayerAPI", "get_presence_layer_interface", "PresenceLayerExtension"]
import carb
import omni.ext
import omni.usd
from .presence_layer_manager import PresenceLayerManager, PresenceLayerAPI
from typing import Dict, Union, List
__all_presence_layer_apis: Dict[omni.usd.UsdContext, PresenceLayerAPI] = {}
__all_presence_managers: List[PresenceLayerManager] = []
def shutdown_all():
global __all_presence_layer_apis
global __all_presence_managers
for presence_layer in __all_presence_managers:
presence_layer.stop()
__all_presence_layer_apis.clear()
__all_presence_managers.clear()
def get_presence_layer_interface(
context_name_or_instance: Union[str, omni.usd.UsdContext] = ""
) -> Union[PresenceLayerAPI, None]:
"""
Gets PresenceLayerAPI interface bound to the context. For each UsdContext, it has unique PresenceLayerAPI instance,
through which, you can access all the interfaces supported. PresenceLayerAPI provides the APIs that serve
for easy access to data of presence layer, where presence layer is the transport layer that works for exchange
persistent data for all users in the Live Session of the bound UsdContext. It only supports Live Session of root
layer for now.
"""
global __all_presence_layer_apis
if not context_name_or_instance:
context_name_or_instance = ""
if isinstance(context_name_or_instance, str):
usd_context = omni.usd.get_context(context_name_or_instance)
elif isinstance(context_name_or_instance, omni.usd.UsdContext):
usd_context = context_name_or_instance
else:
carb.log_warn("Failed to get presence layer interface since the param must be name or instance of UsdContext.")
return None
if not usd_context:
carb.log_warn("Failed to query presence layer interface since UsdContext cannot be found.")
return None
presence_layer_api = __all_presence_layer_apis.get(usd_context, None)
if not presence_layer_api:
presence_layer = PresenceLayerManager(usd_context)
presence_layer.start()
__all_presence_managers.append(presence_layer)
presence_layer_api = PresenceLayerAPI(presence_layer)
__all_presence_layer_apis[usd_context] = presence_layer_api
return presence_layer_api
class PresenceLayerExtension(omni.ext.IExt):
def on_startup(self):
# Initialize presence layer for default context.
get_presence_layer_interface()
def on_shutdown(self):
shutdown_all()
| 2,979 | Python | 36.25 | 119 | 0.728432 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/utils.py | import carb
from .constants import *
from pxr import Sdf, Usd, UsdGeom
class CarbProfilerScope: # pragma: no cover
def __init__(self, id, name):
self._id = id
self._name = name
def __enter__(self):
carb.profiler.begin(self._id, self._name)
def __exit__(self, type, value, trace):
carb.profiler.end(self._id)
@carb.profiler.profile
def get_user_id_from_path(path: Sdf.Path):
prefixes = path.GetPrefixes()
if len(prefixes) < 2:
return None
# "/{SESSION_SHARED_LAYER_ROOT_NAME}/_{self.user_id}"
# Premove the prefix _ to get real user id.
user_id = prefixes[1].name[1:]
return user_id
def is_local_builtin_camera(path: Sdf.Path):
"""
Checkes if it's local builtin camera. If so, it will return the corresponding builtin camera
name for bound camera property.
"""
path = Sdf.Path(path)
return LOCAL_BUILT_IN_CAMERA_PATH_TO_SHARED_NAME.get(path, None)
def get_user_shared_root_path(user_id: str) -> Sdf.Path:
# The prefix "_" is used to make sure the id is valid for identifier
return SESSION_SHARED_LAYER_ROOT_PATH.AppendElementString(f"_{user_id}")
def get_bound_camera_property_path(user_id: str) -> Sdf.Path:
shared_root_path = get_user_shared_root_path(user_id)
return shared_root_path.AppendProperty(SESSION_SHARED_BOUND_CAMERA_PROPERTY_NAME)
def get_selection_property_path(user_id: str) -> Sdf.Path:
shared_root_path = get_user_shared_root_path(user_id)
return shared_root_path.AppendProperty(SESSION_SHARED_SELECTION_PROPERTY_NAME)
def get_following_user_property_path(user_id: str) -> Sdf.Path:
shared_root_path = get_user_shared_root_path(user_id)
return shared_root_path.AppendProperty(SESSION_SHARED_FOLLOWING_USER_PROPERTY_NAME)
def get_or_create_property_spec(layer, property_path, typename, is_custom=True):
property_spec = layer.GetAttributeAtPath(property_path)
if property_spec and property_spec.typeName != typename:
carb.log_verboase(f"Type of property {property_spec} does not match: {property_spec.typeName}, {typename}.")
prim_spec = layer.GetPrimAtPath(property_path.GetPrimPath())
if prim_spec:
prim_spec.RemoveProperty(property_spec)
property_spec = None
if not property_spec:
Sdf.JustCreatePrimAttributeInLayer(
layer, property_path, typename, isCustom=is_custom
)
property_spec = layer.GetAttributeAtPath(property_path)
return property_spec
| 2,521 | Python | 30.135802 | 116 | 0.686632 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/presence_layer_manager.py | import asyncio
import carb
import time
import omni.client
import omni.usd
import omni.kit.usd.layers as layers
import omni.kit.app
from omni.kit.async_engine import run_coroutine
from pxr import Sdf, Usd, UsdGeom, Tf, Trace, Gf
from typing import Dict, List, Union, Set
from .utils import (
get_user_id_from_path, get_bound_camera_property_path, get_following_user_property_path,
get_selection_property_path, get_user_shared_root_path, get_or_create_property_spec,
is_local_builtin_camera
)
from .event import PresenceLayerEventType, EVENT_PAYLOAD_KEY
from .constants import *
from .peer_user_shared_data import PeerUserSharedData
class PresenceLayerChanges:
def __init__(self) -> None:
self.clear()
def clear(self):
self.bound_camera_changed_ids = set()
self.selection_changed_ids = set()
self.following_user_changed_ids = set()
self.camera_info_changes = {}
self.resynced_camera_ids = set()
def is_empty(self):
return (
not self.bound_camera_changed_ids and
not self.selection_changed_ids and
not self.following_user_changed_ids and
not self.camera_info_changes and
not self.resynced_camera_ids
)
def add_camera_info_change(self, user_id, path):
changes = self.camera_info_changes.get(user_id, None)
if changes is None:
self.camera_info_changes[user_id] = set()
# Changed property name
self.camera_info_changes[user_id].add(path.name)
def __str__(self):
return (f"Bound Camera Changed: {self.bound_camera_changed_ids}, "
f"Seletion Changed: {self.selection_changed_ids}, "
f"Following User Changed: {self.following_user_changed_ids}, "
f"Camera Info Changed: {self.camera_info_changes}, "
f"Camera Resynced: {self.resynced_camera_ids}")
class PresenceLayerManager:
def __init__(self, usd_context):
self.__usd_context = usd_context
self.__live_syncing = layers.get_live_syncing(self.__usd_context)
self.__layers = layers.get_layers(self.__usd_context)
self.__shared_data_stage = None
self.__peer_users: Dict[str, PeerUserSharedData] = {}
# Fast access to query the follow relationship. Key is the
# user id that's followed, and values are the user ids that
# are currently following this user.
self.__user_following_map: Dict[str, Set[str]] = {}
self.__layers_event_subscriptions = []
self.__stage_event_subscription = None
self.__shared_stage_objects_changed = None
self.__delayed_changes_handle_task = None
self.__local_following_user_id = None
self.__pending_changed_paths = set()
def start(self):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
layers.LayerEventType.LIVE_SESSION_MERGE_ENDED,
]:
layers_event_sub = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event, name=f"Layers event: omni.kit.collaboration.presence_layer {str(event)}",
order=LAYER_SUBSCRIPTION_ORDER
)
self.__layers_event_subscriptions.append(layers_event_sub)
self.__stage_event_subscription = self.__usd_context.get_stage_event_stream().create_subscription_to_pop(
self.__on_stage_event, name="Stage event: omni.kit.collaboration.presence_layer"
)
stage_url = self.__usd_context.get_stage_url()
if not stage_url.startswith("omniverse:"):
return
self.__on_session_state_changed()
def __on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self.__on_selection_changed()
elif event.type == int(omni.usd.StageEventType.CLOSING):
self.__stop_subscription()
def __on_selection_changed(self):
if not self.__shared_data_stage:
return
selection = self.__usd_context.get_selection()
selected_prim_paths = selection.get_selected_prim_paths() or []
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
logged_user_id = current_session.logged_user_id
selection_property_path = get_selection_property_path(logged_user_id)
with Sdf.ChangeBlock():
property_spec = get_or_create_property_spec(
self.__shared_data_stage.GetRootLayer(), selection_property_path,
Sdf.ValueTypeNames.StringArray
)
property_spec.default = selected_prim_paths
def __start_subscription(self):
# Skip it if one of its sublayer is in live session already.
if self.__shared_data_stage:
return
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
self.__shared_data_stage = self.__create_or_open_shared_stage(current_session)
if not self.__shared_data_stage:
return
self.__shared_stage_objects_changed = Tf.Notice.Register(
Usd.Notice.ObjectsChanged, self.__on_shared_usd_changed, self.__shared_data_stage
)
stage = self.__usd_context.get_stage()
target_layer = stage.GetSessionLayer()
with Usd.EditContext(stage, target_layer):
prim = stage.DefinePrim(LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH, "Scope")
omni.usd.editor.set_hide_in_stage_window(prim, True)
omni.usd.editor.set_hide_in_ui(prim, True)
for peer_user in current_session.peer_users:
self.__track_new_user(peer_user.user_id)
def __stop_subscription(self):
for peer_user in self.__peer_users.values():
peer_user.destroy()
self.__peer_users.clear()
self.__pending_changed_paths.clear()
self.__shared_data_stage = None
if self.__shared_stage_objects_changed:
self.__shared_stage_objects_changed.Revoke()
self.__shared_stage_objects_changed = None
if self.__delayed_changes_handle_task:
self.__delayed_changes_handle_task.cancel()
self.__delayed_changes_handle_task = None
local_stage = self.__usd_context.get_stage()
if local_stage:
layers.LayerUtils.remove_prim_spec(
local_stage.GetSessionLayer(),
LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH
)
self.__user_following_map.clear()
def stop(self):
self.__stop_subscription()
self.__layers_event_subscriptions = []
self.__stage_event_subscription = None
@carb.profiler.profile
def __notify_changes(self, pending_changes):
if pending_changes.is_empty():
return
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
if not event_stream:
return
def __check_and_send_events(event_type, changed_ids, lambda_filter):
valid_users = []
for user_id in changed_ids:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user or not lambda_filter(peer_user):
continue
valid_users.append(user_id)
if valid_users:
event_stream.push(int(event_type), 0, {EVENT_PAYLOAD_KEY: valid_users})
return valid_users
all_bound_camera_changed_ids = set()
for user_id in pending_changes.following_user_changed_ids:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user or not peer_user.update_following_user():
continue
old_following_user_id = peer_user.following_user_id
if old_following_user_id:
self.__remove_following_user(user_id, old_following_user_id)
new_following_user_id = peer_user.following_user_id
if new_following_user_id:
self.__track_following_user(user_id, new_following_user_id)
all_bound_camera_changed_ids.add(user_id)
for user_id in pending_changes.bound_camera_changed_ids:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user or not peer_user.update_bound_camera():
continue
all_bound_camera_changed_ids.add(user_id)
# Updates all users that are currently following this user also.
all_bound_camera_changed_ids.update(self.get_all_following_users(user_id))
if all_bound_camera_changed_ids:
event_stream.push(
int(PresenceLayerEventType.BOUND_CAMERA_CHANGED), 0,
{EVENT_PAYLOAD_KEY: list(all_bound_camera_changed_ids)}
)
__check_and_send_events(
PresenceLayerEventType.BOUND_CAMERA_RESYNCED,
pending_changes.resynced_camera_ids,
lambda user: True
)
__check_and_send_events(
PresenceLayerEventType.SELECTIONS_CHANGED,
pending_changes.selection_changed_ids,
lambda user: user.update_selections()
)
camera_info_changes = pending_changes.camera_info_changes
if camera_info_changes:
# FIXME: WA to make sure changes can be serialized to event stream.
camera_changes_payload = {}
with Sdf.ChangeBlock():
for user_id, property_names in camera_info_changes.items():
peer_user = self.__peer_users.get(user_id, None)
if property_names:
peer_user.replicate_bound_camera_to_local(property_names)
camera_changes_payload[user_id] = list(property_names)
event_stream.push(
int(PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED),
payload=camera_changes_payload
)
@carb.profiler.profile
async def __handling_pending_changes(self):
pending_changes = PresenceLayerChanges()
pending_changed_paths = self.__pending_changed_paths
self.__pending_changed_paths = set()
for path in pending_changed_paths:
if path == SESSION_SHARED_LAYER_ROOT_PATH or path == Sdf.Path.absoluteRootPath:
pending_changes.bound_camera_changed_ids.update(self.__peer_users.keys())
pending_changes.following_user_changed_ids.update(self.__peer_users.keys())
pending_changes.selection_changed_ids.update(self.__peer_users.keys())
pending_changes.resynced_camera_ids.update(self.__peer_users.keys())
break
user_id = get_user_id_from_path(path)
peer_user = self.__peer_users.get(user_id)
if not peer_user:
continue
if path == peer_user.shared_root_path:
pending_changes.bound_camera_changed_ids.add(user_id)
pending_changes.following_user_changed_ids.add(user_id)
pending_changes.selection_changed_ids.add(user_id)
pending_changes.resynced_camera_ids.add(user_id)
continue
# Checkes bound_camera property under user root
if peer_user.is_following_user_property_affected(path):
pending_changes.following_user_changed_ids.add(user_id)
elif peer_user.is_selection_property_affected(path):
pending_changes.selection_changed_ids.add(user_id)
elif peer_user.is_bound_camera_property_affected(path):
pending_changes.bound_camera_changed_ids.add(user_id)
elif peer_user.is_builtin_camera_affected(path):
# Only sync properties that are under camera prim.
if path.IsPropertyPath():
pending_changes.add_camera_info_change(user_id, path)
else:
pending_changes.resynced_camera_ids.add(user_id)
self.__notify_changes(pending_changes)
self.__delayed_changes_handle_task = None
@carb.profiler.profile
def __on_shared_usd_changed(self, notice, sender):
if not sender or sender != self.__shared_data_stage:
return
self.__pending_changed_paths.update(notice.GetResyncedPaths())
self.__pending_changed_paths.update(notice.GetChangedInfoOnlyPaths())
if not self.__pending_changed_paths:
return
if not self.__delayed_changes_handle_task or self.__delayed_changes_handle_task.done():
self.__delayed_changes_handle_task = run_coroutine(self.__handling_pending_changes())
def __create_or_open_shared_stage(self, session: layers.LiveSession):
session_url = session.url
if not session_url.endswith("/"):
session_url += "/"
shared_data_layer_path = omni.client.combine_urls(session_url, SESSION_SHARED_USER_LAYER)
layer = Sdf.Layer.FindOrOpen(shared_data_layer_path)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_layer_path)
if not layer:
carb.log_warn(f"Failed to open shared data layer {shared_data_layer_path}.")
return None
Sdf.CreatePrimInLayer(layer, SESSION_SHARED_LAYER_ROOT_PATH)
stage = Usd.Stage.Open(layer)
return stage
@property
def shared_data_stage(self) -> Usd.Stage:
return self.__shared_data_stage
def __on_session_state_changed(self):
if not self.__live_syncing.is_in_live_session():
self.__stop_subscription()
else:
self.__start_subscription()
def __track_new_user(self, user_id):
if user_id in self.__peer_users:
return
if not self.__shared_data_stage:
return
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
user_info = current_session.get_peer_user_info(user_id)
if not user_info:
return
peer_user = PeerUserSharedData(self.__usd_context, self.__shared_data_stage, user_info)
self.__peer_users[user_id] = peer_user
following_user_id = peer_user.following_user_id
if following_user_id:
self.__track_following_user(user_id, following_user_id)
def __track_following_user(self, user_id, following_user_id):
user_ids = self.__user_following_map.get(following_user_id, None)
if not user_ids:
user_ids = set()
self.__user_following_map[following_user_id] = user_ids
user_ids.add(user_id)
def __untrack_followed_user(self, user_id):
for following_users in self.__user_following_map.values():
following_users.discard(user_id)
self.__user_following_map.pop(user_id, None)
def __remove_following_user(self, user_id, followed_user_id):
"""Removes user_id from list that are currently following followed_user_id."""
user_list = self.__user_following_map.get(followed_user_id, None)
if not user_list:
return False
if user_id in user_list:
user_list.discard(user_id)
return True
return False
def __untrack_user(self, user_id):
self.__untrack_followed_user(user_id)
peer_user = self.__peer_users.pop(user_id, None)
if peer_user:
peer_user.destroy()
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if not payload:
return
interested_events = [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
layers.LayerEventType.LIVE_SESSION_MERGE_ENDED
]
if payload.event_type not in interested_events:
return
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
self.__on_session_state_changed()
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED:
# Creates user shared data
# Try to copy camera info and add widgets for the bound camera.
self.__track_new_user(payload.user_id)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
self.__untrack_user(payload.user_id)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_MERGE_ENDED:
if payload.success:
self.__shared_data_stage.GetRootLayer().Clear()
def get_all_following_users(self, followed_user_id):
"""Get all user ids that are currently following followed_user_id."""
return self.__user_following_map.get(followed_user_id, set())
def get_bound_camera_prim(self, user_id) -> Union[Usd.Prim, None]:
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
accessed_user_ids = set()
usd_prim = None
while True:
# To avoid A follows B and B follows A
if user_id in accessed_user_ids:
break
accessed_user_ids.add(user_id)
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
break
usd_prim = peer_user.get_bound_camera_prim()
if usd_prim:
break
# It's following other users.
user_id = self.get_following_user_id(user_id)
# If it's following me.
if user_id == current_session.logged_user_id:
accessed_user_ids.add(user_id)
shared_data_stage = self.__shared_data_stage
current_stage = self.__usd_context.get_stage()
my_bound_camera_property_path = get_bound_camera_property_path(user_id)
camera_path_property = shared_data_stage.GetRootLayer().GetAttributeAtPath(
my_bound_camera_property_path
)
if camera_path_property:
bound_camera_path = str(camera_path_property.default).strip()
# Maps builin camera binding to local path or keep it intact.
bound_camera_path = SHARED_NAME_TO_LOCAL_BUILT_IN_CAMERA_PATH.get(
bound_camera_path, bound_camera_path
)
if bound_camera_path:
usd_prim = current_stage.GetPrimAtPath(bound_camera_path)
break
# Otherwise, checking local Kit is following other user to pass the ball.
my_following_user_property_path = get_following_user_property_path(user_id)
following_user_property = shared_data_stage.GetRootLayer().GetAttributeAtPath(
my_following_user_property_path
)
if not following_user_property:
break
user_id = str(following_user_property.default).strip()
if not user_id or not current_session.get_peer_user_info(user_id):
break
return usd_prim
def is_bound_to_builtin_camera(self, user_id):
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
return False
return peer_user.is_bound_to_builtin_camera()
def get_following_user_id(self, user_id: str = None) -> str:
"""Gets the user id that the specific user is currently following."""
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return None
if user_id is None:
user_id = current_session.logged_user_id
# Local user is handled differently as peer users.
if user_id == current_session.logged_user_id:
following_user_property_path = get_following_user_property_path(current_session.logged_user_id)
following_user_property = self.__shared_data_stage.GetRootLayer().GetAttributeAtPath(
following_user_property_path
)
if following_user_property:
following_user_id = str(following_user_property.default).strip()
if following_user_id and following_user_id in self.__peer_users:
return following_user_id
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
return None
# Ensure the following user id is currently in the live session.
following_user = self.__peer_users.get(peer_user.following_user_id, None)
logged_user_id = current_session.logged_user_id
if following_user or peer_user.following_user_id == logged_user_id:
return peer_user.following_user_id
return None
def is_user_followed_by(self, user_id: str, followed_by_user_id: str) -> str:
following_user_id = self.get_following_user_id(followed_by_user_id)
return following_user_id == user_id
def get_selections(self, user_id: str) -> List[Sdf.Path]:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
return None
return peer_user.selections
def broadcast_local_bound_camera(self, local_camera_path: Sdf.Path):
if not local_camera_path:
local_camera_path = Sdf.Path.emptyPath
else:
local_camera_path = Sdf.Path(local_camera_path)
shared_data_stage = self.__shared_data_stage
if not shared_data_stage:
return
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return
# If camera does not exist
if local_camera_path:
current_stage = self.__usd_context.get_stage()
camera_prim = current_stage.GetPrimAtPath(local_camera_path)
if not camera_prim or not UsdGeom.Camera(camera_prim):
carb.log_error(f"Cannot sync camera {local_camera_path} to presence layer as it does not exist.")
return
logged_user_id = current_session.logged_user_id
bound_camera_property_path = get_bound_camera_property_path(logged_user_id)
following_user_property_path = get_following_user_property_path(logged_user_id)
local_builtin_camera = is_local_builtin_camera(local_camera_path)
camera_path = local_builtin_camera or local_camera_path # It's local builtin camera path or stage camera.
camera_path = str(camera_path) if camera_path else ""
with Sdf.ChangeBlock():
# Only synchronizes builtin camera as non-builtin cameras are visible to all users already.
if local_builtin_camera:
user_shared_root = get_user_shared_root_path(logged_user_id)
shared_camera_prim_path = user_shared_root.AppendElementString(local_builtin_camera)
Sdf.CreatePrimInLayer(shared_data_stage.GetRootLayer(), shared_camera_prim_path)
Sdf.CopySpec(
current_stage.GetSessionLayer(), local_camera_path,
shared_data_stage.GetRootLayer(), shared_camera_prim_path
)
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = camera_path
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = ""
# Notify all users that are currently following the local user.
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
all_bound_camera_changed_ids = set()
all_bound_camera_changed_ids.update(self.get_all_following_users(logged_user_id))
if all_bound_camera_changed_ids:
event_stream.push(
int(PresenceLayerEventType.BOUND_CAMERA_CHANGED), 0,
{EVENT_PAYLOAD_KEY: list(all_bound_camera_changed_ids)}
)
def __set_following_user_id_property(self, following_user_id):
"""Broadcasts local user's following id."""
shared_data_stage = self.__shared_data_stage
if not shared_data_stage:
return False
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return False
logged_user_id = current_session.logged_user_id
following_user_property_path = get_following_user_property_path(logged_user_id)
bound_camera_property_path = get_bound_camera_property_path(logged_user_id)
with Sdf.ChangeBlock():
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
if following_user_id:
property_spec.default = ""
else:
# Quits to perspective camera by default.
property_spec.default = "/OmniverseKit_Persp"
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = following_user_id
if self.__local_following_user_id:
self.__remove_following_user(logged_user_id, self.__local_following_user_id)
self.__local_following_user_id = following_user_id
if following_user_id:
self.__track_following_user(logged_user_id, following_user_id)
return True
def enter_follow_mode(self, following_user_id: str):
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
carb.log_warn(f"Cannot follow user {following_user_id} as it's not in a live session.")
return False
if current_session.logged_user_id == following_user_id:
carb.log_warn("Cannot follow myself.")
return False
following_user = self.__peer_users.get(following_user_id, None)
if not following_user:
carb.log_warn(f"Cannot follow user {following_user_id} as the user does not exist in the session.")
return False
if not self.get_bound_camera_prim(following_user_id):
message = f"Cannot follow user {following_user.user_name} as the user does not share bound camera."
try:
import omni.kit.notification_manager as nm
nm.post_notification(message, status=nm.NotificationStatus.WARNING)
except ImportError:
pass
finally:
carb.log_warn(message)
return False
# If user is already following me or other users, reports errors.
if (
following_user.following_user_id and
(
following_user.following_user_id == current_session.logged_user_id or
following_user.following_user_id in self.__peer_users
)
):
carb.log_warn(f"Cannot follow user {following_user.user_name} as the user is in following mode.")
return False
if self.get_following_user_id() == following_user_id:
return True
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
if self.__set_following_user_id_property(following_user_id):
event_stream.dispatch(PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
return True
return False
def quit_follow_mode(self):
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return False
if self.is_in_following_mode(current_session.logged_user_id):
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
if self.__set_following_user_id_property(""):
event_stream.dispatch(PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
def can_follow(self, user_id):
following_user = self.__peer_users.get(user_id, None)
return not following_user or following_user.following_user_id
def is_in_following_mode(self, user_id: str = None) -> bool:
"""
Checkes if the user is following other user.
user_id (str): The user id to check. By default, it's None, which means to check if local user is in follow mode.
"""
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return False
if user_id is None:
user_id = current_session.logged_user_id
following_user_id = self.get_following_user_id(user_id)
if following_user_id:
return True
else:
return False
class PresenceLayerAPI:
"""
Presence layer is the transport layer that works for exchange persistent data for
all users in the same Live Session. PresenceLayerAPI provides the APIs that serve
for easy access to data of presence layer.
"""
def __init__(self, presence_layer_instance: PresenceLayerManager) -> None:
self.__presence_layer_instance = presence_layer_instance
def is_bound_to_builtin_camera(self, user_id):
"""
Checkes if peer user is bound to builtin camera. If peer user is following other user,
it will always return False.
"""
return self.__presence_layer_instance.is_bound_to_builtin_camera(user_id)
@carb.profiler.profile
def get_bound_camera_prim(self, user_id) -> Union[Usd.Prim, None]:
"""
Gets the bound camera of the peer user in the local stage. If peer user is following other user, it will
return the bound camera of the following user.
"""
return self.__presence_layer_instance.get_bound_camera_prim(user_id)
def get_following_user_id(self, user_id: str = None) -> str:
"""
Gets the user id that the specific user is currently following.
user_id (str): User id, includes both local and peer users. If it's None, it will return the user id that
local user is currently following.
"""
return self.__presence_layer_instance.get_following_user_id(user_id)
def is_user_followed_by(self, user_id: str, followed_by_user_id: str) -> str:
"""
Checkes if user is followed by other specific user.
Args:
user_id (str): The user id to query.
followed_by_user_id (str): The user that's following the one has user_id.
"""
return self.__presence_layer_instance.is_user_followed_by(user_id, followed_by_user_id)
def get_selections(self, user_id: str) -> List[Sdf.Path]:
"""Gets the prim paths that the user selects."""
return self.__presence_layer_instance.get_selections(user_id)
@carb.profiler.profile
def broadcast_local_bound_camera(self, local_camera_path: Sdf.Path):
"""
Broadcasts local bound camera to presence layer. Local application can be either in
bound camera mode or following user mode. Switching bound camera will quit
following user mode.
"""
return self.__presence_layer_instance.broadcast_local_bound_camera(local_camera_path)
@carb.profiler.profile
def enter_follow_mode(self, following_user_id: str):
"""
Try to follow user from local. Local application can be either in
bound camera mode or following user mode. Switching bound camera will quit
following user mode. If the user specified by following_user_id is in following
mode already, this function will return False.
Args:
following_user_id (str): The user id that local user is trying to follow.
"""
return self.__presence_layer_instance.enter_follow_mode(following_user_id)
def quit_follow_mode(self):
self.__presence_layer_instance.quit_follow_mode()
def can_follow(self, user_id):
"""If the specified peer user can be followed."""
return self.__presence_layer_instance.can_follow(user_id)
def is_in_following_mode(self, user_id: str = None):
"""
Checkes if the user is following other user.
user_id (str): User id, including both the local and peer users. By default, it's None, which means to
check if local user is in follow mode.
"""
return self.__presence_layer_instance.is_in_following_mode(user_id)
def get_shared_data_stage(self):
return self.__presence_layer_instance.shared_data_stage
| 33,571 | Python | 38.589623 | 121 | 0.613446 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/tests/__init__.py | from .test_presence_layer import * | 34 | Python | 33.999966 | 34 | 0.794118 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/tests/test_presence_layer.py | import carb
import omni.kit.test
import omni.usd
import omni.client
import unittest
import omni.kit.app
import carb.settings
import omni.kit.collaboration.presence_layer as pl
import omni.kit.collaboration.presence_layer.utils as pl_utils
import omni.kit.usd.layers as layers
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi
from pxr import Usd, Sdf
from typing import List
class TestPresenceLayer(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
self.layers = layers.get_layers(self.usd_context)
self.live_syncing = layers.get_live_syncing(self.usd_context)
self.local_builtin_cameras = [
"/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"
]
await omni.usd.get_context().new_stage_async()
self.simulated_user_name = "test"
self.simulated_user_id = "abcde"
self.simulated_user_name2 = "test2"
self.simulated_user_id2 = "abcdef"
async def tearDown(self):
pass
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def __create_session_and_simulate_users(self):
session = self.live_syncing.find_live_session_by_name(self.stage_url, "test")
if not session:
session = self.live_syncing.create_live_session("test", self.stage_url)
self.assertTrue(session, "Failed to create live session.")
self.assertTrue(self.live_syncing.join_live_session(session))
await self.wait()
# Access private variable to simulate user login.
user = layers.LiveSessionUser(self.simulated_user_name, self.simulated_user_id, "Create")
user2 = layers.LiveSessionUser(self.simulated_user_name2, self.simulated_user_id2, "Create")
current_session = self.live_syncing.get_current_live_session()
session_channel = current_session._session_channel()
session_channel._peer_users[self.simulated_user_id] = user
session_channel._peer_users[self.simulated_user_id2] = user2
session_channel._send_layer_event(
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
{"user_name": self.simulated_user_name, "user_id": self.simulated_user_id}
)
session_channel._send_layer_event(
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
{"user_name": self.simulated_user_name2, "user_id": self.simulated_user_id2}
)
await self.wait()
def __get_shared_stage(self, current_session: layers.LiveSession):
shared_data_stage_url = current_session.url + "/shared_data/users.live"
layer = Sdf.Layer.FindOrOpen(shared_data_stage_url)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_stage_url)
return Usd.Stage.Open(layer)
async def __bound_camera(self, shared_stage: Usd.Stage, user_id: str, camera_path: Sdf.Path):
if not camera_path:
camera_path = Sdf.Path.emptyPath
camera_path = Sdf.Path(camera_path)
bound_camera_property_path = pl_utils.get_bound_camera_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
builtin_camera_name = pl_utils.is_local_builtin_camera(camera_path)
if not builtin_camera_name:
property_spec.default = str(camera_path)
else:
property_spec.default = builtin_camera_name
if builtin_camera_name:
persp_camera = pl_utils.get_user_shared_root_path(user_id).AppendChild(builtin_camera_name)
camera_prim = shared_stage.DefinePrim(persp_camera, "Camera")
await self.wait()
async def __select_prims(self, shared_stage: Usd.Stage, user_id: str, selections: List[str]):
selection_property_path = pl_utils.get_selection_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), selection_property_path,
Sdf.ValueTypeNames.StringArray
)
property_spec.default = selections
await self.wait()
async def __follow_user(
self, shared_stage: Usd.Stage, user_id: str, following_user_id: str
):
following_user_property_path = pl_utils.get_following_user_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = following_user_id
await self.wait()
@MockLiveSyncingApi
async def test_api(self):
self.stage_url = "omniverse://__faked_omniverse_server__/test/test.usd"
format = Sdf.FileFormat.FindByExtension(".usd")
layer = Sdf.Layer.New(format, self.stage_url)
stage = Usd.Stage.Open(layer)
await self.usd_context.attach_stage_async(stage)
self.all_camera_paths = []
for i in range(10):
camera_path = Sdf.Path(f"/Camera{i}")
stage.DefinePrim(camera_path, "Camera")
self.all_camera_paths.append(camera_path)
# Simulated builtin cameras
with Usd.EditContext(stage, stage.GetSessionLayer()):
for camera_path in self.local_builtin_cameras:
stage.DefinePrim(camera_path, "Camera")
self.all_camera_paths.append(camera_path)
def _on_layers_event(event):
nonlocal payload
p = pl.get_presence_layer_event_payload(event)
if p.event_type:
payload = p
subscription = self.layers.get_event_stream().create_subscription_to_pop(
_on_layers_event, name="omni.kit.collaboration.presence_layer.tests"
)
await self.__create_session_and_simulate_users()
current_live_session = self.live_syncing.get_current_live_session()
shared_stage = self.__get_shared_stage(current_live_session)
self.assertTrue(shared_stage)
presence_layer = pl.get_presence_layer_interface(self.usd_context)
# Simulated user has empty camera bound at start.
self.assertFalse(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id))
self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id))
self.assertFalse(presence_layer.get_following_user_id(self.simulated_user_id))
self.assertFalse(presence_layer.get_selections(self.simulated_user_id))
# Bound to invalid camera
for camera_path in ["/nonexisted", ""]:
await self.__bound_camera(shared_stage, self.simulated_user_id, camera_path)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED)
self.assertFalse(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id))
self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id))
payload = None
# Bound to valid camera
for camera_path in self.all_camera_paths:
camera_path = Sdf.Path(camera_path)
is_builtin_camera = pl_utils.is_local_builtin_camera(camera_path) is not None
await self.__bound_camera(shared_stage, self.simulated_user_id, camera_path)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED, camera_path)
self.assertEqual(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id), is_builtin_camera, camera_path)
self.assertTrue(presence_layer.get_bound_camera_prim(self.simulated_user_id), camera_path)
# Selections
for selections in [["/test", "/test2"], [], ["/test", "/test2", "test3"]]:
payload = None
await self.__select_prims(shared_stage, self.simulated_user_id, selections)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.SELECTIONS_CHANGED)
self.assertEqual(presence_layer.get_selections(self.simulated_user_id), selections, selections)
# Following user
# Setups default camera
logged_user_id = current_live_session.logged_user_id
presence_layer.broadcast_local_bound_camera("/OmniverseKit_Persp")
await self.__bound_camera(shared_stage, self.simulated_user_id2, self.all_camera_paths[0])
for user_id in [logged_user_id, self.simulated_user_id2]:
payload = None
await self.__follow_user(shared_stage, self.simulated_user_id, user_id)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED)
self.assertEqual(presence_layer.get_following_user_id(self.simulated_user_id), user_id)
self.assertTrue(presence_layer.is_user_followed_by(user_id, self.simulated_user_id))
self.assertTrue(presence_layer.get_bound_camera_prim(self.simulated_user_id))
user_id = "invalid_user_id"
payload = None
await self.__follow_user(shared_stage, self.simulated_user_id, user_id)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED)
self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id))
self.assertFalse(presence_layer.is_in_following_mode(self.simulated_user_id), user_id)
self.assertFalse(presence_layer.is_user_followed_by(user_id, self.simulated_user_id))
await self.__follow_user(shared_stage, self.simulated_user_id, "")
payload = None
self.assertFalse(presence_layer.enter_follow_mode(logged_user_id))
self.assertTrue(presence_layer.enter_follow_mode(self.simulated_user_id))
await self.wait()
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
self.assertEqual(presence_layer.get_following_user_id(), self.simulated_user_id)
self.assertTrue(presence_layer.is_in_following_mode(logged_user_id))
self.assertTrue(presence_layer.is_user_followed_by(self.simulated_user_id, logged_user_id))
payload = None
presence_layer.quit_follow_mode()
await self.wait()
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
self.assertFalse(presence_layer.get_following_user_id())
self.assertFalse(presence_layer.is_in_following_mode(logged_user_id))
self.assertFalse(presence_layer.is_user_followed_by(self.simulated_user_id, logged_user_id))
| 10,977 | Python | 45.12605 | 127 | 0.667213 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/hotkeys.py | from typing import Optional
import carb
import omni.kit.app
from omni.kit.actions.core import get_action_registry
_HOTKEYS_EXT = "omni.kit.hotkeys.core"
_DEFAULT_HOTKEY_MAP = {
"perspective_camera": "ALT+P",
"top_camera": "ALT+T",
"front_camera": "ALT+F",
"right_camera": "ALT+R",
"toggle_grid_visibility": "G",
"toggle_camera_visibility": "SHIFT+C",
"toggle_light_visibility": "SHIFT+L",
"toggle_global_visibility": "SHIFT+H",
"toggle_wireframe": "SHIFT+W",
}
def register_hotkeys(extension_id: str, window_name: Optional[str] = None):
ext_manager = omni.kit.app.get_app_interface().get_extension_manager()
if not ext_manager.is_extension_enabled(_HOTKEYS_EXT):
carb.log_info(f"{_HOTKEYS_EXT} is not enabled. Cannot register hotkeys.")
return
import omni.kit.hotkeys.core as hotkeys
hotkey_registry = hotkeys.get_hotkey_registry()
action_registry = get_action_registry()
ext_actions = action_registry.get_all_actions_for_extension(extension_id)
hotkey_filter = hotkeys.HotkeyFilter(windows=[window_name]) if window_name else None
hotkey_map = _DEFAULT_HOTKEY_MAP.copy()
# add UI hotkeys
if carb.settings.get_settings().get("exts/omni.kit.viewport.actions/ui_hotkeys"):
hotkey_map["toggle_ui"] = "F7"
# check if IAppWindowImplOs has already registered F11
if not carb.settings.get_settings().get("/exts/omni.appwindow/listenF11"):
hotkey_map["toggle_fullscreen"] = "F11"
if carb.settings.get_settings().get_as_bool( "/app/window/showDpiScaleMenu"):
hotkey_map["dpi_scale_increase"] = "EQUAL"
hotkey_map["dpi_scale_decrease"] = "MINUS"
for action in ext_actions:
key = hotkey_map.get(action.id, None)
# Not all Actions will have default hotkeys
if not key:
continue
hotkey_registry.register_hotkey(
hotkey_ext_id=extension_id,
key=key,
action_ext_id=action.extension_id,
action_id=action.id,
filter=hotkey_filter,
)
def deregister_hotkeys(extension_id: str):
ext_manager = omni.kit.app.get_app_interface().get_extension_manager()
if not ext_manager.is_extension_enabled(_HOTKEYS_EXT):
carb.log_info(f"{_HOTKEYS_EXT} is not enabled. No hotkeys to deregister.")
return
import omni.kit.hotkeys.core as hotkeys
hotkey_registry = hotkeys.get_hotkey_registry()
hotkey_registry.deregister_all_hotkeys_for_extension(extension_id)
| 2,546 | Python | 35.385714 | 88 | 0.661037 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/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.
#
__all__ = ["ViewportActionsExtension", "get_instance"]
from .actions import register_actions, deregister_actions
from .hotkeys import register_hotkeys, deregister_hotkeys
import omni.ext
import omni.kit.app
from typing import Callable
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
class ViewportActionsExtension(omni.ext.IExt):
"""Actions and Hotkeys related to the Viewport"""
def __init__(self):
super().__init__()
self._ext_name = None
self._hotkey_extension_enabled_hook = None
self._hotkey_extension_disabled_hook = None
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
self._ext_name = omni.ext.get_extension_name(ext_id)
# Hooks to hotkey extension enable/disable
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
hooks: omni.ext.IExtensionManagerHooks = ext_manager.get_hooks()
self._hotkey_extension_enabled_hook = hooks.create_extension_state_change_hook(
self._on_hotkey_ext_changed,
omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE,
ext_name="omni.kit.hotkeys.core",
)
self._hotkey_extension_disabled_hook = hooks.create_extension_state_change_hook(
self._on_hotkey_ext_changed,
omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE,
ext_name="omni.kit.hotkeys.core",
)
register_actions(self._ext_name)
register_hotkeys(self._ext_name)
def on_shutdown(self):
global _extension_instance
_extension_instance = None
self._hotkey_extension_enabled_hook = None
self._hotkey_extension_disabled_hook = None
deregister_hotkeys(self._ext_name)
deregister_actions(self._ext_name)
self._ext_name = None
del ViewportActionsExtension.__g_usd_context_streams
def _on_hotkey_ext_changed(self, ext_id: str, ext_change_type: omni.ext.ExtensionStateChangeType):
if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE:
register_hotkeys(self._ext_name)
if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE:
deregister_hotkeys(self._ext_name)
__g_usd_context_streams = None
@staticmethod
def _watch_stage_open(usd_context_name: str, open_callback: Callable):
if ViewportActionsExtension.__g_usd_context_streams is None:
ViewportActionsExtension.__g_usd_context_streams = {}
sub_id = ViewportActionsExtension.__g_usd_context_streams.get(usd_context_name, None)
if sub_id is not None:
return
import omni.usd
def on_stage_event(event):
if event.type == int(omni.usd.StageEventType.OPENED):
stage = omni.usd.get_context(usd_context_name).get_stage()
if stage:
open_callback(usd_context_name, stage)
ViewportActionsExtension.__g_usd_context_streams[usd_context_name] = (
omni.usd.get_context(usd_context_name).get_stage_event_stream().create_subscription_to_pop(
on_stage_event, name="omni.kit.viewport.actions.sticky_visibility"
)
)
| 3,792 | Python | 35.825242 | 103 | 0.671677 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/actions.py |
__all__ = ["register_actions", "deregister_actions"]
import omni.kit.actions.core
import omni.kit.viewport.utility
import carb
import omni.ui as ui
from pxr import Sdf, UsdGeom
from functools import partial
from typing import List, Optional, Sequence, Tuple
PERSP_CAM = "perspective_camera"
TOP_CAM = "top_camera"
FRONT_CAM = "front_camera"
RIGHT_CAM = "right_camera"
SHOW_ALL_PURPOSE = "toggle_show_by_purpose_all"
SHOW_GUIDE = "toggle_show_by_purpose_guide"
SHOW_PROXY = "toggle_show_by_purpose_proxy"
SHOW_RENDER = "toggle_show_by_purpose_render"
INERTIA_TOGGLE = "toggle_camera_inertia_enabled"
FILL_VIEWPORT_TOGGLE = "toggle_fill_viewport"
RENDERER_RTX_REALTIME = "set_renderer_rtx_realtime"
RENDERER_RTX_PT = "set_renderer_rtx_pathtracing"
RENDERER_RTX_TOGGLE = "toggle_rtx_rendermode"
RENDERER_IRAY = "set_renderer_iray"
RENDERER_PXR_STORM = "set_renderer_pxr_storm"
RENDERER_WIREFRAME = "toggle_wireframe"
PERSISTENT_SETTINGS_PREFIX = "/persistent"
INERTIA_ENABLE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/camInertiaEnabled"
FILL_VIEWPORT_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/fillViewport"
DISPLAY_GUIDE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/guide"
DISPLAY_PROXY_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/proxy"
DISPLAY_RENDER_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/render"
SECTION_VISIBILE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/{section}/visible"
SHADING_MODE_SETTING = "/exts/omni.kit.viewport.menubar.render/shadingMode"
SHOW_DPI_SCALE_MENU_SETTING = "/app/window/showDpiScaleMenu"
DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride"
DPI_SCALE_OVERRIDE_DEFAULT = -1.0
DPI_SCALE_OVERRIDE_MIN = 0.5
DPI_SCALE_OVERRIDE_MAX = 5.0
DPI_SCALE_OVERRIDE_STEP = 0.5
workspace_data = []
def register_actions(extension_id: str):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Viewport Camera Menu Actions"
action_registry.register_action(
extension_id,
PERSP_CAM,
partial(set_camera, "/OmniverseKit_Persp"),
display_name="Perspective Camera",
description="Switch to Perspective Camera",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
TOP_CAM,
partial(set_camera, "/OmniverseKit_Top"),
display_name="Top Camera",
description="Switch to Top Camera",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
FRONT_CAM,
partial(set_camera, "/OmniverseKit_Front"),
display_name="Front Camera",
description="Switch to Front Camera",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RIGHT_CAM,
partial(set_camera, "/OmniverseKit_Right"),
display_name="Right Camera",
description="Switch to Right Camera",
tag=actions_tag,
)
actions_tag = "Viewport Display Menu Actions"
action_registry.register_action(
extension_id,
SHOW_ALL_PURPOSE,
partial(
toggle_category_settings,
DISPLAY_GUIDE_SETTING,
DISPLAY_PROXY_SETTING,
DISPLAY_RENDER_SETTING,
),
display_name="Toggle Show All Purpose",
description="Toggle Show By Purpose - All",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
SHOW_GUIDE,
partial(_toggle_setting, DISPLAY_GUIDE_SETTING),
display_name="Toggle Show Guide Purpose",
description="Toggle Show By Purpose - Guide",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
SHOW_PROXY,
partial(_toggle_setting, DISPLAY_PROXY_SETTING),
display_name="Toggle Show Proxy Purpose",
description="Toggle Show By Purpose - Proxy",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
SHOW_RENDER,
partial(_toggle_setting, DISPLAY_RENDER_SETTING),
display_name="Toggle Show Render Purpose",
description="Toggle Show By Purpose - Render",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_camera_visibility",
toggle_camera_visibility,
display_name="Toggle Show Cameras",
description="Toggle Show By Type - Cameras",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_light_visibility",
toggle_light_visibility,
display_name="Toggle Show Lights",
description="Toggle Show By Type - Lights",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_skeleton_visibility",
toggle_skeleton_visibility,
display_name="Toggle Show Skeletons",
description="Toggle Show By Type - Skeletons",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_audio_visibility",
toggle_audio_visibility,
display_name="Toggle Show Audio",
description="Toggle Show By Type - Audio",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_mesh_visibility",
toggle_mesh_visibility,
display_name="Toggle Show Meshes",
description="Toggle Show By Type - Meshes",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_show_by_type_visibility",
toggle_show_by_type_visibility,
display_name="Toggle Show By Type",
description="Toggle Show By Type - All Type Toggle",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_grid_visibility",
toggle_grid_visibility,
display_name="Toggle Grid",
description="Toggle drawing of grid",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_axis_visibility",
toggle_axis_visibility,
display_name="Toggle Camera Axis",
description="Toggle drawing of camera axis",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_selection_hilight_visibility",
toggle_selection_hilight_visibility,
display_name="Toggle Selection Outline",
description="Toggle drawing of selection hilight",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_global_visibility",
toggle_global_visibility,
display_name="Toggle Global Visibility",
description="Toggle drawing of grid, HUD, audio, light, camera, and skeleton gizmos",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_viewport_visibility",
toggle_viewport_visibility,
display_name="Toggle Viewport item visibility",
description="Toggle drawing of Viewport items by key.",
tag=actions_tag,
)
actions_tag = "Viewport Settings Menu Actions"
action_registry.register_action(
extension_id,
INERTIA_TOGGLE,
partial(_toggle_setting, INERTIA_ENABLE_SETTING),
display_name="Toggle Camera Inertia Enabled",
description="Toggle Camera Inertia Mode Enabled",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
FILL_VIEWPORT_TOGGLE,
partial(_toggle_setting, FILL_VIEWPORT_SETTING),
display_name="Toggle Fill Viewport",
description="Toggle Fill Viewport Setting",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_lock_navigation_height",
partial(_toggle_setting, "/persistent/exts/omni.kit.manipulator.camera/flyViewLock"),
display_name="Toggle Lock Navigation Height",
description="Toggle whether fly-mode forward/backward and up/down uses ore ignores the camera orientation.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"set_viewport_resolution",
set_viewport_resolution,
display_name="Set Viewport Resolution",
description="Set a Viewport's resolution with a tuple or named constant.",
tag=actions_tag,
)
carb.settings.get_settings().set_default_bool(SHOW_DPI_SCALE_MENU_SETTING, False)
action_registry.register_action(
extension_id,
"toggle_ui",
on_toggle_ui,
display_name="Toggle Viewport UI Overlay",
description="Toggle Viewport UI Overlay",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_fullscreen",
on_fullscreen,
display_name="Toggle Viewport Fullscreen",
description="Toggle Viewport Fullscreen",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"dpi_scale_increase",
on_dpi_scale_increase,
display_name="DPI Scale Increase",
description="DPI Scale Increase",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"dpi_scale_decrease",
on_dpi_scale_decrease,
display_name="DPI Scale Decrease",
description="DPI Scale Decrease",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"dpi_scale_reset",
on_dpi_scale_reset,
display_name="DPI Scale Reset",
description="DPI scale reset to default",
tag=actions_tag,
)
actions_tag = "Viewport Render Menu Actions"
# TODO: these should maybe register dynamically as renderers are loaded/unloaded?
settings = carb.settings.get_settings()
available_engines = (settings.get('/renderer/enabled') or '').split(',')
ignore_loaded_engined = True
if ignore_loaded_engined or ('rtx' in available_engines):
action_registry.register_action(
extension_id,
RENDERER_RTX_REALTIME,
partial(set_renderer, "rtx", "RaytracedLighting"),
display_name="Set Renderer to RTX Realtime",
description="Set Renderer Engine to RTX Realtime",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RENDERER_RTX_PT,
partial(set_renderer, "rtx", "PathTracing"),
display_name="Set Renderer to RTX Pathtracing",
description="Set Renderer Engine to RTX Pathtracing",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RENDERER_RTX_TOGGLE,
toggle_rtx_rendermode,
display_name="Toggle RTX render-mode",
description="Toggle RTX render-mode between Realtime and Pathtracing",
tag=actions_tag,
)
if ignore_loaded_engined or ('iray' in available_engines):
action_registry.register_action(
extension_id,
RENDERER_IRAY,
partial(set_renderer, "iray", "iray"),
display_name="Set Renderer to RTX Accurate (Iray)",
description="Set Renderer Engine to RTX Accurate (Iray)",
tag=actions_tag,
)
if ignore_loaded_engined or ('pxr' in available_engines):
action_registry.register_action(
extension_id,
RENDERER_PXR_STORM,
partial(set_renderer, "pxr", "HdStormRendererPlugin"),
display_name="Set Renderer to Pixar Storm",
description="Set Renderer Engine to Pixar Storm",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RENDERER_WIREFRAME,
toggle_wireframe,
display_name="Toggle wireframe",
description="Toggle wireframe",
tag=actions_tag,
)
# HUD visibility actions
actions_tag = "Viewport HUD Visibility Actions"
action_registry.register_action(
extension_id,
"toggle_hud_fps_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderFPS"], action="toggle_hud_fps_visibility"),
display_name="Toggle Render FPS HUD visibility",
description="Toggle whether render fps item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_resolution_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderResolution"], action="toggle_hud_resolution_visibility"),
display_name="Toggle Render Resolution HUD visibility",
description="Toggle whether render resolution item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_progress_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderProgress"], action="toggle_hud_progress_visibility"),
display_name="Toggle Render Progress HUD visibility",
description="Toggle whether render progress item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_camera_speed_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/cameraSpeed"], action="toggle_hud_camera_speed_visibility"),
display_name="Toggle Camera Speed HUD visibility",
description="Toggle whether camera speed HUD item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_memory_visibility",
toggle_hud_memory_visibility,
display_name="Toggle Memory Item HUD visibility",
description="Toggle whether HUD memory items HUD are visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_visibility",
toggle_hud_visibility,
display_name="Toggle Gloabl HUD visiblity",
description="Toggle whether any HUD items are visible or not.",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
if action_registry:
action_registry.deregister_all_actions_for_extension(extension_id)
def _get_viewport_argument(viewport_api, action: str):
if not viewport_api:
viewport_api = omni.kit.viewport.utility.get_active_viewport()
if not viewport_api:
carb.log_warn(f"There was no provided or active Viewport - not able to run viewport-specific action: {action}.")
return None
return viewport_api
def set_camera(camera_str: str, viewport_api=None) -> bool:
"""Switch the camera in the active viewport based on the camera path.
Args:
camera_str (str): Camera Path in string form. ie "/OmniverseKit_Persp"
viewport_api (viewport): Optional viewport in order to set the camera
in a specific viewport.
Returns:
bool: True if successful, False if not.
"""
viewport = _get_viewport_argument(viewport_api, "set_camera")
if not viewport:
return False
stage = viewport.stage
if not stage:
carb.log_warn("Viewport Stage does not exist, to switch cameras.")
return False
camera_path = Sdf.Path(camera_str)
prim = stage.GetPrimAtPath(camera_path)
if not prim:
carb.log_warn(f"Prim for camera path: {camera_path} does not exist in the stage.")
return False
if not UsdGeom.Camera(prim):
carb.log_warn(f"Camera: {camera_path} does not exist in the stage.")
return False
viewport.camera_path = camera_path
return True
def set_renderer(engine_name, render_mode, viewport_api=None) -> bool:
viewport = _get_viewport_argument(viewport_api, "set_renderer")
if not viewport:
return False
viewport.set_hd_engine(engine_name, render_mode)
return True
def toggle_rtx_rendermode(viewport_api=None) -> bool:
viewport = _get_viewport_argument(viewport_api, "toggle_rtx_rendermode")
if not viewport:
return False
# Toggle to PathTracing when already on RTX and using RaytracedLighting
if viewport.hydra_engine == "rtx" and viewport.render_mode == "RaytracedLighting":
render_mode = "PathTracing"
else:
render_mode = "RaytracedLighting"
viewport.set_hd_engine("rtx", render_mode)
return True
def toggle_wireframe() -> str:
settings = carb.settings.get_settings()
mode = settings.get(SHADING_MODE_SETTING)
if mode == "wireframe":
# Set to default
settings.set(SHADING_MODE_SETTING, "default")
settings.set("/rtx/wireframe/mode", 0)
return "default"
else:
# Set to wireframe
settings.set(SHADING_MODE_SETTING, "wireframe")
settings.set("/rtx/debugView/target", "")
flat_shade = settings.get("/rtx/debugMaterialType") == 0
wire_mode = 2 if flat_shade else 1
settings.set("/rtx/wireframe/mode", wire_mode)
return "wireframe"
def toggle_category_settings(*setting_names):
settings = carb.settings.get_settings()
vals = [settings.get(setting_name) for setting_name in setting_names]
value_for_all = False if all(vals) else True
for setting_name in setting_names:
settings.set(setting_name, value_for_all)
def _toggle_setting(setting_name: str, viewport_api: Optional["ViewportAPI"] = None, visible: bool | None = None):
viewport_api = _get_viewport_argument(viewport_api, "_toggle_setting")
if not viewport_api:
return
setting_path = setting_name.format(viewport_api_id=viewport_api.id)
settings = carb.settings.get_settings()
if visible is None:
visible = not bool(settings.get(setting_path))
settings.set(setting_path, visible)
return visible
_k_setting_to_prim_type = {
"scene/cameras": {"Camera"},
"scene/skeletons": {"Skeleton"},
"scene/audio": {"Sound", "Listener"},
"scene/meshes": {"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"},
# "scene/lights"
}
def _stage_opened(usd_context_name: str, stage):
if not stage:
return
settings = carb.settings.get_settings()
reset_on_open = settings.get("/exts/omni.kit.viewport.actions/resetVisibilityOnOpen")
def get_display_option_and_off(setting_key: str):
vis_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible"
return (vis_key, not bool(settings.get(vis_key)))
def is_display_option_off(setting_key: str):
return get_display_option_and_off(setting_key)[1]
types_to_hide = set()
for setting_key, prim_types in _k_setting_to_prim_type.items():
vis_key, is_off = get_display_option_and_off(setting_key)
if reset_on_open and setting_key in reset_on_open:
if is_off:
settings.set(vis_key, True)
elif is_off:
types_to_hide.update(prim_types)
if not types_to_hide:
return
from omni.kit.viewport.actions.visibility import VisibilityEdit
VisibilityEdit(stage, types_to_show=None, types_to_hide=types_to_hide).run()
def _get_visible(visible: bool | Sequence[bool], index: int):
"""Utility function to get visibilty as a bool or from a bool or a list with index"""
getitem = getattr(visible, "__getitem__", None)
if getitem:
return bool(getitem(index))
return bool(visible)
def _toggle_legacy_display_visibility(viewport_api,
visible: bool | Sequence[bool],
setting_keys: Sequence[str],
reduce_sequence: bool) -> List[str]:
persitent_to_legacy_map = {
"hud/renderFPS": (1 << 0, None),
"guide/axis": (1 << 1, None),
"hud/renderResolution": (1 << 3, None),
"scene/cameras": (1 << 5, "/app/viewport/show/camera"),
"guide/grid": (1 << 6, "/app/viewport/grid/enabled"),
"guide/selection": (1 << 7, "/app/viewport/outline/enabled"),
"scene/lights": (1 << 8, "/app/viewport/show/lights"),
"scene/skeletons": (1 << 9, None),
"scene/meshes": (1 << 10, None),
"hud/renderProgress": (1 << 11, None),
"scene/audio": (1 << 12, "/app/viewport/show/audio"),
"hud/deviceMemory": (1 << 13, None),
"hud/hostMemory": (1 << 14, None),
}
settings = carb.settings.get_settings()
display_options = settings.get("/persistent/app/viewport/displayOptions") or 0
empty_tuple = (None, None)
result = []
for i in range(len(setting_keys)):
section, new_visible = setting_keys[i], _get_visible(visible, i)
section_mask, section_key = persitent_to_legacy_map.get(section, empty_tuple)
if section_mask is None:
continue
was_visible = bool(display_options & section_mask)
if new_visible is None:
display_options ^= section_mask
# Make new_visible != was_visible comparison below correct for state transition
new_visible = bool(display_options & section_mask)
elif new_visible != was_visible:
if new_visible:
display_options |= section_mask
else:
display_options &= ~section_mask
if new_visible != was_visible:
result.append(section)
if section_key:
settings.set(section_key, new_visible)
settings.set("/persistent/app/viewport/displayOptions", display_options)
# Reduce the case of a single item sequence to the item or None if requested
if reduce_sequence:
result = result[0] if result else None
return result
def _toggle_viewport_visibility(viewport_api,
visible: bool | Sequence[bool] | None,
setting_keys: Sequence[str],
action: str,
reduce_sequence: bool = True) -> List[str] | str | None:
viewport_api = _get_viewport_argument(viewport_api, action)
if not viewport_api:
return []
if hasattr(viewport_api, 'legacy_window'):
return _toggle_legacy_display_visibility(viewport_api, visible, setting_keys, reduce_sequence)
settings = carb.settings.get_settings()
usd_context_name = viewport_api.usd_context_name
def get_visibility(setting_key: str) -> Tuple[bool, str]:
# Currently settings in "scene" correspond to a state change in the Usd stage
if setting_key.startswith("scene"):
setting_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible"
else:
setting_key = f"/persistent/app/viewport/{viewport_api.id}/{setting_key}/visible"
return bool(settings.get(setting_key)), setting_key
if visible is None:
# No explicit visiblity given, figure out what things to flip
all_visible, any_visible = True, False
for setting_key in setting_keys:
# Get the current visibility
cur_visibility, _ = get_visibility(setting_key)
# If this any item is not visible, then the toggle is a transition to all items visible; early exit
if not cur_visibility:
all_visible = False
else:
any_visible = True
# Transition to hidden if all were visible, otherwise transition to visible
# All were visible => Nothing visible
# Nothing was visible => All visible
# Anything was visible => All visible
if any_visible and not all_visible:
visible = True
else:
visible = not all_visible
stage = viewport_api.stage
types_to_show, types_to_hide = set(), set()
# Apply any visibility UsdAttribute changes to the types requested
setting_to_prim_types = _k_setting_to_prim_type if stage else {}
result = []
# Find all the objects that need to be toggled
for i in range(len(setting_keys)):
setting_key, new_visible = setting_keys[i], _get_visible(visible, i)
cur_visibility, pref_key = get_visibility(setting_key)
cur_visibility = bool(cur_visibility)
if cur_visibility != new_visible:
settings.set(pref_key, new_visible)
prim_types = setting_to_prim_types.get(setting_key)
if prim_types:
if new_visible:
types_to_show.update(prim_types)
else:
types_to_hide.update(prim_types)
elif setting_key == "guide/selection":
# Still need to special case this to forward correctly (its global)
settings.set("/app/viewport/outline/enabled", new_visible)
# If visibility was toggled, add to the key to the return value
if new_visible != cur_visibility:
result.append(setting_key)
# Apply any visibility UsdAttribute changes to the types requested
if types_to_show or types_to_hide:
from .visibility import VisibilityEdit
VisibilityEdit(stage, types_to_show=types_to_show, types_to_hide=types_to_hide).run()
# The action is a toggle of state that is sticky across new stage's, so need to apply state to any new stage
from omni.kit.viewport.actions.extension import get_instance
get_instance()._watch_stage_open(usd_context_name, _stage_opened)
# Reduce the case of a single item sequence to the item or None if requested
if reduce_sequence:
result = result[0] if result else None
return result
def toggle_grid_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["guide/grid"], "toggle_grid_visibility")
def toggle_axis_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["guide/axis"], "toggle_axis_visibility")
def toggle_selection_hilight_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["guide/selection"], "toggle_selection_hilight_visibility")
def toggle_camera_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/cameras"], "toggle_camera_visibility")
def toggle_light_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/lights"], "toggle_light_visibility")
def toggle_skeleton_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/skeletons"], "toggle_skeleton_visibility")
def toggle_audio_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/audio"], "toggle_audio_visibility")
def toggle_mesh_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/meshes"], "toggle_mesh_visibility")
def toggle_show_by_type_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]:
return _toggle_viewport_visibility(viewport_api, visible,
["scene/cameras", "scene/lights", "scene/skeletons", "scene/audio"],
"toggle_show_by_type_visibility", False)
def _get_toggle_types(settings, setting_path: str) -> List[str]:
toggle_types = settings.get(setting_path)
if toggle_types is None:
return []
if isinstance(toggle_types, str):
return toggle_types.split(",")
return toggle_types
def toggle_global_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]:
viewport_api = _get_viewport_argument(viewport_api, "toggle_global_visibility")
if viewport_api and hasattr(viewport_api, "legacy_window"):
viewport_api.legacy_window.toggle_global_visibility_settings()
return []
# Get the list of what to hide (defaulting to what legacy Viewport and toggle_global_visibility_settings did)
settings = carb.settings.get_settings()
toggle_types = _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/globalTypes")
toggle_types += _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/hudTypes")
return _toggle_viewport_visibility(viewport_api, visible, toggle_types, "toggle_global_visibility", False)
def toggle_viewport_visibility(keys: Sequence[str], viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]:
return _toggle_viewport_visibility(viewport_api, visible, keys, "toggle_viewport_visibility", False)
def toggle_hud_memory_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None, host: bool = True, device: bool = True) -> str | None:
items = []
if host:
items.append("hud/hostMemory")
if device:
items.append("hud/deviceMemory")
if items:
return _toggle_viewport_visibility(viewport_api, visible, items, "toggle_hud_memory_visibility")
return []
def toggle_hud_visibility(viewport_api=None, visible: bool | None = None, use_setting: bool = False):
viewport = _get_viewport_argument(viewport_api, "toggle_hud_visibility")
if not viewport:
return
# as_menu works around a defect in Viewport-menu modeling of settings, where top-level item will enable
# or disable all child items only in the first grouping, but toggle_hud_visibility action should really mean
# all HUD items, (the ui-layer that contains any "hud/children" items).
if use_setting:
settings = carb.settings.get_settings()
toggle_types = _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/hudTypes")
toggled = _toggle_viewport_visibility(viewport, visible, toggle_types, "toggle_hud_visibility", reduce_sequence=False)
any_vis = bool(visible)
if not any_vis:
for key in toggle_types:
any_vis = settings.get(f"/persistent/app/viewport/{viewport.id}/{key}/visible")
if any_vis:
break
# If any of the children are now visible, make sure the top-level parent is also visible
if any_vis:
_toggle_setting("/persistent/app/viewport/{viewport_api_id}/hud/visible", viewport, visible=True)
return toggled
return _toggle_setting("/persistent/app/viewport/{viewport_api_id}/hud/visible", viewport)
def set_viewport_resolution(resolution, viewport_api=None):
viewport_api = _get_viewport_argument(viewport_api, "set_viewport_resolution")
if not viewport_api:
return
# Accept resolution as a named constant (str) as well as a tuple
if isinstance(resolution, str):
resolution_tuple = NAME_RESOLUTIONS = {
"Icon": (512, 512),
"Square": (1024, 1024),
"SD": (1280, 960),
"HD720P": (1280, 720),
"HD1080P": (1920, 1080),
"2K": (2048, 1080),
"1440P": (2560, 1440),
"UHD": (3840, 2160),
"Ultra Wide": (3440, 1440),
"Super Ultra Wide": (3840, 1440),
"5K Wide": (5120, 2880),
}.get(resolution)
if resolution_tuple is None:
carb.log_error("Resolution named {resolution} is not known.")
return
resolution = resolution_tuple
viewport_api.resolution = resolution
def set_ui_hidden(hide):
global workspace_data
if hide:
# hide context_menu
try:
omni.kit.context_menu.close_menu()
except:
pass
# windows are going to be hidden. Save workspace 1st
workspace_data = ui.Workspace.dump_workspace()
carb.settings.get_settings().set("/app/window/hideUi", hide)
else:
carb.settings.get_settings().set("/app/window/hideUi", hide)
# windows are going to be restored from hidden. Re-load workspace
# ui.Workspace.restore_workspace is async so it don't need to
# wait for initial unhide of the window here
ui.Workspace.restore_workspace(workspace_data, False)
workspace_data = []
def is_ui_hidden():
return carb.settings.get_settings().get("/app/window/hideUi")
def on_toggle_ui():
set_ui_hidden(not is_ui_hidden())
def on_fullscreen():
display_mode_lock = carb.settings.get_settings().get(f"/app/window/displayModeLock")
if display_mode_lock:
# Always stay in fullscreen_mode, only hide or show UI.
set_ui_hidden(not is_ui_hidden())
else:
# Only toggle fullscreen on/off when not display_mode_lock
was_fullscreen = omni.appwindow.get_default_app_window().is_fullscreen()
omni.appwindow.get_default_app_window().set_fullscreen(not was_fullscreen)
# Always hide UI in fullscreen
set_ui_hidden(not was_fullscreen)
def step_and_clamp_dpi_scale_override(increase):
import omni.ui as ui
# Get the current value.
dpi_scale = carb.settings.get_settings().get_as_float(DPI_SCALE_OVERRIDE_SETTING)
if dpi_scale == DPI_SCALE_OVERRIDE_DEFAULT:
dpi_scale = ui.Workspace.get_dpi_scale()
# Increase or decrease the current value by the setp value.
if increase:
dpi_scale += DPI_SCALE_OVERRIDE_STEP
else:
dpi_scale -= DPI_SCALE_OVERRIDE_STEP
# Clamp the new value between the min/max values.
dpi_scale = max(min(dpi_scale, DPI_SCALE_OVERRIDE_MAX), DPI_SCALE_OVERRIDE_MIN)
# Set the new value.
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, dpi_scale)
def on_dpi_scale_increase():
step_and_clamp_dpi_scale_override(True)
def on_dpi_scale_decrease():
step_and_clamp_dpi_scale_override(False)
def on_dpi_scale_reset():
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, DPI_SCALE_OVERRIDE_DEFAULT)
| 34,697 | Python | 35.71746 | 152 | 0.64484 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/visibility.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["VisibilityEdit"]
import carb
import omni.usd
from pxr import Usd, UsdGeom, Sdf
from typing import Callable, Optional, Sequence
def _get_usd_rt_stage(stage: Usd.Stage):
try:
from pxr import UsdUtils
from usdrt import Usd as UsdRtUsd
stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt()
fabric_active_for_stage = UsdRtUsd.Stage.StageWithHistoryExists(stage_id)
if fabric_active_for_stage:
return UsdRtUsd.Stage.Attach(stage_id)
except (ImportError, ModuleNotFoundError):
pass
return None
class VisibilityEdit:
def __init__(self, stage, types_to_show: Optional[Sequence[str]] = None, types_to_hide: Optional[Sequence[str]] = None):
# Sdf.Path.FindLongestPrefix require Sdf.PathVector (i.e. list) so we cannot use a dict
self.__path_to_change = {}
self.__stage = stage
self.__types_to_show = types_to_show
self.__types_to_hide = types_to_hide
self.__ignore_hidden_in_stage = carb.settings.get_settings().get("/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden")
def run(self):
if self.__gather_prims():
self.__hide_prims()
@carb.profiler.profile
def __get_prim_iterator(self, predicate):
# Early exit for request to do nothing
if not bool(self.__types_to_show) and not bool(self.__types_to_hide):
return
# Local function to filter Usd.Prim, returns None to ignore it or the Usd.Prim otherwise
def filter_prim(prim: Usd.Prim):
if self.__ignore_hidden_in_stage and omni.usd.editor.is_hide_in_stage_window(prim):
return None
return prim
# If UsdRt is available, use it to pre-prune the traversal to only given types
rt_stage = _get_usd_rt_stage(self.__stage)
if rt_stage:
# Merge all the prim-types of interest into one set for querying
if self.__types_to_show:
prim_types = set(self.__types_to_show)
if self.__types_to_hide:
prim_types = prim_types.union(set(self.__types_to_hide))
else:
prim_types = set(self.__types_to_hide)
for prim_type in prim_types:
for prim_path in rt_stage.GetPrimsWithTypeName(prim_type):
prim = filter_prim(self.__stage.GetPrimAtPath(prim_path.GetString()))
if prim:
yield prim
return
iterator = iter(self.__stage.Traverse(predicate))
for prim in iterator:
# Prune anything that is hide_in_stage_window
# Not sure why, but this matches legacy behavior
if filter_prim(prim) is None:
iterator.PruneChildren()
continue
yield prim
@property
def predicate(self):
return Usd.TraverseInstanceProxies(Usd.PrimDefaultPredicate)
def __get_visibility(self, prim: Usd.Prim, prim_path: Sdf.Path):
type_name = prim.GetTypeName()
make_visible = type_name in self.__types_to_show if self.__types_to_show else False
make_invisible = type_name in self.__types_to_hide if self.__types_to_hide else False
return (make_visible, make_invisible)
@carb.profiler.profile
def __gather_prims(self):
path_to_change = {}
# Traverse the satge, gathering the prims that have requested a visibility change
# This is a two-phase process to allow hiding leaves of instances by hiding the
# top-most un-instanced parent whose leaves are all of a hideable type
for prim in self.__get_prim_iterator(self.predicate):
prim_path = prim.GetPath()
make_visible, make_invisible = self.__get_visibility(prim, prim_path)
# If not making this type visible or invisible, then nothing to do
if (make_visible is False) and (make_invisible is False):
continue
if prim.IsInstanceProxy():
is_child = False
for path in path_to_change.keys():
if path.GetCommonPrefix(prim_path) == path:
is_child = True
break
if is_child:
continue
parent = prim.GetParent()
while parent and not parent.IsInstance():
parent = parent.GetParent()
# Insert the parent now and validate all children in the second phase
if parent:
path_to_change[parent.GetPath()] = True
else:
path_to_change[prim_path] = False
self.__path_to_change = path_to_change
return len(self.__path_to_change) != 0
@carb.profiler.profile
def __hide_prims(self):
# Traverse the instanced prims, making sure that all children are of the proper type
# or an allowed 'intermediate' type of Xform or Scope.
# If all children pass that test, then the instance can safely be hidden, otherwise
# it contains children that are not being requested as hidden, so the instance is left alone.
predicate = self.predicate
# UsdGeom.Imageabales that are acceptable intermediate children
allowed_imageables = set(("Xform", "Scope"))
# Setup the edit-context once, and batch all changes
session_layer = self.__stage.GetSessionLayer()
with Usd.EditContext(self.__stage, session_layer):
with Sdf.ChangeBlock():
for prim_path, is_instance in self.__path_to_change.items():
prim = self.__stage.GetPrimAtPath(prim_path)
if not prim:
continue
if prim.IsInstanceProxy():
carb.log_error(f"Unexpected instance in list of prims to toggle visibility: {prim.GetPath()}")
continue
# Assume success
toggle_error = None
visible = None
# If its an instance, traverse all children and make sure that
# they are of the right type, not a UsdImageable, or an allowed intermediate.
if is_instance:
for child_prim in prim.GetFilteredChildren(predicate):
child_type = child_prim.GetTypeName()
child_show, child_hide = self.__get_visibility(child_prim, child_prim.GetPath())
if (not child_show) and (not child_hide):
# If child is in neither list, than it must be an allowed intermediate type (or not an Imagaeable)
if (not UsdGeom.Imageable(child_prim)) or (child_type in allowed_imageables):
continue
toggle_error = "it contains at least one child with a type not being requested to hide."
break
# First loop iteration, set visible to proper state
if visible is None:
visible = child_show
if child_show != visible:
toggle_error = "its hiearchy is too heterogeneous for this action."
break
else:
visible = prim.GetTypeName() in self.__types_to_show if self.__types_to_show else False
if toggle_error:
visible_verb = 'show' if visible else 'hide'
carb.log_warn(f"Will not {visible_verb} '{prim_path}', {toggle_error}")
continue
if visible:
# as the session layer overrides all other layers, remove the primSpec
prim_spec = session_layer.GetPrimAtPath(prim_path)
property = session_layer.GetPropertyAtPath(prim_path.AppendProperty(UsdGeom.Tokens.visibility)) if prim_spec else None
if property:
prim_spec.RemoveProperty(property)
else:
imageable = UsdGeom.Imageable(prim)
if imageable:
imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.invisible)
| 8,950 | Python | 45.139175 | 148 | 0.574078 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_actions.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestActionsAndHotkeys']
import omni.kit.actions.core
from omni.kit.test import AsyncTestCase
from ..actions import is_ui_hidden, set_camera
class TestActionsAndHotkeys(AsyncTestCase):
async def setUp(self):
self.extension_id = "omni.kit.viewport.actions"
async def wait_n_updates(self, n_frames: int = 3):
app = omni.kit.app.get_app()
for _ in range(n_frames):
await app.next_update_async()
async def test_find_registered_action(self):
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action(self.extension_id, "perspective_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "top_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "front_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "right_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_rtx_rendermode")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "set_viewport_resolution")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_camera_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_light_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_grid_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_axis_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_selection_hilight_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_global_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_viewport_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_fps_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_resolution_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_progress_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_camera_speed_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_memory_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_wireframe")
self.assertIsNotNone(action)
async def test_action_return_values(self):
"""Test the return valus for actions match expected cases."""
await omni.usd.get_context().new_stage_async()
action_registry = omni.kit.actions.core.get_action_registry()
test_keys = ["scene/lights", "guide/grid", "guide/axis"]
try:
action = action_registry.get_action(self.extension_id, "toggle_camera_visibility")
self.assertIsNotNone(action)
# First toggle, should return key as camera's are visible by default
result = action.execute()
self.assertEqual(result, "scene/cameras")
# Re-run making invisible again, should do nothing as nothing was toggled
result = action.execute(visible=False)
self.assertEqual(result, None)
# Re-run making visible again, should return the type that was toggled
result = action.execute(visible=True)
self.assertEqual(result, "scene/cameras")
action = action_registry.get_action(self.extension_id, "toggle_viewport_visibility")
self.assertIsNotNone(action)
result = action.execute(keys=test_keys)
self.assertEqual(result, test_keys)
# Re-run making invisible again, should do nothing as nothing was toggled
result = action.execute(keys=test_keys, visible=False)
self.assertEqual(result, [])
# Re-run making visible again, should return the type that was toggled
sub_keys = [test_keys[0], test_keys[2]]
result = action.execute(keys=sub_keys, visible=True)
self.assertEqual(result, sub_keys)
# Test API to pass sequence of visibility bools (should return nothing as [0] and [2] are vis, and [1] is invis)
result = action.execute(keys=test_keys, visible=[True, False, True])
self.assertEqual(result, [])
# Test API to pass sequence of visibility bools (should return type of [1] as it is toggling to visible
result = action.execute(keys=test_keys, visible=[True, True, True])
self.assertEqual(result, [test_keys[1]])
action = action_registry.get_action(self.extension_id, "toggle_wireframe")
self.assertIsNotNone(action)
# First toggle, should change from "default" to "wireframe"
result = action.execute()
self.assertEqual(result, "wireframe")
# Re-run, should change fron "wireframe" to "default"
result = action.execute()
self.assertEqual(result, "default")
action = action_registry.get_action(self.extension_id, "top_camera")
self.assertIsNotNone(action)
result = action.execute()
self.assertTrue(result)
action = action_registry.get_action(self.extension_id, "front_camera")
self.assertIsNotNone(action)
result = action.execute()
self.assertTrue(result)
result = set_camera("/randomCamera") # Test for a camera that doesn't exist
self.assertFalse(result)
finally:
# Return everything to known startup state
action_registry.get_action(self.extension_id, "toggle_camera_visibility").execute(visible=True)
action_registry.get_action(self.extension_id, "toggle_viewport_visibility").execute(keys=test_keys, visible=True)
action_registry.get_action(self.extension_id, "perspective_camera").execute()
async def test_hud_action_overrides_parent_visibility(self):
"""Test that toggling any HUD item to visible will force the parent to visible"""
from omni.kit.viewport.utility import get_active_viewport_window
import carb.settings
try:
vp_window = get_active_viewport_window()
self.assertIsNotNone(vp_window)
self.assertIsNotNone(vp_window.viewport_api)
settings = carb.settings.get_settings()
hud_vis_path = f"/persistent/app/viewport/{vp_window.viewport_api.id}/hud/visible"
settings.set(hud_vis_path, False)
await self.wait_n_updates()
self.assertFalse(settings.get(hud_vis_path))
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action(self.extension_id, "toggle_hud_visibility")
self.assertIsNotNone(action)
action.execute(visible=True, use_setting=True)
# Should have forced the parent item back to True
await self.wait_n_updates()
self.assertTrue(settings.get(hud_vis_path))
finally:
pass
async def test_ui_toggling(self):
"""Test that ui toggles visibility and fullscreen correctly"""
await omni.usd.get_context().new_stage_async()
action_registry = omni.kit.actions.core.get_action_registry()
# Make sure it's not hidden to start with
self.assertFalse(is_ui_hidden())
action = action_registry.get_action(self.extension_id, "toggle_ui")
self.assertIsNotNone(action)
result = action.execute()
# Make sure it was hidden when toggled
self.assertTrue(is_ui_hidden())
result = action.execute()
# Make sure it is unhidden again after toggling again
self.assertFalse(is_ui_hidden())
action = action_registry.get_action(self.extension_id, "toggle_fullscreen")
self.assertIsNotNone(action)
await self.wait_n_updates(10)
# Make sure we're not fullscreen already
self.assertFalse(omni.appwindow.get_default_app_window().is_fullscreen())
result = action.execute()
await self.wait_n_updates(10)
# Make sure we are in fullscreen now
self.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen())
result = action.execute()
await self.wait_n_updates(10)
# Make sure we are back out of fullscreen
self.assertFalse(omni.appwindow.get_default_app_window().is_fullscreen())
| 9,685 | Python | 41.858407 | 125 | 0.661951 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/__init__.py | from .test_actions import *
from .test_visibility import *
from .test_extension import *
| 89 | Python | 21.499995 | 30 | 0.764045 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_extension.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestExtension']
import omni.kit.actions.core
from omni.kit.test import AsyncTestCase
class TestExtension(AsyncTestCase):
async def setUp(self):
self.extension_id = "omni.kit.viewport.actions"
async def wait_n_updates(self, n_frames: int = 3):
app = omni.kit.app.get_app()
for _ in range(n_frames):
await app.next_update_async()
async def test_extension_start_stop(self):
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = self.extension_id
self.assertTrue(ext_id)
self.assertTrue(manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, False)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(not manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, True)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(manager.is_extension_enabled(ext_id))
| 1,480 | Python | 36.024999 | 77 | 0.686486 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_visibility.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.viewport.actions.visibility import VisibilityEdit
import carb
import omni.kit.app
import omni.kit.test
import omni.timeline
from pxr import Sdf, Usd, UsdGeom
from functools import partial
from pathlib import Path
TEST_DATA_PATH = Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
).resolve().absolute().joinpath("data", "tests")
USD_TEST_DATA_PATH = TEST_DATA_PATH.joinpath("usd")
class TestVisibilitySetting(omni.kit.test.AsyncTestCase):
async def setUp(self):
super().setUp()
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
# After running each test
async def tearDown(self):
super().tearDown()
@staticmethod
def __is_in_set(prim_set: set, prim: Usd.Prim, prim_path: Sdf.Path) -> bool: # pragma: no cover
return prim.GetTypeName() in prim_set
@staticmethod
def __make_callback(prim_set: set):
return prim_set
async def test_hide_show_skeletons(self):
usd_path = USD_TEST_DATA_PATH.joinpath("visibility.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
is_skel_test = self.__make_callback({"SkelRoot"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_skel_test)
vis_edit.run()
# Skeleton should still be set to invisible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
# Everything else should be have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
vis_edit = VisibilityEdit(stage, types_to_show=is_skel_test, types_to_hide=None)
vis_edit.run()
# Skeleton should still be restored to inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Everything else should have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
async def test_hide_show_meshes(self):
usd_path = USD_TEST_DATA_PATH.joinpath("visibility.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
is_in_mesh = self.__make_callback({"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_in_mesh)
vis_edit.run()
# Skeleton should still be visible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Points should have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Everything else should be off or inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
vis_edit = VisibilityEdit(stage, types_to_show=is_in_mesh, types_to_hide=None)
vis_edit.run()
# Skeleton should still be visible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Points should have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Everything else should be restored to inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
async def test_hide_show_meshes_instanceable_references(self):
usd_path = USD_TEST_DATA_PATH.joinpath("referenced", "scene.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
is_in_mesh = self.__make_callback({"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_in_mesh)
vis_edit.run()
visibility_a = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_0/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
visibility_b = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_1/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
self.assertEqual(str(visibility_a), 'invisible')
self.assertEqual(str(visibility_b), 'invisible')
vis_edit = VisibilityEdit(stage, types_to_show=is_in_mesh, types_to_hide=None)
vis_edit.run()
visibility_a = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_0/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
visibility_b = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_1/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
self.assertEqual(str(visibility_a), 'inherited')
self.assertEqual(str(visibility_b), 'inherited')
async def __test_hide_show_hide_camera_at_time(self):
usd_path = USD_TEST_DATA_PATH.joinpath("cam_visibility.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
# Default should be visible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
# Hide cameras
is_camera = self.__make_callback({"Camera"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_camera)
vis_edit.run()
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
# Show cameras
vis_edit = VisibilityEdit(stage, types_to_show=is_camera, types_to_hide=None)
vis_edit.run()
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
async def test_hide_show_hide_camera(self):
'''Test show and hide of camera works at default time'''
await self.__test_hide_show_hide_camera_at_time()
async def test_hide_show_hide_camera_at_time(self):
'''Test show and hide of camera works at user time'''
try:
omni.timeline.get_timeline_interface().set_current_time(100)
await self.__test_hide_show_hide_camera_at_time()
finally:
omni.timeline.get_timeline_interface().set_current_time(0)
@omni.kit.test.omni_test_registry(guid="1e1fa926-ddf8-11ed-995d-ac91a108fede")
async def test_camera_visibility_stage_window_hidden(self):
'''Test show and hide of prims that accounts for objects hidden in stage window'''
usd_path = USD_TEST_DATA_PATH.joinpath("stage_window_hidden.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
# Default should be visible
def test_visibility(expected):
if isinstance(expected, str):
expected = [expected] * 4
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/CameraA")).ComputeVisibility()
self.assertEqual(str(visibility), expected[0])
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/CameraB")).ComputeVisibility()
self.assertEqual(str(visibility), expected[1])
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshA")).ComputeVisibility()
self.assertEqual(str(visibility), expected[2])
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshB")).ComputeVisibility()
self.assertEqual(str(visibility), expected[3])
test_visibility('inherited')
# Hide all camera and mesh
prim_test = self.__make_callback({"Camera", "Mesh"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=prim_test)
vis_edit.run()
test_visibility('invisible')
# Revert back and re-test
vis_edit = VisibilityEdit(stage, types_to_show=prim_test, types_to_hide=None)
vis_edit.run()
test_visibility('inherited')
settings = carb.settings.get_settings()
igswh = settings.get('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden')
try:
settings.set('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden', True)
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=prim_test)
vis_edit.run()
test_visibility(['invisible', 'inherited', 'invisible', 'inherited'])
# Revert back and re-test
vis_edit = VisibilityEdit(stage, types_to_show=prim_test, types_to_hide=None)
vis_edit.run()
test_visibility('inherited')
finally:
settings.set('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden', igswh)
| 17,167 | Python | 46.821727 | 130 | 0.694472 |
omniverse-code/kit/exts/omni.assets/omni/assets/yeller.py | import carb
import omni.ext
class AssetsYellerExtension(omni.ext.IExt):
def on_startup(self, ext_id):
carb.log_warn('omni.assets extension is deprecated! Please replace your dependency omni.assets -> omni.assets.plugins in extension.toml!')
def on_shutdown(self):
pass
| 296 | Python | 25.999998 | 146 | 0.719595 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/scripts/__init__.py | from .material_swap import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/scripts/material_swap.py | import os
import carb
import weakref
import omni.ext
import omni.kit.ui
import omni.usd
from typing import Callable
from pathlib import Path
from pxr import Usd, UsdGeom, Sdf, UsdShade
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
TEST_DATA_PATH = ""
_extension_instance = None
class MaterialSwapExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._build_ui()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
global _extension_instance
_extension_instance = self
def _build_ui(self):
self._window = omni.kit.ui.Window("Material Swap", 300, 200, menu_path="Window/Material Swap")
mat_settings = omni.kit.ui.CollapsingFrame("Material Swap Parameters", True)
field_width = 120
self._default_material_name = "None Selected"
self._old_mat = omni.kit.ui.TextBox(self._default_material_name)
self._old_mat_label = omni.kit.ui.Label("Material to Replace")
self._old_mat_selected = omni.kit.ui.Button("Use Selected")
self._old_mat_selected.set_clicked_fn(self._get_selectedold_fn)
self._old_mat.width = field_width * 3
self._old_mat_label.width = field_width
self._old_mat_selected.width = field_width
old_row = omni.kit.ui.RowLayout()
old_row.add_child(self._old_mat_label)
old_row.add_child(self._old_mat)
old_row.add_child(self._old_mat_selected)
self._new_mat = omni.kit.ui.TextBox(self._default_material_name)
self._new_mat_label = omni.kit.ui.Label("Material to Use")
self._new_mat_browse = omni.kit.ui.Button("Browse")
self._new_mat_browse.set_clicked_fn(self._on_browse_fn)
self._new_mat_selected = omni.kit.ui.Button("Use Selected")
self._new_mat_selected.set_clicked_fn(self._get_selectednew_fn)
def on_filter_item(dialog: FilePickerDialog, item: FileBrowserItem) -> bool:
if item and not item.is_folder and dialog.current_filter_option == 0:
_, ext = os.path.splitext(item.path)
return ext in [".mdl"]
return True
# create filepicker
dialog = FilePickerDialog(
"Open File",
apply_button_label="Open",
click_apply_handler=lambda filename, dirname, o=weakref.ref(self): MaterialSwapExtension._on_file_open(o, dialog, filename, dirname),
item_filter_options=["MDL Files (*.mdl)", "All Files (*)"],
item_filter_fn=lambda item: on_filter_item(dialog, item),
)
dialog.hide()
self._new_mat_fp = dialog
self._new_mat.width = field_width * 3
self._new_mat_label.width = field_width
self._new_mat_browse.width = field_width
self._new_mat_selected.width = field_width
new_row = omni.kit.ui.RowLayout()
new_row.add_child(self._new_mat_label)
new_row.add_child(self._new_mat)
new_row.add_child(self._new_mat_selected)
new_row.add_child(self._new_mat_browse)
mat_settings.add_child(old_row)
mat_settings.add_child(new_row)
# buttons
actions = omni.kit.ui.CollapsingFrame("Actions", True)
self._ui_swap_button = omni.kit.ui.Button("Swap")
self._ui_swap_button.set_clicked_fn(self._on_swap_fn)
self._ui_swap_button.width = omni.kit.ui.Percent(30)
actions.add_child(self._ui_swap_button)
self._window.layout.add_child(mat_settings)
self._window.layout.add_child(actions)
def _on_swap_fn(self, widget):
if self._old_mat.value == self._default_material_name:
carb.log_error('"Material To Replace" not set')
return
if self._new_mat.value == self._default_material_name:
carb.log_error('"Material to Use" not set')
return
stage = self._usd_context.get_stage()
for prim in stage.Traverse():
if not prim.GetMetadata("hide_in_stage_window") and omni.usd.is_prim_material_supported(prim):
mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
mat_path = mat.GetPath()
if mat_path == self._old_mat.value:
path = prim.GetPath()
omni.kit.commands.execute(
"BindMaterial",
prim_path=path,
material_path=self._new_mat.value,
strength=UsdShade.Tokens.weakerThanDescendants,
)
def _on_browse_fn(self, widget):
self._new_mat_fp.show()
@staticmethod
def _on_file_open(owner_weak, dialog: FilePickerDialog, filename: str, dirname: str):
owner = owner_weak()
if not owner:
return
file_path = ""
if dirname:
file_path = f"{dirname}/{filename}"
elif filename:
file_path = filename
dialog.hide()
if not "omniverse:" in file_path:
carb.log_warn("No local file support, please select an Omniverse asset")
owner._new_mat.value = "No local file support, please select an Omniverse asset"
else:
owner._import_file_path = file_path
base_name = os.path.basename(owner._import_file_path)
file_name, _ = os.path.splitext(os.path.basename(base_name))
file_name = owner._make_valid_identifier(file_name)
owner._add_material(file_path, file_name)
def _add_material(self, mat_path, mat_name):
stage = self._usd_context.get_stage()
d_xform = stage.GetDefaultPrim()
d_xname = str(d_xform.GetPath())
mat_prim = stage.DefinePrim("{}/Looks/{}".format(d_xname, mat_name), "Material")
mat = UsdShade.Material.Get(stage, mat_prim.GetPath())
if mat:
shader_prim = stage.DefinePrim("{}/Looks/{}/Shader".format(d_xname, mat_name), "Shader")
shader = UsdShade.Shader.Get(stage, shader_prim.GetPath())
if shader:
mdl_token = "mdl"
shader_out = shader.CreateOutput("out", Sdf.ValueTypeNames.Token)
mat.CreateSurfaceOutput(mdl_token).ConnectToSource(shader_out)
mat.CreateVolumeOutput(mdl_token).ConnectToSource(shader_out)
mat.CreateDisplacementOutput(mdl_token).ConnectToSource(shader_out)
shader.GetImplementationSourceAttr().Set(UsdShade.Tokens.sourceAsset)
shader.SetSourceAsset(mat_path, mdl_token)
shader.SetSourceAssetSubIdentifier(mat_name, mdl_token)
self._new_mat.value = str(mat.GetPath())
def _make_valid_identifier(self, identifier):
if len(identifier) == 0:
return "_"
result = identifier[0]
if not identifier[0].isalpha():
result = "_"
for i in range(len(identifier) - 1):
if identifier[i + 1].isalnum():
result += identifier[i + 1]
else:
result += "_"
return result
def _on_file_selected_fn(self, widget):
carb.log_warn("file selected fn")
def _get_selectedold_fn(self, widget):
paths = self._selection.get_selected_prim_paths()
base_path = paths[0] if len(paths) > 0 else None
base_path = Sdf.Path(base_path) if base_path else None
if base_path:
mat = self._get_material(base_path)
self._old_mat.value = str(mat)
else:
carb.log_error("No selected prim")
def _get_selectednew_fn(self, widget):
paths = self._selection.get_selected_prim_paths()
base_path = paths[0] if len(paths) > 0 else None
base_path = Sdf.Path(base_path) if base_path else None
if base_path:
mat = self._get_material(base_path)
self._new_mat.value = str(mat)
else:
carb.log_error("No selected prim")
def _get_material(self, path):
stage = self._usd_context.get_stage()
prim = stage.GetPrimAtPath(path)
p_type = prim.GetTypeName()
if p_type == "Material":
return path
else:
return None
def on_shutdown(self):
if self._new_mat_fp:
del self._new_mat_fp
self._new_mat_fp = None
global _extension_instance
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
| 8,818 | Python | 36.688034 | 145 | 0.598889 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/tests/__init__.py | from .test_material_swap import *
| 34 | Python | 16.499992 | 33 | 0.764706 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/tests/test_material_swap.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 unittest
import carb
import omni.kit.test
from pxr import Usd, UsdGeom, Sdf, UsdShade
class TestMaterialSwap(omni.kit.test.AsyncTestCase):
async def setUp(self):
from omni.kit.window.material_swap.scripts.material_swap import TEST_DATA_PATH
self._usd_path = TEST_DATA_PATH.absolute()
async def tearDown(self):
pass
async def test_material_swap(self):
def get_bound_material(path: str) -> str:
prim = omni.usd.get_context().get_stage().GetPrimAtPath(path)
mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
if mat:
return mat.GetPath().pathString
return ""
test_file_path = self._usd_path.joinpath("material_swap_test.usda").absolute()
await omni.usd.get_context().open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
material_swap = omni.kit.window.material_swap.get_instance()
selection = omni.usd.get_context().get_selection()
# verify initial state
self.assertEqual(get_bound_material('/World/studiohemisphere/Sphere'), "/World/Looks/GroundMat")
self.assertEqual(get_bound_material('/World/studiohemisphere/Floor'), "/World/Looks/GroundMat")
# select old material
selection.set_selected_prim_paths(["/World/Looks/GroundMat"], True)
material_swap._get_selectedold_fn(None)
await omni.kit.app.get_app().next_update_async()
# select new material
selection.set_selected_prim_paths(["/World/Looks/PreviewSurfaceTexture"], True)
material_swap._get_selectednew_fn(None)
await omni.kit.app.get_app().next_update_async()
# swap material
material_swap._on_swap_fn(None)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# verify change
self.assertEqual(get_bound_material('/World/studiohemisphere/Sphere'), "/World/Looks/PreviewSurfaceTexture")
self.assertEqual(get_bound_material('/World/studiohemisphere/Floor'), "/World/Looks/PreviewSurfaceTexture")
| 2,592 | Python | 41.508196 | 116 | 0.689043 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/extension.py | import omni.ext
from omni.rtx.window.settings import RendererSettingsFactory
from .widgets.common_widgets import CommonSettingStack
from .widgets.post_widgets import PostSettingStack
from .widgets.pt_widgets import PTSettingStack
from .widgets.rt_widgets import RTSettingStack
class RTXSettingsExtension(omni.ext.IExt):
MENU_PATH = "Rendering"
rendererNames = ["Real-Time", "Interactive (Path Tracing)"]
stackNames = ["Common", "Ray Tracing", "Path Tracing", "Post Processing"]
def on_startup(self):
RendererSettingsFactory.register_stack(self.stackNames[0], CommonSettingStack)
RendererSettingsFactory.register_stack(self.stackNames[1], RTSettingStack)
RendererSettingsFactory.register_stack(self.stackNames[2], PTSettingStack)
RendererSettingsFactory.register_stack(self.stackNames[3], PostSettingStack)
RendererSettingsFactory.register_renderer(
self.rendererNames[0], [self.stackNames[0], self.stackNames[1], self.stackNames[3]]
)
RendererSettingsFactory.register_renderer(
self.rendererNames[1], [self.stackNames[0], self.stackNames[2], self.stackNames[3]]
)
RendererSettingsFactory.build_ui()
def on_shutdown(self):
for renderer in self.rendererNames:
RendererSettingsFactory.unregister_renderer(renderer)
for stack in self.stackNames:
RendererSettingsFactory.unregister_stack(stack)
RendererSettingsFactory.build_ui()
| 1,496 | Python | 40.583332 | 95 | 0.731952 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/common_widgets.py | import omni.ui as ui
from omni.kit.widget.settings import SettingType
import omni.kit.commands
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
from omni.kit.widget.settings import SettingsWidgetBuilder
import carb
class GeometrySettingsFrame(SettingsCollectionFrame):
""" Geometry """
def _build_ui(self):
tbnMode = ["Auto", "CPU", "GPU", "Force GPU"]
scale_option = {"Default": -1, "Small - 1cm": 0.01, "Medium - 10 cm": 0.1, "Big - 100 cm": 1}
with ui.CollapsableFrame("Misc Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting_combo("Normal & Tangent Space Generation Mode", "/rtx/hydra/TBNFrameMode", tbnMode,
tooltip="\nMode selection for vertex Normals and Tangents generation. Options are:"
"\n-AUTO: Selects the mode depending on available data and data update pattern."
"\n-CPU: Uses mikktspace to generate tangent basis on the CPU."
"\n-GPU: Allows normal and tangent basis update on the GPU to avoid the CPU overhead, such as for deforming meshes."
"\n-Force GPU: Forces GPU mode.")
self._add_setting(SettingType.BOOL, "Back Face Culling", "/rtx/hydra/faceCulling/enabled",
tooltip="\nEnables back face culling for 'Single Sided' primitives."
"\nThis applies to UsdGeom prims set to 'Single Sided' since the Double Sided flag is ignored.")
self._add_setting(SettingType.BOOL, "USD ST Main Texcoord as Default UV Set", "/rtx/hydra/uvsets/stIsDefaultUvSet", tooltip="\nIf enabled, ST is considered to be the default UV set name.")
self._add_setting(SettingType.BOOL, "Hide Geometry That Uses Opacity (debug)", "/rtx/debug/onlyOpaqueRayFlags", tooltip="\nAllows hiding all objects which have opacity enabled in their material.")
self._add_setting(SettingType.BOOL, "Instance Selection", "/rtx/hydra/instancePickingEnabled", tooltip="\nEnables the picking of instances.")
# if set to zero, override to scene unit, which means the scale factor would be 1
self._add_setting_combo("Renderer-Internal Meters Per Unit", "/rtx/scene/renderMeterPerUnit", scale_option,
tooltip="\nNumber of units per meter used by the renderer relative to the scene scale."
"\nSome materials depend on scene scale, such as subsurface scattering and volumetric shading.")
self._add_setting(SettingType.FLOAT, "Ray Offset (0 = auto)", "/rtx/raytracing/rayOffset", 0.0, 5.0, 0.001, tooltip="\nOffset used to prevent ray-triangle self intersections." )
self._add_setting(SettingType.FLOAT, "Points Default Width", "/persistent/rtx/hydra/points/defaultWidth", tooltip="\nUses this value if width is not specified in UsdGeomPoints.")
with ui.CollapsableFrame("Wireframe Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Per-primitive Wireframe uses World Space Thickness", "/rtx/wireframe/wireframeThicknessWorldSpace", tooltip="\nInterprets the per-primitive wireframe thickness value in world space instead of screen space.")
self._add_setting(SettingType.BOOL, "Global Wireframe uses World Space Thickness", "/rtx/wireframe/globalWireframeThicknessWorldSpace", tooltip="\nInterprets the global wireframe thickness value in world space instead of screen space.")
self._add_setting(SettingType.FLOAT, "Thickness", "/rtx/wireframe/wireframeThickness", 0.1, 100, 0.1, tooltip="\nWireframe thickness in wireframe mode.")
def clear_refinement_overrides():
omni.kit.commands.execute("ClearRefinementOverrides")
with ui.CollapsableFrame("Subdivision Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.INT, "Global Refinement Level", "/rtx/hydra/subdivision/refinementLevel", 0, 8, hard_range=True,
tooltip="\nThe refinement level for all primitives with Subdivision Schema not set to None."
"\nEach increment increases the mesh triangle count by a factor of 4.")
self._add_setting(SettingType.BOOL, "Feature-Adaptive Refinement", "/rtx/hydra/subdivision/adaptiveRefinement",
tooltip="\nIncreases or reduces the refinement level based on geometric features."
"\nThis reduces the number of triangles used in flat areas for example.")
ui.Button("Clear Refinement Override in All Prims", clicked_fn=clear_refinement_overrides, tooltip="\nClears the Refinement Override set in all Prims.")
def clear_splits_overrides():
omni.kit.commands.execute("ClearCurvesSplitsOverridesCommand")
with ui.CollapsableFrame("Curves Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.INT, "Global Number of BVH Splits", "/rtx/hydra/curves/splits", 1, 8, hard_range=True,
tooltip="\nHigher number of splits results in faster rendering but longer BVH build time."
"\nThe speed up depends on the geometry: long and thin curve segments tend to benefit from more splits."
"\nMemory used by the BVH grows linearly with the number of splits.")
ui.Button("Clear Number of BVH Splits Overrides in All Prims", clicked_fn=clear_splits_overrides, tooltip="\nClears the Number of BVH Splits Refinement Override set in all Prims.")
class MaterialsSettingsFrame(SettingsCollectionFrame):
""" Materials """
def _on_change(self, *_):
self._rebuild()
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/app/renderer/skipMaterialLoading", self._on_change)
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx-transient/resourcemanager/enableTextureStreaming", self._on_change)
# The setting is maxMipCount, to make it more user friendly we expose it in the API as max resolution
texture_mip_sizes = {
"64": 7,
"128": 8,
"256": 9,
"512": 10,
"1024": 11,
"2048": 12,
"4096": 13,
"8192": 14,
"16384": 15,
"32768": 16,
}
self._add_setting(SettingType.BOOL, "Disable Material Loading", "/app/renderer/skipMaterialLoading", tooltip="\nScenes will be loaded without materials. This can lower scene loading time.")
if not self._settings.get("/app/renderer/skipMaterialLoading"):
with ui.CollapsableFrame("Texture Compression Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting_combo("Max Resolution", "/rtx-transient/resourcemanager/maxMipCount", texture_mip_sizes, tooltip="\nTextures larger than this will be downsampled at this resolution.")
self._add_setting(SettingType.INT, "Compression Size Threshold", "/rtx-transient/resourcemanager/compressionMipSizeThreshold", 0, 8192, tooltip="\nTextures smaller than this size won't be compressed. 0 disables compression.")
self._add_setting(SettingType.BOOL, "Normal Map Mip-Map Generation (toggling requires scene reload)", "/rtx-transient/resourcemanager/genMipsForNormalMaps", tooltip="\nEnables mip-map generation for normal maps to reduce memory usage at the expense of quality.")
# if self._settings.get("/rtx-transient/resourcemanager/genMipsForNormalMaps"):
# self._add_setting(SettingType.BOOL, "Normal Map Roughness generation (toggling requires scene reload)", "/rtx-transient/resourcemanager/createNormalRoughness", tooltip="\nEnables roughness generation for normal maps for improved specular reflection with mip mapping enabled.")
with ui.CollapsableFrame("Texture Streaming Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Enable Texture Streaming (toggling requires scene reload)", "/rtx-transient/resourcemanager/enableTextureStreaming", tooltip="\nEnables texture streaming.")
if self._settings.get("/rtx-transient/resourcemanager/enableTextureStreaming"):
self._add_setting(SettingType.FLOAT, " Memory Budget (% of GPU memory)", "/rtx-transient/resourcemanager/texturestreaming/memoryBudget", 0, 1, tooltip="\nLimits the GPU memory budget used for texture streaming.")
self._add_setting(SettingType.INT, " Budget Per Request (in MB)", "/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0, 10000,
tooltip="\nMaximum budget per streaming request. 0 = unlimited but could lead to stalling during streaming."
"\nHigh or unlimited budget could lead to stalling during streaming.")
with ui.CollapsableFrame("MDL Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.FLOAT, "Animation Time Override", "/rtx/animationTime", tooltip="\nOverrides the time value provided to MDL materials.")
self._add_setting(SettingType.BOOL, "Animation Time Use Wallclock", "/rtx/animationTimeUseWallclock", tooltip="\nUse actual elapsed time for animation instead of simulated time.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
super().destroy()
class LightingSettingsFrame(SettingsCollectionFrame):
""" Lighting """
def _build_ui(self):
with ui.CollapsableFrame("Light Visibility Settings", height=0):
with ui.VStack(height=0, spacing=5):
# Common show light setting for all render modes - this makes the /pathracing/showLights and /directLighting/showLights deprecated and should be used instead
# see LightTypes.hlslh for enum
show_lights_settings = {
"Per-Light Enable": 0,
"Force Enable": 1,
"Force Disable": 2
}
self._add_setting_combo("Show Area Lights In Primary Rays", "/rtx/raytracing/showLights", show_lights_settings, tooltip="\nDefines if area lights are visible or invisible in primary rays.")
self._add_setting(SettingType.FLOAT, "Invisible Lights Roughness Threshold", "/rtx/raytracing/invisLightRoughnessThreshold", 0, 1, 0.001,
tooltip="\nDefines the roughness threshold below which lights invisible in primary rays"
"\nare also invisible in reflections and refractions.")
self._add_setting(SettingType.BOOL, "Use First Distant Light & First Dome Light Only", "/rtx/scenedb/skipMostLights", tooltip="\nDisable all lights except the first distant light and first dome light.")
self._add_setting(SettingType.FLOAT, "Shadow Bias", "/rtx/raytracing/shadowBias", 0.0, 5.0, 0.001, tooltip="\nOffset applied for shadow ray origin along the surface normal. Reduces self-shadowing artifacts.")
with ui.CollapsableFrame("Dome Light Settings", height=0):
with ui.VStack(height=0, spacing=5):
dome_lighting_sampling_type = {
"Image-Based Lighting": 0,
"Approximated Image-Based Lighting": 4,
"Environment Mapped Image-Based Lighting": 3
}
self._add_setting_combo("Lighting Mode", "/rtx/domeLight/upperLowerStrategy", dome_lighting_sampling_type,
tooltip="\n-Image-Based Lighting: Most accurate even for high-frequency Dome Light textures. Can introduce sampling artefacts in real-time mode."
"\n-Approximated Image-Based Lighting: Fast and artefacts-free sampling in real-time mode but only works well with a low-frequency texture,"
"\nfor example a sky with no sun disc where the sun is instead a separate Distant Light. Requires enabling Direct Lighting denoiser."
"\n-Limited Image-Based Lighting: Only sampled for reflection and refraction. Fastest, but least accurate. Good for cases where the Dome Light"
"\ncontributes less than other light sources.")
dome_texture_resolution_items = {
"16": 16,
"32": 32,
"64": 64,
"128": 128,
"256": 256,
"512": 512,
"1024": 1024,
"2048": 2048,
"4096": 4096,
"8192": 8192,
}
self._add_setting_combo("Baking Resolution", "/rtx/domeLight/baking/resolution", dome_texture_resolution_items, tooltip="\nThe baking resolution of the Dome Light texture when an MDL material is used as its image source.")
class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame):
""" Global Volumetric Effects Common Settings RT & PT """
def _frame_setting_path(self):
return "/rtx/raytracing/globalVolumetricEffects/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Fog Height", "/rtx/raytracing/inscattering/atmosphereHeight", -2000, 100000, 10, tooltip="\nHeight in world units (centimeters) at which the medium ends. Useful for atmospheres with distant lights or dome lights.")
self._add_setting(SettingType.FLOAT, "Fog Height Fall Off", "/rtx/pathtracing/ptvol/fogHeightFallOff", 10, 2000, 1, tooltip="\nExponential decay of the fog above the Fog Height.")
self._add_setting(SettingType.FLOAT, "Maximum inscattering Distance", "/rtx/raytracing/inscattering/maxDistance", 10, 1000000,
tooltip="\nMaximum depth in world units (centimeters) the voxel grid is allocated to."
"\nIf set to 10,000 with 10 depth slices, each slice will span 1,000 units (assuming a slice distribution exponent of 1)."
"\nIdeally this should be kept as low as possible without causing artifacts to make the most of the fixed number of depth slices.")
self._add_setting(SettingType.FLOAT, "Density Multiplier", "/rtx/raytracing/inscattering/densityMult", 0, 2, 0.001, tooltip="\nScales the fog density.")
self._add_setting(SettingType.FLOAT, "Transmittance Measurment Distance", "/rtx/raytracing/inscattering/transmittanceMeasurementDistance", 0.0001, 1000000, 10, tooltip="\nControls how far light can travel through fog. Lower values yield thicker fog.")
self._add_setting(SettingType.COLOR3, "Transmittance Color", "/rtx/raytracing/inscattering/transmittanceColor",
tooltip="\nAssuming a white light, it represents its tint after traveling a number of units through"
"\nthe volume as specified in Transmittance Measurement Distance.")
self._add_setting(SettingType.COLOR3, "Single Scattering Albedo", "/rtx/raytracing/inscattering/singleScatteringAlbedo", tooltip="\nThe ratio of scattered-light to attenuated-light for an interaction with the volume. Values closer to 1 indicate high scattering.")
self._add_setting(SettingType.FLOAT, "Anisotropy Factor (g)", "/rtx/raytracing/inscattering/anisotropyFactor", -0.999, 0.999, 0.01,
tooltip="\nAnisotropy of the volumetric phase function, or the degree of light scattering asymmetry."
"\n-1 is back-scattered, 0 is isotropic, 1 is forward-scattered.")
with ui.CollapsableFrame("Density Noise Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Apply Density Noise", "/rtx/raytracing/inscattering/useDetailNoise", tooltip="\nEnables modulating the density with a noise. Enabling this option can reduce performance.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/inscattering/useDetailNoise", self._on_change)
if self._settings.get("/rtx/raytracing/inscattering/useDetailNoise"):
self._add_setting(SettingType.FLOAT, " World Scale", "/rtx/raytracing/inscattering/detailNoiseScale", 0.0, 1, 0.00001, tooltip="\nA scale multiplier for the noise. Smaller values produce more sparse noise.")
self._add_setting(SettingType.FLOAT, " Animation Speed X", "/rtx/raytracing/inscattering/noiseAnimationSpeedX", -1.0, 1.0, 0.01, tooltip="\nThe X vector for the noise shift when animated.")
self._add_setting(SettingType.FLOAT, " Animation Speed Y", "/rtx/raytracing/inscattering/noiseAnimationSpeedY", -1.0, 1.0, 0.01, tooltip="\nThe Y vector for the noise shift when animated.")
self._add_setting(SettingType.FLOAT, " Animation Speed Z", "/rtx/raytracing/inscattering/noiseAnimationSpeedZ", -1.0, 1.0, 0.01, tooltip="\nThe Z vector for the noise shift when animated.")
self._add_setting(SettingType.FLOAT, " Scale Min", "/rtx/raytracing/inscattering/noiseScaleRangeMin", -1.0, 5.0, 0.01,
tooltip="\nA range to map the noise values of each noise octave."
"\nTypically these should be 0 and 1."
"\nTo make sparse points in the noise less sparse a higher Min can be used, or a lower Max for dense points to be less dense.")
self._add_setting(SettingType.FLOAT, " Scale Max", "/rtx/raytracing/inscattering/noiseScaleRangeMax", -1.0, 5.0, 0.01,
tooltip="\nA range to map the noise values of each noise octave."
"\nTypically these should be 0 and 1. To make sparse points in the noise less sparse"
"\na higher Min can be used, or a lower Max for dense points to be less dense.")
self._add_setting(SettingType.INT, " Octave Count", "/rtx/raytracing/inscattering/noiseNumOctaves", 1, 8, tooltip="\nA higher octave count results in greater noise detail, at the cost of performance.")
def destroy(self):
self._change_cb1 = None
super().destroy()
class SimpleFogSettingsFrame(SettingsCollectionFrame):
""" Simple Fog """
def _frame_setting_path(self):
return "/rtx/fog/enabled"
def _build_ui(self):
self._add_setting(SettingType.COLOR3, "Color", "/rtx/fog/fogColor", tooltip="\nThe color or tint of the fog volume.")
self._add_setting(SettingType.FLOAT, "Intensity", "/rtx/fog/fogColorIntensity", 1, 1000000, 1, tooltip="\nThe intensity of the fog effect.")
self._add_setting(SettingType.BOOL, "Height-based Fog - Use +Z Axis", "/rtx/fog/fogZup/enabled", tooltip="\nUse positive Z axis for height-based fog. Otherwise use the positive Y axis.")
self._add_setting(SettingType.FLOAT, "Height-based Fog - Plane Height", "/rtx/fog/fogStartHeight", -1000000, 1000000, 0.01, tooltip="\nThe starting height (in meters) for height-based fog.")
self._add_setting(SettingType.FLOAT, "Height Density", "/rtx/fog/fogHeightDensity", 0, 1, 0.001, tooltip="\nDensity of the height-based fog. Higher values result in thicker fog.")
self._add_setting(SettingType.FLOAT, "Height Falloff", "/rtx/fog/fogHeightFalloff", 0, 1000, 0.002, tooltip="\nRate at which the height-based fog falls off.")
self._add_setting(SettingType.FLOAT, "Start Distance to Camera", "/rtx/fog/fogStartDist", 0, 1000000, 0.1, tooltip="\nDistance from the camera at which the fog begins.")
self._add_setting(SettingType.FLOAT, "End Distance to Camera", "/rtx/fog/fogEndDist", 0, 1000000, 0.1, tooltip="\nDistance from the camera at which the fog achieves maximum density.")
self._add_setting(SettingType.FLOAT, "Distance Density", "/rtx/fog/fogDistanceDensity", 0, 1, 0.001, tooltip="\nThe fog density at the End Distance.")
def destroy(self):
super().destroy()
class FlowSettingsFrame(SettingsCollectionFrame):
""" Flow """
def _frame_setting_path(self):
return "/rtx/flow/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Shadows", "/rtx/flow/rayTracedShadowsEnabled")
self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Reflections", "/rtx/flow/rayTracedReflectionsEnabled")
self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Translucency", "/rtx/flow/rayTracedTranslucencyEnabled")
self._add_setting(SettingType.BOOL, "Flow in Path-Traced Mode", "/rtx/flow/pathTracingEnabled")
self._add_setting(SettingType.BOOL, "Flow in Path-Traced Mode Shadows", "/rtx/flow/pathTracingShadowsEnabled")
self._add_setting(SettingType.BOOL, "Composite with Flow Library Renderer", "/rtx/flow/compositeEnabled")
self._add_setting(SettingType.BOOL, "Use Flow Library Self Shadow", "/rtx/flow/useFlowLibrarySelfShadow")
self._add_setting(SettingType.INT, "Max Blocks", "/rtx/flow/maxBlocks")
def destroy(self):
super().destroy()
class IndexCompositeSettingsFrame(SettingsCollectionFrame):
""" NVIDIA IndeX Compositing """
def _frame_setting_path(self):
return "/rtx/index/compositeEnabled"
def _build_ui(self):
ui.Label("You can activate IndeX composite rendering for individual Volume or Points prims "
"by enabling their 'Use IndeX compositing' property.", word_wrap=True)
ui.Separator()
depth_compositing_settings = {
"Disable": 0,
"Before Anti-Aliasing": 1,
"After Anti-Aliasing": 2,
"After Anti-Aliasing (Stable Depth)": 3
}
self._add_setting_combo(
"Depth Compositing",
"/rtx/index/compositeDepthMode",
depth_compositing_settings,
tooltip="Depth-correct compositing between renderers")
self._add_setting(
SettingType.FLOAT,
"Color Scaling",
"/rtx/index/colorScale",
0.0,
100.0,
tooltip="Scale factor for color output",
)
self._add_setting(
SettingType.BOOL,
"sRGB Conversion",
"/rtx/index/srgbConversion",
tooltip="Apply color space conversion to IndeX rendering",
)
self._add_setting(
SettingType.INT,
"Resolution Scaling",
"/rtx/index/resolutionScale",
1,
100,
tooltip="Reduces the IndeX rendering resolution (in percent relative to the viewport resolution)",
)
self._add_setting(
SettingType.INT,
"Rendering Samples",
"/rtx/index/renderingSamples",
1,
32,
tooltip="Number of samples per pixel used during rendering",
)
self._add_setting(
SettingType.FLOAT,
"Default Point Width",
"/rtx/index/defaultPointWidth",
tooltip="Default point width for new point clouds loaded from USD. If set to 0, a simple heuristic will be used.",
)
def destroy(self):
super().destroy()
class DebugViewSettingsFrame(SettingsCollectionFrame):
""" Debug View """
def _on_debug_view_change(self, *_):
self._rebuild()
def _build_ui(self):
debug_view_items = {
"Off": "",
"RT Developer Debug Texture": "developerDebug",
"3D Motion Vectors [WARNING: Flashing Colors]": "targetMotion",
"3D Motion Vector Arrows [WARNING: Flashing Colors]": "targetMotionArrows",
"3D Final Motion Vector Arrows [WARNING: Flashing Colors]": "finalMotion",
"Barycentrics": "barycentrics",
"Beauty After Tonemap": "beautyPostTonemap",
"Beauty Before Tonemap": "beautyPreTonemap",
"Depth": "depth",
"Instance ID": "instanceId",
"Interpolated Normal": "normal",
"Heat Map: Any Hit": "anyHitCountHeatMap",
"Heat Map: Intersection": "intersectionCountHeatMap",
"Heat Map: Timing": "timingHeatMap",
"SDG: Cross Correspondence": "sdgCrossCorrespondence",
"SDG: Motion": "sdgMotion",
"Tangent U": "tangentu",
"Tangent V": "tangentv",
"Texture Coordinates 0": "texcoord0",
"Texture Coordinates 1": "texcoord1",
"Triangle Normal": "triangleNormal",
"Triangle Normal (OctEnc)": "triangleNormalOctEnc", # ReLAX Only
"Wireframe": "wire",
"RT Ambient Occlusion": "ao",
"RT Caustics": "caustics",
"RT Denoised Dome Light": "denoisedDomeLightingTex",
"RT Denoised Sampled Lighting": "rtDenoisedSampledLighting",
"RT Denoised Sampled Lighting Diffuse": "rtDenoiseSampledLightingDiffuse", # ReLAX Only
"RT Denoised Sampled Lighting Specular": "rtDenoiseSampledLightingSpecular", # ReLAX Only
"RT Diffuse GI": "indirectDiffuse",
"RT Diffuse GI (Not Accumulated)": "indirectDiffuseNonAccum",
"RT Diffuse Reflectance": "diffuseReflectance",
"RT Material Normal": "materialGeometryNormal",
"RT Material Normal (OctEnc)": "materialGeometryNormalOctEnc", # ReLAX Only
"RT Matte Object Compositing Alpha": "matteObjectAlpha",
"RT Matte Object Mask": "matteObjectMask",
"RT Matte Object View Before Postprocessing": "matteBeforePostprocessing",
"RT Noisy Dome Light": "noisyDomeLightingTex",
"RT Noisy Sampled Lighting": "rtNoisySampledLighting",
"RT Noisy Sampled Lighting (Not Accumulated)": "rtNoisySampledLightingNonAccum",
"RT Noisy Sampled Lighting Diffuse": "rtNoisySampledLightingDiffuse", # ReLAX Only
"RT Noisy Sampled Lighting Diffuse (Not Accumulated)": "sampledLightingDiffuseNonAccum",
"RT Noisy Sampled Lighting Specular": "rtNoisySampledLightingSpecular", # ReLAX Only
"RT Noisy Sampled Lighting Specular (Not Accumulated)": "sampledLightingSpecularNonAccum",
"RT Radiance": "radiance",
"RT Subsurface Radiance": "subsurface",
"RT Subsurface Transmission Radiance": "subsurfaceTransmission",
"RT Reflections": "reflections",
"RT Reflections (Not Accumulated)": "reflectionsNonAccum",
"RT Reflections 3D Motion Vectors [WARNING: Flashing Colors]": "reflectionsMotion",
"RT Roughness": "roughness",
"RT Shadow (last light)": "shadow",
"RT Specular Reflectance": "reflectance",
"RT Translucency": "translucency",
"RT World Position": "worldPosition",
"PT Adaptive Sampling Error [WARNING: Flashing Colors]": "PTAdaptiveSamplingError",
"PT Denoised Result": "pathTracerDenoised",
"PT Noisy Result": "pathTracerNoisy",
"PT AOV Background": "PTAOVBackground",
"PT AOV Diffuse Filter": "PTAOVDiffuseFilter",
"PT AOV Direct Illumation": "PTAOVDI",
"PT AOV Global Illumination": "PTAOVGI",
"PT AOV Reflections": "PTAOVReflections",
"PT AOV Reflection Filter": "PTAOVReflectionFilter",
"PT AOV Refractions": "PTAOVRefractions",
"PT AOV Refraction Filter": "PTAOVRefractionFilter",
"PT AOV Self-Illumination": "PTAOVSelfIllum",
"PT AOV Volumes": "PTAOVVolumes",
"PT AOV World Normal": "PTAOVWorldNormals",
"PT AOV World Position": "PTAOVWorldPos",
"PT AOV Z-Depth": "PTAOVZDepth",
"PT AOV Multimatte0": "PTAOVMultimatte0",
"PT AOV Multimatte1": "PTAOVMultimatte1",
"PT AOV Multimatte2": "PTAOVMultimatte2",
"PT AOV Multimatte3": "PTAOVMultimatte3",
"PT AOV Multimatte4": "PTAOVMultimatte4",
"PT AOV Multimatte5": "PTAOVMultimatte5",
"PT AOV Multimatte6": "PTAOVMultimatte6",
"PT AOV Multimatte7": "PTAOVMultimatte7",
}
self._add_setting_searchable_combo("Render Target", "/rtx/debugView/target", debug_view_items, "Off", "\nA list of all render passes which can be visualized.")
debug_view_target = self._settings.get("/rtx/debugView/target")
# Trigger the combo update to reflect the current selection when the ui is rebuilt
self._settings.set("/rtx/debugView/target", debug_view_target);
# Subscribe this frame to the target setting so we can show the heat map controls if necessary.
# This will remove the subscription from the searchable combo, but we will have a chance to update it
# because the new callback does a rebuild.
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/debugView/target", self._on_debug_view_change)
is_timing_heat_map = debug_view_target == "timingHeatMap"
is_any_hit_count_heat_map = debug_view_target == "anyHitCountHeatMap"
is_intersection_count_heat_map = debug_view_target == "intersectionCountHeatMap"
if is_timing_heat_map or is_any_hit_count_heat_map or is_intersection_count_heat_map:
# 'heat_map_view_items' MUST perfectly match with 'HeatMapSelectablePass' in 'RtxRendererContext.h'
heat_map_view_items = {
"GBuffer RT": 1,
"Path Tracing": 2,
"Shadow RT": 3,
"Deferred LTC Lighting RT": 4,
"Deferred Sampled Lighting RT": 5,
"Reflections LTC RT ": 6,
"Reflections Sampled RT": 7,
"Back Lighting": 8,
"Translucency RT": 9,
"SSS RT": 10,
"Transmission RT": 11,
"Indirect Diffuse RT (Apply Cache)": 12,
"Ray Traced Ambient Occlusion": 13
}
# 'heat_map_color_palette_items' MUST perfectly match with condition in 'temperature' function in 'DebugView.cs.hlsl'
heat_map_color_palette_items = {
"Rainbow": 0,
"Viridis": 1,
"Turbo": 2,
"Plasma": 3
}
self._add_setting_combo(" Pass To Visualize ", "/rtx/debugView/heatMapPass", heat_map_view_items)
if is_timing_heat_map:
self._add_setting(SettingType.FLOAT, " Maximum Time (µs)", "/rtx/debugView/heatMapMaxTime", 0, 100000.0, 1.0)
elif is_any_hit_count_heat_map:
self._add_setting(SettingType.INT, " Maximum Any Hit", "/rtx/debugView/heatMapMaxAnyHitCount", 1, 100)
elif is_intersection_count_heat_map:
self._add_setting(SettingType.INT, " Maximum Intersection", "/rtx/debugView/heatMapMaxIntersectionCount", 1, 100)
self._add_setting_combo(" Color Palette", "/rtx/debugView/heatMapColorPalette", heat_map_color_palette_items)
self._add_setting(SettingType.BOOL, " Show Color Bar", "/rtx/debugView/heatMapOverlayHeatMapScale")
else:
self._add_setting(SettingType.FLOAT, " Output Value Scaling", "/rtx/debugView/scaling", -1000000, 1000000, 1.0, tooltip="\nScales the output value by this factor. Useful to accentuate differences.")
class MaterialFlattenerSettingsFrame(SettingsCollectionFrame):
""" Material Flattening """
def _build_ui(self):
import carb
if not carb.settings.get_settings().get("/rtx/materialflattener/enabled"):
ui.Label("Material flattener disabled, rerun with --/rtx/materialflattener/enabled=true")
else:
planarProjectionPlaneAxes = ["auto", "xy", "xz", "yz"]
self._add_setting_combo("Planar Projection Plane Axes", "/rtx/materialflattener/planarProjectionPlaneAxes", planarProjectionPlaneAxes)
self._add_setting(SettingType.BOOL, "Show Decal Sources", "/rtx/materialflattener/showSources")
self._add_setting(SettingType.BOOL, "Live Baking", "/rtx/materialflattener/liveBaking")
self._add_setting(SettingType.BOOL, "Rebaking", "/rtx/materialflattener/rebaking")
self._add_setting(SettingType.BOOL, "Clear before baking", "/rtx/materialflattener/clearMaterialInputsBeforeBaking")
coverageSamples = ["Disabled", "4", "16", "64", "256"]
self._add_setting_combo("Decal Antialiasing Samples", "/rtx/materialflattener/decalCoverageSamples", coverageSamples)
self._add_setting(SettingType.BOOL, "Disable tile budget", "/rtx/materialflattener/disableTileBudget")
self._add_setting(SettingType.INT, "Number of tiles per frame", "/rtx/materialflattener/maxNumTilesToBakePerFrame")
self._add_setting(SettingType.INT, "Number of texels per frame", "/rtx/materialflattener/maxNumTexelsToBakePerFrame")
self._add_setting(SettingType.INT, "Number of material components per bake pass", "/rtx/materialflattener/numMaterialComponentsPerBakePass", 1, 12)
self._add_setting(SettingType.INT, "VTex Group to bake (-1 ~ all)", "/rtx/materialflattener/vtexGroupToBake", -1, 1023)
self._add_setting(SettingType.BOOL, "Radius based tile residency", "/rtx/materialflattener/radiusBasedResidency")
self._add_setting(SettingType.FLOAT, "Radius based tile residency - radius", "/rtx/materialflattener/radiusBasedResidencyRadius", 0, 10000, 0.1)
self._add_setting(SettingType.FLOAT, "Lod: derivative scale", "/rtx/virtualtexture/derivativeScale", 0.01, 100, 0.01)
self._add_setting(SettingType.FLOAT, "Decal distance tolerance", "/rtx/materialflattener/decalDistanceTolerance", 0, 1000, 0.01)
self._add_setting(SettingType.FLOAT, "Sampling LOD Bias", "/rtx/textures/lodBias", -15, 15, 0.01)
self._add_setting(SettingType.INT, "VTex Group ID color option (0 = disabled)", "/rtx/virtualtexture/colorCodeByVtexGroupIdOption", 0, 4)
self._add_setting(SettingType.INT, "Baking LOD Bias (on top of Sampling LOD bias)", "/rtx/materialflattener/bakingLodBias", -15, 12)
class CommonSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
GeometrySettingsFrame("Geometry", parent=self)
MaterialsSettingsFrame("Materials", parent=self)
LightingSettingsFrame("Lighting", parent=self)
SimpleFogSettingsFrame("Simple Fog", parent=self)
GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self)
FlowSettingsFrame("Flow", parent=self)
# Only show IndeX settings if the extension is loaded
if carb.settings.get_settings().get("/nvindex/compositeRenderingMode"):
IndexCompositeSettingsFrame("NVIDIA IndeX Compositing", parent=self)
# MaterialFlattenerSettingsFrame("Material Flattener", parent=self)
DebugViewSettingsFrame("Debug View", parent=self)
| 36,215 | Python | 69.459144 | 302 | 0.638133 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/post_widgets.py | import omni.kit.app
import omni.ui as ui
from omni.kit.widget.settings import SettingType
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
import carb.settings
class ToneMappingSettingsFrame(SettingsCollectionFrame):
""" Tone Mapping """
def _on_tonemap_change(self, *_):
self._rebuild()
def _build_ui(self):
# The main tonemapping layout contains only the combo box. All the other options
# are saved in a different layout which can be swapped out in case the tonemapper changes.
tonemapper_ops = [
"Clamp",
"Linear (Off)",
"Reinhard",
"Modified Reinhard",
"HejlHableAlu",
"HableUc2",
"Aces",
"Iray",
]
self._add_setting_combo("Tone Mapping Operator", "/rtx/post/tonemap/op", tonemapper_ops,
tooltip="\nTone Mapping Operator selector."
"\n-Clamp: Leaves the radiance values unchanged, skipping any exposure adjustment."
"\n-Linear (Off): Applies the exposure adjustments but leaves the tone values otherwise unchanged."
"\n-Reinhard: Operator based on Erik Reinhard's tone mapping work."
"\n-Modified Reinhard: Variation of the operator based on Erik Reinhard's tone mapping work."
"\n-HejiHableAlu: John Hable's ALU approximation of Jim Heji's operator."
"\n-HableUC2: John Hable's Uncharted 2 filmic tone map."
"\n-ACES: Operator based on the Academy Color Encoding System."
"\n-Iray: Reinhard-based operator that matches the operator used by NVIDIA Iray by default.")
tonemapOpIdx = self._settings.get("/rtx/post/tonemap/op")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/tonemap/op", self._on_change)
if tonemapOpIdx == 3: # Modified Reinhard
self._add_setting(SettingType.FLOAT, " Max White Luminance", "/rtx/post/tonemap/maxWhiteLuminance", 0, 100, tooltip="\nMaximum HDR luminance value that will map to 1.0 post tonemap.")
if tonemapOpIdx == 5: # HableUc2
self._add_setting(SettingType.FLOAT, " White Scale Value", "/rtx/post/tonemap/whiteScale", 0, 100, tooltip="\nMaximum white value that will map to 1.0 post tonemap.")
if tonemapOpIdx == 7: # Iray
self._add_setting(SettingType.FLOAT, " Crush Blacks", "/rtx/post/tonemap/irayReinhard/crushBlacks", 0, 1, 0.02)
self._add_setting(SettingType.FLOAT, " Burn Highlights", "/rtx/post/tonemap/irayReinhard/burnHighlights", 0, 1, 0.02)
self._add_setting(SettingType.BOOL, " Burn Highlights per Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsPerComponent")
self._add_setting(SettingType.BOOL, " Burn Highlights max Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsMaxComponent")
self._add_setting(SettingType.FLOAT, " Saturation", "/rtx/post/tonemap/irayReinhard/saturation", 0, 1, 0.02)
if tonemapOpIdx != 0: # Clamp is never using srgb conversion
self._add_setting(SettingType.BOOL, " SRGB To Gamma Conversion", "/rtx/post/tonemap/enableSrgbToGamma", tooltip="\nAvailable with Linear/Reinhard/Modified Reinhard/HejiHableAlu/HableUc2 Tone Mapping.")
self._add_setting(SettingType.FLOAT, "cm^2 Factor", "/rtx/post/tonemap/cm2Factor", 0, 2, tooltip="\nUse this factor to adjust for scene units being different from centimeters.")
self._add_setting(SettingType.FLOAT, "Film ISO", "/rtx/post/tonemap/filmIso", 50, 1600, tooltip="\nSimulates the effect on exposure of a camera's ISO setting.")
self._add_setting(SettingType.FLOAT, "Camera Shutter", "/rtx/post/tonemap/cameraShutter", 1, 5000, tooltip="\nSimulates the effect on exposure of a camera's shutter open time.")
self._add_setting(SettingType.FLOAT, "F-stop", "/rtx/post/tonemap/fNumber", 1, 20, 0.1, tooltip="\nSimulates the effect on exposure of a camera's f-stop aperture.")
self._add_setting(SettingType.COLOR3, "White Point", "/rtx/post/tonemap/whitepoint", tooltip="\nA color mapped to white on the output.")
tonemapColorMode = ["sRGBLinear", "ACEScg"]
self._add_setting_combo("Tone Mapping Color Space", "/rtx/post/tonemap/colorMode", tonemapColorMode, tooltip="\nTone Mapping Color Space selector.")
self._add_setting(SettingType.FLOAT, "Wrap Value", "/rtx/post/tonemap/wrapValue", 0, 100000, tooltip="\nOffset")
self._add_setting(SettingType.FLOAT, "Dither strength", "/rtx/post/tonemap/dither", 0, .02, .001, tooltip="\nRemoves banding artifacts in final images.")
def destroy(self):
self._change_cb = None
super().destroy()
class AutoExposureSettingsFrame(SettingsCollectionFrame):
""" Auto Exposure """
def _frame_setting_path(self):
return "/rtx/post/histogram/enabled"
def _build_ui(self):
histFilter_types = ["Median", "Average"]
self._add_setting_combo("Histogram Filter", "/rtx/post/histogram/filterType", histFilter_types, tooltip="\nSelect a method to filter the histogram. Options are Median and Average.")
self._add_setting(SettingType.FLOAT, "Adaptation Speed", "/rtx/post/histogram/tau", 0.5, 10.0, 0.01, tooltip="\nHow fast automatic exposure compensation adapts to changes in overall light intensity.")
self._add_setting(SettingType.FLOAT, "White Point Scale", "/rtx/post/histogram/whiteScale", 0.01, 80.0, 0.001,
tooltip="\nControls how bright of an image the auto-exposure should aim for."
"\nLower values result in brighter images, higher values result in darker images.")
self._add_setting(SettingType.BOOL, "Exposure Value Clamping", "/rtx/post/histogram/useExposureClamping", tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/histogram/useExposureClamping", self._on_change)
if self._settings.get("/rtx/post/histogram/useExposureClamping"):
self._add_setting(SettingType.FLOAT, " Minimum Value", "/rtx/post/histogram/minEV", 0.0, 1000000.0, 1, tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.")
self._add_setting(SettingType.FLOAT, " Maximum Value", "/rtx/post/histogram/maxEV", 0.0, 1000000.0, 1, tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.")
# self._add_setting(SettingType.FLOAT, "Min Log Luminance", "/rtx/post/histogram/minloglum", -15, 5.0, 0.001)
# self._add_setting(SettingType.FLOAT, "Log Luminance Range", "/rtx/post/histogram/loglumrange", 0.00001, 50.0, 0.001)
def destroy(self):
self._change_cb = None
super().destroy()
class ColorCorrectionSettingsFrame(SettingsCollectionFrame):
""" Color Correction """
def _frame_setting_path(self):
return "/rtx/post/colorcorr/enabled"
def _on_colorcorrect_change(self, *_):
self._rebuild()
def _build_ui(self):
mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"]
self._add_setting_combo("Mode", "/rtx/post/colorcorr/mode", mode, tooltip="\nChoose between ACES (Pre-Tone mapping) or Standard (Post-Tone mapping) mode.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/colorcorr/mode", self._on_change)
colorCorrectionMode = ["sRGBLinear", "ACEScg"]
if self._settings.get("/rtx/post/colorcorr/mode") == 0:
self._add_setting_combo(" Output Color Space", "/rtx/post/colorcorr/outputMode", colorCorrectionMode,
tooltip="\nDefines the color space used as output of Color Correction."
"\nsRGB Linear: scene linear space"
"\nAcesCG: ACES CG color space")
self._add_setting(SettingType.COLOR3, "Saturation", "/rtx/post/colorcorr/saturation", tooltip="\nHigher values increase color saturation while lowering desaturates.")
self._add_setting(SettingType.COLOR3, "Contrast", "/rtx/post/colorcorr/contrast", 0, 10, 0.005, tooltip="\nHigher values increase the contrast of darks/lights and colors.")
self._add_setting(SettingType.COLOR3, "Gamma", "/rtx/post/colorcorr/gamma", 0.2, 10, 0.005, tooltip="\nGamma value in inverse gamma curve applied before output.")
self._add_setting(SettingType.COLOR3, "Gain", "/rtx/post/colorcorr/gain", 0, 10, 0.005, tooltip="\nA factor applied to the color values.")
self._add_setting(SettingType.COLOR3, "Offset", "/rtx/post/colorcorr/offset", -1, 1, 0.001, tooltip="\nAn offset applied to the color values.")
def destroy(self):
self._change_cb = None
super().destroy()
class ColorGradingSettingsFrame(SettingsCollectionFrame):
""" Color Grading """
def _frame_setting_path(self):
return "/rtx/post/colorgrad/enabled"
def _on_colorgrade_change(self, *_):
self._rebuild()
def _build_ui(self):
mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"]
self._add_setting_combo("Mode", "/rtx/post/colorgrad/mode", mode, tooltip="\nChoose between ACES (Pre-Tonemap) or Standard (Post-Tonemap) Mode.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/colorgrad/mode", self._on_change)
colorGradingMode = ["sRGBLinear", "ACEScg"]
if self._settings.get("/rtx/post/colorgrad/mode") == 0:
self._add_setting_combo(" Output Color Space", "/rtx/post/colorgrad/outputMode", colorGradingMode,
tooltip="\nChoose between ACES (Pre-Tonemap) or Standard (Post-Tonemap) Mode."
"\nsRGB Linear: scene linear space"
"\nAcesCG: ACES CG color space")
self._add_setting(SettingType.COLOR3, "Black Point", "/rtx/post/colorgrad/blackpoint", -1, 1, 0.005, tooltip="\nDefines the Black Point value.")
self._add_setting(SettingType.COLOR3, "White Point", "/rtx/post/colorgrad/whitepoint", 0, 10, 0.005, tooltip="\nDefines the White Point value.")
self._add_setting(SettingType.COLOR3, "Contrast", "/rtx/post/colorgrad/contrast", 0, 10, 0.005, tooltip="\nHigher values increase the contrast of darks/lights and colors.")
self._add_setting(SettingType.COLOR3, "Lift", "/rtx/post/colorgrad/lift", -10, 10, 0.005, tooltip="\nColor is multiplied by (Lift - Gain) and later Lift is added back.")
self._add_setting(SettingType.COLOR3, "Gain", "/rtx/post/colorgrad/gain", 0, 10, 0.005, tooltip="\nColor is multiplied by (Lift - Gain) and later Lift is added back.")
self._add_setting(SettingType.COLOR3, "Multiply", "/rtx/post/colorgrad/multiply", 0, 10, 0.005, tooltip="\nA factor applied to the color values.")
self._add_setting(SettingType.COLOR3, "Offset", "/rtx/post/colorgrad/offset", -1, 1, 0.001, tooltip="\nColor offset: an offset applied to the color values.")
self._add_setting(SettingType.COLOR3, "Gamma", "/rtx/post/colorgrad/gamma", 0.2, 10, 0.005, tooltip="\nGamma value in inverse gamma curve applied before output.")
def destroy(self):
self._change_cb = None
super().destroy()
class MatteObjectSettingsFrame(SettingsCollectionFrame):
def _frame_setting_path(self):
return "/rtx/matteObject/enabled"
def _build_ui(self):
self._add_setting(SettingType.COLOR3, "Backplate Color", "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor", tooltip="\nA constant color used if no backplate texture is set.")
self._add_setting("ASSET", "Backplate Texture", "/rtx/post/backgroundZeroAlpha/backplateTexture", tooltip="\nThe path to a texture to use as a backplate.")
self._add_setting(SettingType.BOOL, "Shadow Catcher", "/rtx/post/matteObject/enableShadowCatcher",
tooltip="\Treats all matte objects as shadow catchers. Matte objects receives only shadow and"
"\nnot reflections or GI which improves rendering performance." )
class XRCompositingSettingsFrame(SettingsCollectionFrame):
def _frame_setting_path(self):
return "/rtx/post/backgroundZeroAlpha/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Composite in Editor", "/rtx/post/backgroundZeroAlpha/backgroundComposite",
tooltip="\nEnables alpha compositing with a backplate texture, instead of"
"\noutputting the rendered image with an alpha channel for compositing externally,"
"\nby saving to EXR images.")
self._add_setting(SettingType.BOOL, "Output Alpha in Composited Image", "/rtx/post/backgroundZeroAlpha/outputAlphaInComposite",
tooltip="\nOutputs the matte compositing alpha in the composited image."
"\nOnly activates when not compositing in editor."
"\nThis option can interfere with DLSS, producing jaggied edges.")
self._add_setting(SettingType.BOOL, "Output Black Background in Composited Image", "/rtx/post/backgroundZeroAlpha/blackBackgroundInComposite",
tooltip="\nOutputs a black background in the composited image, for XR compositing."
"\nOnly activates when not compositing in editor.")
self._add_setting(SettingType.BOOL, "Multiply color value by alpha in Composited Image", "/rtx/post/backgroundZeroAlpha/premultiplyColorByAlpha",
tooltip="\nWhen enabled, the RGB color will be RGB * alpha.")
self._add_setting(SettingType.COLOR3, "Backplate Color", "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor", tooltip="\nA constant color used if no backplate texture is set.")
self._add_setting("ASSET", "Backplate Texture", "/rtx/post/backgroundZeroAlpha/backplateTexture", tooltip="\nThe path to a texture to use as a backplate.")
self._add_setting(SettingType.BOOL, " Is linear", "/rtx/post/backgroundZeroAlpha/backplateTextureIsLinear", tooltip="\nSets the color space for the Backplate Texture to linear space.")
self._add_setting(SettingType.FLOAT, "Backplate Luminance Scale", "/rtx/post/backgroundZeroAlpha/backplateLuminanceScaleV2", tooltip="\nScales the Backplate Texture/Color luminance.")
self._add_setting(SettingType.BOOL, "Lens Distortion", "/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection",
tooltip="\nEnables distortion of the rendered image using a set of lens distortion and undistortion maps."
"\nEach of these should refer to a <UDIM> EXR texture set, containing one image for each"
"\nof the discrete focal length values specified in the array of float settings under"
"\n/rtx/post/lensDistortion/lensFocalLengthArray (not currently exposed).")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection", self._on_change)
if self._settings.get("/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection"):
self._add_setting("ASSET", " Distortion Map", "/rtx/post/lensDistortion/distortionMap", tooltip="\n<UDIM> EXR texture path to store the distortion maps for specified focal lengths.")
self._add_setting("ASSET", " Undistortion Map", "/rtx/post/lensDistortion/undistortionMap", tooltip="\n<UDIM> EXR texture path to store the un-distortion maps for specified focal lengths.")
def destroy(self):
self._change_cb = None
super().destroy()
class ChromaticAberrationSettingsFrame(SettingsCollectionFrame):
""" Chromatic Aberration """
def _frame_setting_path(self):
return "/rtx/post/chromaticAberration/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Strength Red", "/rtx/post/chromaticAberration/strengthR", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Red channel.")
self._add_setting(SettingType.FLOAT, "Strength Green", "/rtx/post/chromaticAberration/strengthG", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Green channel.")
self._add_setting(SettingType.FLOAT, "Strength Blue", "/rtx/post/chromaticAberration/strengthB", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Blue channel.")
chromatic_aberration_ops = ["Radial", "Barrel"]
self._add_setting_combo("Algorithm Red", "/rtx/post/chromaticAberration/modeR", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Red channel.")
self._add_setting_combo("Algorithm Green", "/rtx/post/chromaticAberration/modeG", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Green channel.")
self._add_setting_combo("Algorithm Blue", "/rtx/post/chromaticAberration/modeB", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Blue channel.")
self._add_setting(SettingType.BOOL, "Use Lanczos Sampler", "/rtx/post/chromaticAberration/enableLanczos", tooltip="\nUse a Lanczos sampler when sampling the input image being distorted.")
with ui.CollapsableFrame("Boundary Blending", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Repeat Mirrored", "/rtx/post/chromaticAberration/mirroredRepeat", tooltip="\nEnables mirror repeat for texture lookups in out-of-lens regions. When disabled, out-of-lens regions are black.")
self._add_setting(SettingType.FLOAT, "Blend Region Size", "/rtx/post/chromaticAberration/boundaryBlendRegionSize", 0.0, 1.0, 0.01, tooltip="\nDetermines the blend region size.")
self._add_setting(SettingType.FLOAT, "Blend Region Falloff", "/rtx/post/chromaticAberration/boundaryBlendFalloff", 0.001, 5.0, 0.001, tooltip="\nDetermines the falloff in the blending region.")
class DepthOfFieldSettingsFrame(SettingsCollectionFrame):
""" Depth of Field Camera Overrides """
def _frame_setting_path(self):
return "/rtx/post/dof/overrideEnabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Enable DOF", "/rtx/post/dof/enabled", tooltip="\nEnables Depth of Field. If disabled, camera parameters affecting Depth of Field are ignored.")
self._add_setting(SettingType.FLOAT, "Subject Distance", "/rtx/post/dof/subjectDistance", -10000, 10000.0, tooltip="\nObjects at this distance from the camera will be in focus.")
self._add_setting(SettingType.FLOAT, "Focal Length (mm)", "/rtx/post/dof/focalLength", 0, 1000, tooltip="\nThe focal length of the lens (in mm). The focal length divided by the f-stop is the aperture diameter.")
self._add_setting(SettingType.FLOAT, "F-stop", "/rtx/post/dof/fNumber", 0, 1000, tooltip="\nF-stop (aperture) of the lens. Lower f-stop numbers decrease the distance range from the Subject Distance where objects remain in focus.")
self._add_setting(SettingType.FLOAT, "Anisotropy", "/rtx/post/dof/anisotropy", -1, 1, 0.01, tooltip="\nAnisotropy of the lens. A value of -0.5 simulates the depth of field of an anamorphic lens.")
class MotionBlurSettingsFrame(SettingsCollectionFrame):
""" Motion Blur """
def _frame_setting_path(self):
return "/rtx/post/motionblur/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Blur Diameter Fraction", "/rtx/post/motionblur/maxBlurDiameterFraction", 0, 0.5, 0.01, tooltip="\nThe fraction of the largest screen dimension to use as the maximum motion blur diameter.")
self._add_setting(SettingType.FLOAT, "Exposure Fraction", "/rtx/post/motionblur/exposureFraction", 0, 5.0, 0.01, tooltip="\nExposure time fraction in frames (1.0 = one frame duration) to sample.")
self._add_setting(SettingType.INT, "Number of Samples", "/rtx/post/motionblur/numSamples", 4, 32, 1, tooltip="\nNumber of samples to use in the filter. A higher number improves quality at the cost of performance.")
class FFTBloomSettingsFrame(SettingsCollectionFrame):
""" FFT Bloom """
def _frame_setting_path(self):
return "/rtx/post/lensFlares/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Scale", "/rtx/post/lensFlares/flareScale", -1000, 1000, tooltip="\nOverall intensity of the bloom effect.")
self._add_setting(SettingType.DOUBLE3, "Cutoff Point", "/rtx/post/lensFlares/cutoffPoint", tooltip="\nA cutoff color value to tune the radiance range for which Bloom will have any effect. ")
self._add_setting(SettingType.FLOAT, "Cutoff Fuzziness", "/rtx/post/lensFlares/cutoffFuzziness", 0.0, 1.0,
tooltip="\nIf greater than 0, defines the width of a 'fuzzy cutoff' region around the Cutoff Point values."
"\nInstead of a sharp cutoff, a smooth transition between 0 and the original values is used.")
self._add_setting(SettingType.FLOAT, "Alpha channel scale", "/rtx/post/lensFlares/alphaExposureScale", 0.0, 100.0, tooltip="\nAlpha channel intensity of the bloom effect.")
self._add_setting(SettingType.BOOL, "Energy Constrained", "/rtx/post/lensFlares/energyConstrainingBlend", tooltip="\nConstrains the total light energy generated by bloom.")
self._add_setting(SettingType.BOOL, "Physical Model", "/rtx/post/lensFlares/physicalSettings", tooltip="\nChoose between a Physical or Non-Physical bloom model.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/lensFlares/physicalSettings", self._on_change)
if self._settings.get("/rtx/post/lensFlares/physicalSettings") == 1:
self._add_setting(SettingType.INT, " Blades", "/rtx/post/lensFlares/blades", 0, 10, tooltip="\nThe number of physical blades of a simulated camera diaphragm causing the bloom effect.")
self._add_setting(SettingType.FLOAT, " Aperture Rotation", "/rtx/post/lensFlares/apertureRotation", -1000, 1000, tooltip="\nRotation of the camera diaphragm.")
self._add_setting(SettingType.FLOAT, " Sensor Diagonal", "/rtx/post/lensFlares/sensorDiagonal", -1000, 1000, tooltip="\nDiagonal of the simulated sensor.")
self._add_setting(SettingType.FLOAT, " Sensor Aspect Ratio", "/rtx/post/lensFlares/sensorAspectRatio", -1000, 1000, tooltip="\nAspect ratio of the simulated sensor, results in the bloom effect stretching in one direction.")
self._add_setting(SettingType.FLOAT, " F-stop", "/rtx/post/lensFlares/fNumber", -1000, 1000, tooltip="\nIncreases/Decreases the sharpness of the bloom effect.")
self._add_setting(SettingType.FLOAT, " Focal Length (mm)", "/rtx/post/lensFlares/focalLength", -1000, 1000, tooltip="\nFocal length of the lens modeled to simulate the bloom effect.")
else:
self._add_setting(SettingType.DOUBLE3, " Halo Radius", "/rtx/post/lensFlares/haloFlareRadius", tooltip="\nControls the size of each RGB component of the halo flare effect.")
self._add_setting(SettingType.DOUBLE3, " Halo Flare Falloff", "/rtx/post/lensFlares/haloFlareFalloff", tooltip="\nControls the falloff of each RGB component of the halo flare effect.")
self._add_setting(SettingType.FLOAT, " Halo Flare Weight", "/rtx/post/lensFlares/haloFlareWeight", -1000, 1000, tooltip="\nControls the intensity of the halo flare effect.")
self._add_setting(SettingType.DOUBLE3, " Aniso Falloff Y", "/rtx/post/lensFlares/anisoFlareFalloffY", tooltip="\nControls the falloff of each RGB component of the anistropic flare effect in the X direction.")
self._add_setting(SettingType.DOUBLE3, " Aniso Falloff X", "/rtx/post/lensFlares/anisoFlareFalloffX", tooltip="\nControls the falloff of each RGB component of the anistropic flare effect in the Y direction.")
self._add_setting(SettingType.FLOAT, " Aniso Flare Weight", "/rtx/post/lensFlares/anisoFlareWeight", -1000, 1000, tooltip="\nControl the intensity of the anisotropic flare effect.")
self._add_setting(SettingType.DOUBLE3, " Isotropic Flare Falloff", "/rtx/post/lensFlares/isotropicFlareFalloff", tooltip="\nControls the falloff of each RGB component of the isotropic flare effect.")
self._add_setting(SettingType.FLOAT, " Isotropic Flare Weight", "/rtx/post/lensFlares/isotropicFlareWeight", -1000, 1000, tooltip="\nControl the intensity of the isotropic flare effect.")
def destroy(self):
self._change_cb = None
super().destroy()
class TVNoiseGrainSettingsFrame(SettingsCollectionFrame):
""" TV Noise | Film Grain """
def _frame_setting_path(self):
return "/rtx/post/tvNoise/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Enable Scanlines", "/rtx/post/tvNoise/enableScanlines", tooltip="\nEmulates a Scanline Distortion typical of old televisions.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableScanlines", self._on_change)
if self._settings.get("/rtx/post/tvNoise/enableScanlines"):
self._add_setting(SettingType.FLOAT, " Scanline Spreading", "/rtx/post/tvNoise/scanlineSpread", 0.0, 2.0, 0.01, tooltip="\nHow wide the Scanline distortion will be.")
self._add_setting(SettingType.BOOL, "Enable Scroll Bug", "/rtx/post/tvNoise/enableScrollBug", tooltip="\nEmulates sliding typical on old televisions.")
self._add_setting(SettingType.BOOL, "Enable Vignetting", "/rtx/post/tvNoise/enableVignetting", tooltip="\nBlurred darkening around the screen edges.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableVignetting", self._on_change)
if self._settings.get("/rtx/post/tvNoise/enableVignetting"):
self._add_setting(SettingType.FLOAT, " Vignetting Size", "/rtx/post/tvNoise/vignettingSize", 0.0, 255, tooltip="\nControls the size of vignette region.")
self._add_setting(SettingType.FLOAT, " Vignetting Strength", "/rtx/post/tvNoise/vignettingStrength", 0.0, 2.0, 0.01, tooltip="\nControls the intensity of the vignette.")
self._add_setting(SettingType.BOOL, " Enable Vignetting Flickering", "/rtx/post/tvNoise/enableVignettingFlickering", tooltip="\nEnables a slight flicker effect on the vignette.")
self._add_setting(SettingType.BOOL, "Enable Ghost Flickering", "/rtx/post/tvNoise/enableGhostFlickering", tooltip="\nIntroduces a blurred flicker to help emulate an old television.")
self._add_setting(SettingType.BOOL, "Enable Wavy Distortion", "/rtx/post/tvNoise/enableWaveDistortion", tooltip="\nIntroduces a Random Wave Flicker to emulate an old television.")
self._add_setting(SettingType.BOOL, "Enable Vertical Lines", "/rtx/post/tvNoise/enableVerticalLines", tooltip="\nIntroduces random vertical lines to emulate an old television.")
self._add_setting(SettingType.BOOL, "Enable Random Splotches", "/rtx/post/tvNoise/enableRandomSplotches", tooltip="\nIntroduces random splotches typical of old dirty television.")
self._add_setting(SettingType.BOOL, "Enable Film Grain", "/rtx/post/tvNoise/enableFilmGrain", tooltip="\nEnables a film grain effect to emulate the graininess in high speed (ISO) film.")
# Filmgrain is a subframe in TV Noise
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableFilmGrain", self._on_change)
if self._settings.get("/rtx/post/tvNoise/enableFilmGrain"):
self._add_setting(SettingType.FLOAT, " Grain Amount", "/rtx/post/tvNoise/grainAmount", 0, 0.2, 0.002, tooltip="\nThe intensity of the film grain effect.")
self._add_setting(SettingType.FLOAT, " Color Amount", "/rtx/post/tvNoise/colorAmount", 0, 1.0, 0.02, tooltip="\nThe amount of color offset each grain will be allowed to use.")
self._add_setting(SettingType.FLOAT, " Luminance Amount", "/rtx/post/tvNoise/lumAmount", 0, 1.0, 0.02, tooltip="\nThe amount of offset in luminance each grain will be allowed to use.")
self._add_setting(SettingType.FLOAT, " Grain Size", "/rtx/post/tvNoise/grainSize", 1.5, 2.5, 0.02, tooltip="\nThe size of the film grains.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
super().destroy()
class ReshadeSettingsFrame(SettingsCollectionFrame):
""" ReShade """
def _frame_setting_path(self):
return "/rtx/reshade/enable"
def _build_ui(self):
self._add_setting("ASSET", "Preset File Path", "/rtx/reshade/presetFilePath", tooltip="\nThe path to a preset.init file containing the Reshade preset to use.")
widget = self._add_setting("ASSET", "Effect search dir path", "/rtx/reshade/effectSearchDirPath", tooltip="\nThe path to a directory containing the Reshade files that the preset can reference.")
widget.is_folder=True
widget = self._add_setting("ASSET", "Texture search dir path", "/rtx/reshade/textureSearchDirPath", tooltip="\nThe path to a directory containing the Reshade texture files that the preset can reference.")
widget.is_folder=True
class PostSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
ToneMappingSettingsFrame("Tone Mapping", parent=self)
AutoExposureSettingsFrame("Auto Exposure", parent=self)
ColorCorrectionSettingsFrame("Color Correction", parent=self)
ColorGradingSettingsFrame("Color Grading", parent=self)
XRCompositingSettingsFrame("XR Compositing", parent=self)
MatteObjectSettingsFrame("Matte Object", parent=self)
ChromaticAberrationSettingsFrame("Chromatic Aberration", parent=self)
DepthOfFieldSettingsFrame("Depth of Field Camera Overrides", parent=self)
MotionBlurSettingsFrame("Motion Blur", parent=self)
FFTBloomSettingsFrame("FFT Bloom", parent=self)
TVNoiseGrainSettingsFrame("TV Noise & Film Grain", parent=self)
ReshadeSettingsFrame("ReShade", parent=self)
ui.Spacer()
| 30,479 | Python | 84.617977 | 243 | 0.696578 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/pt_widgets.py | import omni.ui as ui
import omni.kit.app
import carb.settings
import math
from omni.kit.widget.settings import SettingType
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
class AntiAliasingSettingsFrame(SettingsCollectionFrame):
""" Anti-Aliasing """
def _build_ui(self):
pt_aa_ops = ["Box", "Triangle", "Gaussian", "Uniform"]
self._add_setting_combo("Anti-Aliasing Sample Pattern", "/rtx/pathtracing/aa/op", pt_aa_ops, tooltip="\nSampling pattern used for Anti-Aliasing. Select between Box, Triangle, Gaussian and Uniform.")
self._add_setting(SettingType.FLOAT, "Anti-Aliasing Radius", "/rtx/pathtracing/aa/filterRadius", 0.0001, 5.0, 0.001, tooltip="\nSampling footprint radius, in pixels, when generating samples with the selected antialiasing sample pattern.")
class FireflyFilterSettingsFrame(SettingsCollectionFrame):
""" Firefly Filtering """
def _frame_setting_path(self):
return "/rtx/pathtracing/fireflyFilter/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Max Ray Intensity Glossy", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSample", 0, 100000, 100, tooltip="\nClamps the maximium ray intensity for glossy bounces. Can help prevent fireflies, but may result in energy loss.")
self._add_setting(SettingType.FLOAT, "Max Ray Intensity Diffuse", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSampleDiffuse", 0, 100000, 100, tooltip="\nClamps the maximium ray intensity for diffuse bounces. Can help prevent fireflies, but may result in energy loss.")
class PathTracingSettingsFrame(SettingsCollectionFrame):
""" Path-Tracing """
def _build_ui(self):
clampSpp = self._settings.get("/rtx/pathtracing/clampSpp")
if clampSpp is not None and clampSpp > 1: # better 0, but setting range = (1,1) completely disables the UI control range
self._add_setting(SettingType.INT, "Samples per Pixel per Frame(1 to {})".format(clampSpp), "/rtx/pathtracing/spp", 1, clampSpp, tooltip="\nTotal number of samples for each rendered pixel, per frame.")
else:
self._add_setting(SettingType.INT, "Samples per Pixel per Frame", "/rtx/pathtracing/spp", 1, 1048576, tooltip="\nTotal number of samples for each rendered pixel, per frame.")
self._add_setting(SettingType.INT, "Total Samples per Pixel (0 = inf)", "/rtx/pathtracing/totalSpp", 0, 100000,
tooltip="\nMaximum number of samples to accumulate per pixel. When this count is reached the rendering stops until"
"\na scene or setting change is detected, restarting the rendering process. Set to 0 to remove this limit.")
self._add_setting(SettingType.BOOL, "Adaptive Sampling", "/rtx/pathtracing/adaptiveSampling/enabled", tooltip="\nWhen enabled, noise values are computed for each pixel, and upon threshold level eached, the pixel is no longer sampled")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/adaptiveSampling/enabled", self._on_change)
if self._settings.get("/rtx/pathtracing/adaptiveSampling/enabled"):
self._add_setting(SettingType.FLOAT, " Target Error", "/rtx/pathtracing/adaptiveSampling/targetError", 0.00001, 1, tooltip="\nThe noise value treshold after which the pixel would no longer be sampled.")
ui.Line()
self._add_setting(SettingType.INT, "Max Bounces", "/rtx/pathtracing/maxBounces", 0, 64, tooltip="\nMaximum number of ray bounces for any ray type. Higher values give more accurate results, but worse performance.")
self._add_setting(SettingType.INT, "Max Specular and Transmission Bounces", "/rtx/pathtracing/maxSpecularAndTransmissionBounces", 1, 128, tooltip="\nMaximum number of ray bounces for specular and trasnimission.")
self._add_setting(SettingType.INT, "Max SSS Volume Scattering Bounces", "/rtx/pathtracing/maxVolumeBounces", 0, 1024, tooltip="\nMaximum number of ray bounces for SSS.")
self._add_setting(SettingType.INT, "Max Fog Scattering Bounces", "/rtx/pathtracing/ptfog/maxBounces", 1, 10, tooltip="\nMaximum number of bounces for volume scattering within a fog/sky volume.")
# self._add_setting(SettingType.BOOL, "Dome Lights: High Quality Primary Rays", "/rtx/pathtracing/domeLight/primaryRaysEvaluateDomelightMdlDirectly")
ui.Line()
# self._add_setting(SettingType.BOOL, "Show Lights", "/rtx/pathtracing/showLights/enabled") # depreacted, use /rtx/raytracing/showLights instead
self._add_setting(SettingType.BOOL, "Fractional Cutout Opacity", "/rtx/pathtracing/fractionalCutoutOpacity",
tooltip="\nIf enabled, fractional cutout opacity values are treated as a measure of surface 'presence',"
"\nresulting in a translucency effect similar to alpha-blending. Path-traced mode uses stochastic"
"\nsampling based on these values to determine whether a surface hit is valid or should be skipped.")
self._add_setting(SettingType.BOOL, "Reset Accumulation on Time Change", "/rtx/resetPtAccumOnAnimTimeChange",
tooltip="\nIf enabled, rendering is restarted every time the MDL animation time changes.")
def destroy(self):
self._change_cb = None
super().destroy()
class SamplingAndCachingSettingsFrame(SettingsCollectionFrame):
""" Sampling & Caching """
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Caching", "/rtx/pathtracing/cached/enabled", tooltip="\nEnables caching path-tracing results for improved performance at the cost of some accuracy.")
self._add_setting(SettingType.BOOL, "Many-Light Sampling", "/rtx/pathtracing/lightcache/cached/enabled",
tooltip="\nEnables many-light sampling algorithm, resulting in faster rendering of scenes with many lights."
"\nThis should generally be always enabled, and is exposed as an option for debugging potential algorithm artifacts.")
self._add_setting(SettingType.BOOL, "Mesh-Light Sampling", "/rtx/pathtracing/ris/meshLights", tooltip="\nEnables direct illumination sampling of geometry with emissive materials.")
# ui.Label("Neural Radiance Caching does not work on Multi-GPU and requires (spp=1)", alignment=ui.Alignment.CENTER)
# self._add_setting(SettingType.BOOL, "Enable Neural Radiance Cache (Experimental)", "/rtx/pathtracing/nrc/enabled")
class DenoisingSettingsFrame(SettingsCollectionFrame):
""" Denoising """
def _frame_setting_path(self):
return "/rtx/pathtracing/optixDenoiser/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "OptiX Denoiser Blend Factor", "/rtx/pathtracing/optixDenoiser/blendFactor", 0, 1, 0.001,
tooltip="\nA blend factor indicating how much to blend the denoised image with the original non-denoised image."
"\n0 shows only the denoised image, 1.0 shows the image with no denoising applied.")
self._add_setting(SettingType.BOOL, "Denoise AOVs", "/rtx/pathtracing/optixDenoiser/AOV", tooltip="\nIf enabled, the OptiX Denoiser will also denoise the AOVs.")
class NonUniformVolumesSettingsFrame(SettingsCollectionFrame):
""" Path-Traced Volume """
def _frame_setting_path(self):
return "/rtx/pathtracing/ptvol/enabled"
def _build_ui(self):
""" Path-Traced Volume """
pt_vol_tr_ops = ["Biased Ray Marching", "Ratio Tracking"]
self._add_setting_combo("Transmittance Method", "/rtx/pathtracing/ptvol/transmittanceMethod", pt_vol_tr_ops, tooltip="\nChoose between Biased Ray Marching or Ratio Tracking. Biased ray marching is the ideal option in all cases.")
self._add_setting(SettingType.INT, "Max Ray Steps (Scattering)", "/rtx/pathtracing/ptvol/maxCollisionCount", 0, 1024, 32, tooltip="\nMaximum delta tracking steps between bounces. Increase to more than 32 for highly scattering volumes like clouds.")
self._add_setting(SettingType.INT, "Max Ray Steps (Shadow)", "/rtx/pathtracing/ptvol/maxLightCollisionCount", 0, 1024, 16, tooltip="\nMaximum ratio tracking delta steps for shadow rays. Increase to more than 32 for highly scattering volumes like clouds.")
self._add_setting(SettingType.INT, "Max Non-uniform Volume Scattering Bounces", "/rtx/pathtracing/ptvol/maxBounces", 1, 1024, 1, tooltip="\nMaximum number of bounces in non-uniform volumes.")
class AOVSettingsFrame(SettingsCollectionFrame):
""" AOV Settings"""
def _build_ui(self):
""" AOV Settings """
self._add_setting(SettingType.FLOAT, "Minimum Z-Depth", "/rtx/pathtracing/zDepthMin", 0, 10000, 1)
self._add_setting(SettingType.FLOAT, "Maximum Z-Depth", "/rtx/pathtracing/zDepthMax", 0, 10000, 1)
self._add_setting(SettingType.BOOL, "32 Bit Depth AOV", "/rtx/pathtracing/depth32BitAov", tooltip="\nUses a 32-bit format for the depth AOV")
ui.Label("Enables AOV Preview in Debug View", alignment=ui.Alignment.CENTER)
self._add_setting(SettingType.BOOL, "Background", "/rtx/pathtracing/backgroundAOV", tooltip="\nShading of the background, such as the background resulting from rendering a Dome Light.")
self._add_setting(SettingType.BOOL, "Diffuse Filter", "/rtx/pathtracing/diffuseFilterAOV", tooltip="\nThe raw color of the diffuse texture.")
self._add_setting(SettingType.BOOL, "Direct Illumation", "/rtx/pathtracing/diAOV", tooltip="\nShading from direct paths to light sources.")
self._add_setting(SettingType.BOOL, "Global Illumination", "/rtx/pathtracing/giAOV", tooltip="\nDiffuse shading from indirect paths to light sources.")
self._add_setting(SettingType.BOOL, "Reflection", "/rtx/pathtracing/reflectionsAOV", tooltip="\nShading from indirect reflection paths to light sources.")
self._add_setting(SettingType.BOOL, "Reflection Filter", "/rtx/pathtracing/reflectionFilterAOV", tooltip="\nThe raw color of the reflection, before being multiplied for its final intensity.")
self._add_setting(SettingType.BOOL, "Refraction", "/rtx/pathtracing/refractionsAOV", tooltip="\nShading from refraction paths to light sources.")
self._add_setting(SettingType.BOOL, "Refraction Filter", "/rtx/pathtracing/refractionFilterAOV", tooltip="\nThe raw color of the refraction, before being multiplied for its final intensity.")
self._add_setting(SettingType.BOOL, "Self-Illumination", "/rtx/pathtracing/selfIllumAOV", tooltip="\nShading of the surface's own emission value.")
self._add_setting(SettingType.BOOL, "Volumes", "/rtx/pathtracing/volumesAOV", tooltip="\nShading from VDB volumes.")
self._add_setting(SettingType.BOOL, "World Normal", "/rtx/pathtracing/worldNormalsAOV", tooltip="\nThe surface's normal in world-space.")
self._add_setting(SettingType.BOOL, "World Position", "/rtx/pathtracing/worldPosAOV", tooltip="\nThe surface's position in world-space.")
self._add_setting(SettingType.BOOL, "Z-Depth", "/rtx/pathtracing/zDepthAOV", tooltip="\nThe surface's depth relative to the view position.")
class MultiMatteSettingsFrame(SettingsCollectionFrame):
def _on_multimatte_change(self, *_):
self._rebuild()
def _build_ui(self):
self._add_setting(SettingType.INT, "Channel Count:", "/rtx/pathtracing/multimatte/channelCount", 0, 24, 1,
tooltip="\nMultimatte allows rendering AOVs of meshes which have a Multimatte ID index matching a Multimatte AOV's channel index."
"\nChannel Count determines how many channels can be used, which are distributed among the Multimatte AOVs' color channels."
"\nYou can preview a Multimatte AOV by selecting one in the Debug View.")
self._change_channels = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/multimatte/channelCount", self._on_multimatte_change)
def clamp(num, min_value, max_value):
return max(min(num, max_value), min_value)
value = self._settings.get("/rtx/pathtracing/multimatte/channelCount")
channelCount = clamp(self._settings.get("/rtx/pathtracing/multimatte/channelCount"), 0, 24) if value is not None else 0
if channelCount != 0:
mapCount = math.ceil(channelCount / 3)
channelIndex = 0
for i in range(0, mapCount):
ui.Label("Multimatte" + str(i), alignment=ui.Alignment.CENTER)
self._add_setting(SettingType.INT, "Red Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the red channel of this Multimatte AOV.")
channelIndex += 1
if channelIndex >= channelCount:
break
self._add_setting(SettingType.INT, "Green Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the green channel of this Multimatte AOV.")
channelIndex += 1
if channelIndex >= channelCount:
break
self._add_setting(SettingType.INT, "Blue Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the blue channel of this Multimatte AOV.")
channelIndex += 1
if channelIndex >= channelCount:
break
# self._add_setting(SettingType.BOOL, "is material ID " + str(i), "/rtx/pathtracing/multimatte/channel" + str(i) + "_isMat")
def destroy(self):
self._change_channels = None
super().destroy()
class MultiGPUSettingsFrame(SettingsCollectionFrame):
""" Multi-GPU """
def _frame_setting_path(self):
return "/rtx/pathtracing/mgpu/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Auto Load Balancing","/rtx/pathtracing/mgpu/autoLoadBalancing/enabled", tooltip="\nAutomatically balance the amount of total path-tracing work to be performed by each GPU in a multi-GPU configuration.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/mgpu/autoLoadBalancing/enabled", self._on_change)
if not self._settings.get("/rtx/pathtracing/mgpu/autoLoadBalancing/enabled") :
self._add_setting(SettingType.FLOAT, "GPU 0 Weight", "/rtx/pathtracing/mgpu/weightGpu0", 0, 1, 0.001,
tooltip="\nThe amount of total Path-Tracing work (between 0 and 1) to be performed by the first GPU in a Multi-GPU configuration."
"\nA value of 1 means the first GPU will perform the same amount of work assigned to any other GPU.")
self._add_setting(SettingType.BOOL, "Compress Radiance", "/rtx/pathtracing/mgpu/compressRadiance", tooltip="Enables lossy compression of per-pixel output radiance values.")
self._add_setting(SettingType.BOOL, "Compress Albedo", "/rtx/pathtracing/mgpu/compressAlbedo", tooltip="Enables lossy compression of per-pixel output albedo values (needed by OptiX denoiser).")
self._add_setting(SettingType.BOOL, "Compress Normals", "/rtx/pathtracing/mgpu/compressNormals", tooltip="Enables lossy compression of per-pixel output normal values (needed by OptiX denoiser).")
self._add_setting(SettingType.BOOL, "Multi-Threading", "/rtx/multiThreading/enabled", tooltip="Enabling multi-threading improves UI responsiveness.")
def destroy(self):
self._change_cb1 = None
super().destroy()
class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame):
""" PT Only Global Volumetric Effects Settings"""
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Rayleigh Atmosphere", "/rtx/pathtracing/ptvol/raySky", tooltip="\nEnables an additional medium of Rayleigh-scattering particles to simulate a physically-based sky.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/ptvol/raySky", self._on_change)
if self._settings.get("/rtx/pathtracing/ptvol/raySky"):
self._add_setting(SettingType.FLOAT, " Rayleigh Atmosphere Scale", "/rtx/pathtracing/ptvol/raySkyScale", 0.01, 100, 1, tooltip="\nScales the size of the Rayleigh sky.")
self._add_setting(SettingType.BOOL, " Skip Background", "/rtx/pathtracing/ptvol/raySkyDomelight",
tooltip="\nIf a domelight is rendered for the sky color, the Rayleight Atmosphere is applied to the"
"\nforeground while the background sky color is left unaffected.")
def destroy(self):
self._change_cb = None
super().destroy()
class PTSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
PathTracingSettingsFrame("Path-Tracing", parent=self)
SamplingAndCachingSettingsFrame("Sampling & Caching", parent=self)
AntiAliasingSettingsFrame("Anti-Aliasing", parent=self)
FireflyFilterSettingsFrame("Firefly Filtering", parent=self)
DenoisingSettingsFrame("Denoising", parent=self)
NonUniformVolumesSettingsFrame("Non-uniform Volumes", parent=self)
GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self)
AOVSettingsFrame("AOV", parent=self)
MultiMatteSettingsFrame("Multi Matte", parent=self)
gpu_count = carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") or 0
if gpu_count > 1:
MultiGPUSettingsFrame("Multi-GPU", parent=self)
| 18,001 | Python | 79.366071 | 279 | 0.70135 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/rt_widgets.py | import omni.kit.app
import omni.ui as ui
import carb.settings
from omni.kit.widget.settings import SettingType
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
DEBUG_OPTIONS = False
sampled_lighting_spp_items = {"1": 1, "2": 2, "4": 4, "8": 8}
class EcoMode(SettingsCollectionFrame):
""" ECO Mode """
def _frame_setting_path(self):
return "/rtx/ecoMode/enabled"
def _build_ui(self):
self._add_setting(SettingType.INT, "Stop Rendering After This Many Frames Without Changes", "/rtx/ecoMode/maxFramesWithoutChange", 0, 100)
class AntiAliasingSettingsFrame(SettingsCollectionFrame):
""" DLSS """
def _on_antialiasing_change(self, *_):
self._rebuild()
def _build_ui(self):
# Note: order depends on rtx::postprocessing::AntialiasingMethod
antialiasing_ops = dict()
if self._settings.get("/rtx-transient/post/dlss/supported") is True:
antialiasing_ops["DLSS"] = 3
antialiasing_ops["DLAA"] = 4
if self._settings.get("/rtx-transient/hashed/995bcbda752ace40e33a4d131067d270"):
self._add_setting(SettingType.BOOL, "Frame Generation", "/rtx-transient/dlssg/enabled",
tooltip="\nDLSS Frame Generation boosts performance by using AI to generate more frames."
"\nDLSS analyzes sequential frames and motion data to create additional high quality frames. This feature requires an Ada Lovelace architecture GPU.")
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx-transient/hashed/995bcbda752ace40e33a4d131067d270", self._on_antialiasing_change)
self._add_setting(SettingType.BOOL, "Ray Reconstruction", "/rtx/newDenoiser/enabled", tooltip="\nDLSS Ray Reconstruction enhances image quality for ray-traced scenes with an NVIDIA"
"\nsupercomputer-trained AI network that generates higher-quality pixels in between sampled rays.")
self._add_setting_combo("Super Resolution", "/rtx/post/aa/op", antialiasing_ops, tooltip="\nDLSS Super Resolution boosts performance by using AI to output higher resolution frames from a lower resolution input."
"\nDLSS samples multiple lower resolution images and uses motion data and feedback from prior frames to reconstruct native quality images.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/post/aa/op", self._on_antialiasing_change)
antialiasingOpIdx = self._settings.get("/rtx/post/aa/op")
exposure_ops = {
"Force self evaluated" : 0,
"PostProcess Autoexposure" : 1,
"Fixed" : 2
}
if antialiasingOpIdx == 1:
""" TAA """
self._add_setting(SettingType.FLOAT, "Static scaling", "/rtx/post/scaling/staticRatio", 0.33, 1, 0.01)
self._add_setting(SettingType.INT, "TAA Samples", "/rtx/post/taa/samples", 1, 16)
self._add_setting(SettingType.FLOAT, "TAA history scale", "/rtx/post/taa/alpha", 0, 1, 0.1)
elif antialiasingOpIdx == 2:
""" FXAA """
self._add_setting(SettingType.FLOAT, "Subpixel Quality", "/rtx/post/fxaa/qualitySubPix", 0.0, 1.0, 0.02)
self._add_setting(SettingType.FLOAT, "Edge Threshold", "/rtx/post/fxaa/qualityEdgeThreshold", 0.0, 1.0, 0.02)
self._add_setting(SettingType.FLOAT, "Edge Threshold Min", "/rtx/post/fxaa/qualityEdgeThresholdMin", 0.0, 1.0, 0.02)
elif antialiasingOpIdx == 3 or antialiasingOpIdx == 4:
""" DLSS and DLAA """
if antialiasingOpIdx == 3:
# needs to be in sync with DLSSMode enum
dlss_opts = {"Auto": 3, "Performance": 0, "Balanced": 1, "Quality": 2}
self._add_setting_combo(" Mode", "/rtx/post/dlss/execMode", dlss_opts, tooltip="\nAuto: Selects the best DLSS Mode for the current output resolution.\nPerformance: Higher performance than balanced mode.\nBalanced: Balanced for optimized performance and image quality.\nQuality: Higher image quality than balanced mode.")
self._add_setting(SettingType.FLOAT, " Sharpness", "/rtx/post/aa/sharpness", 0.0, 1.0, 0.5, tooltip="\nHigher values produce sharper results.")
self._add_setting_combo(" Exposure Mode", "/rtx/post/aa/autoExposureMode", exposure_ops, tooltip="\nChoose between Force self evaluated, PostProcess AutoExposure, Fixed.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/post/aa/autoExposureMode", self._on_antialiasing_change)
autoExposureIdx = self._settings.get("/rtx/post/aa/autoExposureMode")
if autoExposureIdx == 1:
self._add_setting(SettingType.FLOAT, " Auto Exposure Multiplier", "/rtx/post/aa/exposureMultiplier", 0.00001, 10.0, 0.00001, tooltip="\nFactor with which to multiply the selected exposure mode.")
elif autoExposureIdx == 2:
self._add_setting(SettingType.FLOAT, " Fixed Exposure Value", "/rtx/post/aa/exposure", 0.00001, 1.0, 0.00001)
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
super().destroy()
class DirectLightingSettingsFrame(SettingsCollectionFrame):
""" Direct Lighting """
def _frame_setting_path(self):
return "/rtx/directLighting/enabled"
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/enabled", self._on_change)
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/autoEnable", self._on_change)
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/domeLight/enabled", self._on_change)
self._change_cb4 = omni.kit.app.SettingChangeSubscription("/rtx/newDenoiser/enabled", self._on_change)
self._change_cb5 = omni.kit.app.SettingChangeSubscription("/rtx/shadows/enabled", self._on_change)
self._add_setting(SettingType.BOOL, "Shadows", "/rtx/shadows/enabled", tooltip="\nWhen disabled, lights will not cast shadows.")
self._add_setting(SettingType.BOOL, "Sampled Direct Lighting Mode", "/rtx/directLighting/sampledLighting/enabled", tooltip="\nMode which favors performance with many lights (10 or more), at the cost of image quality.")
self._add_setting(SettingType.BOOL, "Auto-enable Sampled Direct Lighting Above Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnable", tooltip="\nAutomatically enables Sampled Direct Lighting when the light count is greater than the Light Count Threshold.")
if self._settings.get("/rtx/directLighting/sampledLighting/autoEnable"):
self._add_setting(SettingType.INT, " Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold", tooltip="\nLight count threshold above which Sampled Direct Lighting is automatically enabled.")
if not self._settings.get("/rtx/directLighting/sampledLighting/enabled"):
with ui.CollapsableFrame("Non-Sampled Lighting Settings", height=0):
with ui.VStack(height=0, spacing=5):
if self._settings.get("/rtx/shadows/enabled"):
self._add_setting(SettingType.INT, " Shadow Samples per Pixel", "/rtx/shadows/sampleCount", 1, 16, tooltip="\nHigher values increase the quality of shadows at the cost of performance.")
if not self._settings.get("/rtx/newDenoiser/enabled"):
self._add_setting(SettingType.BOOL, " Low Resolution Shadow Denoiser", "/rtx/shadows/denoiser/quarterRes", tooltip="\nReduces the shadow denoiser resolution to gain performance at the cost of quality.")
self._add_setting(SettingType.BOOL, " Dome Lighting", "/rtx/directLighting/domeLight/enabled", tooltip="\nEnables dome light contribution to diffuse BSDFs if Dome Light mode is IBL.")
if self._settings.get("/rtx/directLighting/domeLight/enabled"):
self._add_setting(SettingType.BOOL, " Dome Lighting in Reflections", "/rtx/directLighting/domeLight/enabledInReflections", tooltip="\nEnables Dome Light sampling in reflections at the cost of performance.")
self._add_setting(SettingType.INT, " Dome Light Samples per Pixel", "/rtx/directLighting/domeLight/sampleCount", 0, 32, tooltip="\nHigher values increase dome light sampling quality at the cost of performance.")
else:
with ui.CollapsableFrame("Sampled Direct Lighting Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting_combo(" Samples per Pixel", "/rtx/directLighting/sampledLighting/samplesPerPixel", sampled_lighting_spp_items, tooltip="\nHigher values increase the direct lighting quality at the cost of performance.")
# self._add_setting(SettingType.BOOL, "Clamp Sample Count to Light Count", "/rtx/directLighting/sampledLighting/clampSamplesPerPixelToNumberOfLights", tooltip="\n\t When enabled, clamps the \"Samples per Pixel\" to the number of lights in the scene")
self._add_setting(SettingType.FLOAT, " Max Ray Intensity", "/rtx/directLighting/sampledLighting/maxRayIntensity", 0.0, 1000000, 100, tooltip="\nClamps the brightness of a sample, which helps reduce fireflies, but may result in some loss of energy.")
# self._add_setting(SettingType.BOOL, "Reflections: Clamp Sample Count to Light Count", "/rtx/reflections/sampledLighting/clampSamplesPerPixelToNumberOfLights", tooltip="\n\t When enabled, clamps the \"Reflections: Light Samples per Pixel\" to the number of lights in the scene")
self._add_setting_combo(" Reflections: Light Samples per Pixel", "/rtx/reflections/sampledLighting/samplesPerPixel", sampled_lighting_spp_items, tooltip="\nHigher values increase the reflections quality at the cost of performance.")
self._add_setting(SettingType.FLOAT, " Reflections: Max Ray Intensity", "/rtx/reflections/sampledLighting/maxRayIntensity", 0.0, 1000000, 100, tooltip="\nClamps the brightness of a sample, which helps reduce fireflies, but may result in some loss of energy.")
if not self._settings.get("/rtx/newDenoiser/enabled"):
firefly_filter_types = {"None" : "None", "Median" : "Cross-Bilateral Median", "RCRS" : "Cross-Bilateral RCRS"}
self._add_setting_combo(" Firefly Filter", "/rtx/lightspeed/ReLAX/fireflySuppressionType", firefly_filter_types, tooltip="\nChoose the filter type (None, Median, RCRS). Clamps overly bright pixels to a maximum value.")
self._add_setting(SettingType.BOOL, " History Clamping", "/rtx/lightspeed/ReLAX/historyClampingEnabled", tooltip="\nReduces temporal lag.")
self._add_setting(SettingType.INT, " Denoiser Iterations", "/rtx/lightspeed/ReLAX/aTrousIterations", 1, 10, tooltip="\nNumber of times the frame is denoised.")
# disabled with macro in the .hlsl as was causing extra spills & wasnt really used at all
# self._add_setting(SettingType.BOOL, "Enable Extended Diffuse Backscattering", "/rtx/directLighting/diffuseBackscattering/enabled")
# self._add_setting(SettingType.FLOAT, "Shadow Ray Offset", "/rtx/directLighting/diffuseBackscattering/shadowOffset", 0.1, 1000, 0.5)
# self._add_setting(SettingType.FLOAT, "Extinction", "/rtx/directLighting/diffuseBackscattering/extinction", 0.001, 100, 0.01)
self._add_setting(SettingType.BOOL, " Mesh-Light Sampling", "/rtx/directLighting/sampledLighting/ris/meshLights", tooltip="\nEnables direct illumination sampling of geometry with emissive materials.")
# Hiding this to simplify things for now. Will be auto-enabled if /rtx/raytracing/fractionalCutoutOpacity is enabled
# self._add_setting(SettingType.BOOL, "Enable Fractional Opacity", "/rtx/shadows/fractionalCutoutOpacity")
# self._add_setting(SettingType.BOOL, "Show Lights", "/rtx/directLighting/showLights") #deprecated, use /rtx/raytracing/showLights
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
self._change_cb4 = None
self._change_cb5 = None
super().destroy()
class ReflectionsSettingsFrame(SettingsCollectionFrame):
""" Reflections """
def _frame_setting_path(self):
return "/rtx/reflections/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Roughness Cache Threshold", "/rtx/reflections/maxRoughness", 0.0, 1.0, 0.02, tooltip="\nRoughness threshold for approximated reflections. Higher values result in better quality, at the cost of performance.")
self._add_setting(SettingType.INT, "Max Reflection Bounces", "/rtx/reflections/maxReflectionBounces", 0, 100, tooltip="\nNumber of bounces for reflection rays.")
class TranslucencySettingsFrame(SettingsCollectionFrame):
""" Translucency (Refraction) """
def _frame_setting_path(self):
return "/rtx/translucency/enabled"
def _build_ui(self):
self._add_setting(SettingType.INT, "Max Refraction Bounces", "/rtx/translucency/maxRefractionBounces", 0, 100, tooltip="\nNumber of bounces for refraction rays.")
self._add_setting(SettingType.BOOL, "Reflection Seen Through Refraction", "/rtx/translucency/reflectAtAllBounce", tooltip="\n\t When enabled, reflection seen through refraction is rendered. When disabled, reflection is limited to first bounce only. More accurate, but worse performance")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/translucency/reflectAtAllBounce", self._on_change)
if self._settings.get("/rtx/translucency/reflectAtAllBounce"):
self._add_setting(SettingType.FLOAT, "Secondary Bounce Reflection Throughput Threshold", "/rtx/translucency/reflectionThroughputThreshold", 0.0, 1.0, 0.005, tooltip="\nThreshold below which reflection paths due to fresnel are no longer traced. Lower values result in higher quality at the cost of performance.")
self._add_setting(SettingType.BOOL, "Fractional Cutout Opacity", "/rtx/raytracing/fractionalCutoutOpacity", tooltip="\nEnables fractional cutout opacity values resulting in a translucency-like effect similar to alpha-blending.")
self._add_setting(SettingType.BOOL, "Depth Correction for DoF", "/rtx/translucency/virtualDepth", tooltip="\nImproves DoF for translucent (refractive) objects, but can result in worse performance.")
self._add_setting(SettingType.BOOL, "Motion Vector Correction (experimental)", "/rtx/translucency/virtualMotion", tooltip="\nEnables motion vectors for translucent (refractive) objects, which can improve temporal rendering such as denoising, but can result in worse performance.")
self._add_setting(SettingType.FLOAT, "World Epsilon Threshold", "/rtx/translucency/worldEps", 0.0001, 5, 0.01, tooltip="\nTreshold below which image-based reprojection is used to compute refractions. Lower values result in higher quality at the cost performance.")
self._add_setting(SettingType.BOOL, "Roughness Sampling (experimental)", "/rtx/translucency/sampleRoughness", tooltip="\nEnables sampling roughness, such as for simulating frosted glass, but can result in worse performance.")
def destroy(self):
self._change_cb1 = None
super().destroy()
class CausticsSettingsFrame(SettingsCollectionFrame):
""" Caustics """
def _frame_setting_path(self):
return "/rtx/caustics/enabled"
def _build_ui(self):
self._add_setting(SettingType.INT, "Photon Count Multiplier", "/rtx/raytracing/caustics/photonCountMultiplier", 1, 5000, tooltip="\nFactor multiplied by 1024 to compute the total number of photons to generate from each light.")
self._add_setting(SettingType.INT, "Photon Max Bounces", "/rtx/raytracing/caustics/photonMaxBounces", 1, 20, tooltip="\nMaximum number of bounces to compute for each light/photon path.")
self._add_setting(SettingType.FLOAT, "Position Phi", "/rtx/raytracing/caustics/positionPhi", 0.1, 50)
self._add_setting(SettingType.FLOAT, "Normal Phi", "/rtx/raytracing/caustics/normalPhi", 0.3, 1)
self._add_setting(SettingType.INT, "Filter Iterations", "/rtx/raytracing/caustics/eawFilteringSteps", 0, 10, tooltip="\nNumber of iterations for the denoiser applied to the results of the caustics tracing pass.")
class IndirectDiffuseLightingSettingsFrame(SettingsCollectionFrame):
def _on_denoiser_change(self, *_):
self._rebuild()
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/ambientOcclusion/enabled", self._on_change)
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/indirectDiffuse/enabled", self._on_change)
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/indirectDiffuse/denoiser/method", self._on_change)
self._change_cb4 = omni.kit.app.SettingChangeSubscription("/rtx/newDenoiser/enabled", self._on_change)
self._add_setting(SettingType.BOOL, "Indirect Diffuse GI", "/rtx/indirectDiffuse/enabled", tooltip="\nEnables indirect diffuse GI sampling.")
if self._settings.get("/rtx/indirectDiffuse/enabled"):
gi_denoising_techniques_ops = ["NVRTD", "NRD:Reblur"]
self._add_setting(SettingType.INT, " Samples Per Pixel", "/rtx/indirectDiffuse/fetchSampleCount", 0, 4, tooltip="\nNumber of samples made for indirect diffuse GI. Higher number gives better GI quality, but worse performance.")
self._add_setting(SettingType.INT, " Max Bounces", "/rtx/indirectDiffuse/maxBounces", 0, 16, tooltip="\nNumber of bounces approximated with indirect diffuse GI.")
self._add_setting(SettingType.FLOAT, " Intensity", "/rtx/indirectDiffuse/scalingFactor", 0.0, 20.0, 0.1, tooltip="\nMultiplier for the indirect diffuse GI contribution.")
self._add_setting_combo(" Denoising Mode", "/rtx/indirectDiffuse/denoiser/method", gi_denoising_techniques_ops)
if self._settings.get("/rtx/indirectDiffuse/denoiser/method") == 0:
self._add_setting(SettingType.INT, " Kernel Radius", "/rtx/indirectDiffuse/denoiser/kernelRadius", 1, 64, tooltip="\nControls the spread of local denoising area. Higher values results in smoother GI.")
self._add_setting(SettingType.INT, " Iteration Count", "/rtx/indirectDiffuse/denoiser/iterations", 1, 10, tooltip="\nThe number of denoising passes. Higher values results in smoother looking GI.")
self._add_setting(SettingType.INT, " Max History Length", "/rtx/indirectDiffuse/denoiser/temporal/maxHistory", 1, 100, tooltip="\nControls latency in GI updates. Higher values results in smoother looking GI.")
if self._settings.get("/rtx/indirectDiffuse/denoiser/method") == 1:
self._add_setting(SettingType.INT, " Frames In History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxAccumulatedFrameNum", 0, 63)
self._add_setting(SettingType.INT, " Frames In Fast History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxFastAccumulatedFrameNum", 0, 63)
self._add_setting(SettingType.FLOAT, " Plane Distance Sensitivity", "/rtx/lightspeed/NRD_ReblurDiffuse/planeDistanceSensitivity", 0, 1, 0.01)
self._add_setting(SettingType.FLOAT, " Blur Radius", "/rtx/lightspeed/NRD_ReblurDiffuse/blurRadius", 0, 100, 5)
self._add_setting(SettingType.BOOL, "Ambient Occlusion", "/rtx/ambientOcclusion/enabled", tooltip="\nEnables ambient occlusion.")
if self._settings.get("/rtx/ambientOcclusion/enabled"):
self._add_setting(SettingType.FLOAT, " Ray Length (cm)", "/rtx/ambientOcclusion/rayLength", 0.0, 2000.0, tooltip="\nThe radius around the intersection point which the ambient occlusion affects.")
self._add_setting(SettingType.INT, " Minimum Samples Per Pixel", "/rtx/ambientOcclusion/minSamples", 1, 16, tooltip="\nMinimum number of samples per frame for ambient occlusion sampling.")
self._add_setting(SettingType.INT, " Maximum Samples Per Pixel", "/rtx/ambientOcclusion/maxSamples", 1, 16, tooltip="\nMaximum number of samples per frame for ambient occlusion sampling.")
aoDenoiserMode = {
"None" : 0,
"Aggressive" : 1,
"Simple" : 2,
}
if not self._settings.get("/rtx/newDenoiser/enabled"):
self._add_setting_combo(" Denoiser", "/rtx/ambientOcclusion/denoiserMode", aoDenoiserMode, tooltip="\nAllows for increased AO denoising at the cost of more blurring.")
self._add_setting(SettingType.COLOR3, "Ambient Light Color", "/rtx/sceneDb/ambientLightColor", tooltip="\nColor of the global environment lighting.")
self._add_setting(SettingType.FLOAT, "Ambient Light Intensity", "/rtx/sceneDb/ambientLightIntensity", 0.0, 10.0, 0.1, tooltip="\nBrightness of the global environment lighting.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
self._change_cb4 = None
super().destroy()
class RTMultiGPUSettingsFrame(SettingsCollectionFrame):
""" Multi-GPU """
def _frame_setting_path(self):
return "/rtx/realtime/mgpu/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Automatic Tiling", "/rtx/realtime/mgpu/autoTiling/enabled",
tooltip="\nAutomatically determines the image-space grid used to distribute rendering to available GPUs."
"\nThe image rendering is split into a large tile per GPU with a small overlap region between them."
"\nNote that by default not necessarily all GPUs are used. The approximate number of tiles is viewport"
"\nresolution divided by the Minimum Megapixels Per Tile setting, since at low resolution small tiles distributed"
"\nacross too many devices decreases performance due to multi-GPU overheads."
"\nDisable automatic tiling to manually specify the number of tiles to be distributed across devices.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/realtime/mgpu/autoTiling/enabled", self._on_change)
if self._settings.get("/rtx/realtime/mgpu/autoTiling/enabled"):
self._add_setting(SettingType.FLOAT, " Minimum Megapixels Per Tile", "/rtx/realtime/mgpu/autoTiling/minMegaPixelsPerTile", 0.1, 2.0, 0.1, tooltip="\nThe minimum number of Megapixels each tile should have after screen-space subdivision.")
else:
currentGpuCount = self._settings.get("/renderer/multiGpu/currentGpuCount")
self._add_setting(SettingType.INT, "Tile Count", "/rtx/realtime/mgpu/tileCount", 2, currentGpuCount, tooltip="\nNumber of tiles to split the image into. Usually this should match the number of GPUs, but can be less.")
self._add_setting(SettingType.INT, "Tile Overlap (Pixels)", "/rtx/realtime/mgpu/tileOverlap", 0, 256, 0.1, tooltip="\nWidth, in pixels, of the overlap region between any two neighboring tiles.")
self._add_setting(SettingType.FLOAT, "GPU 0 Weight", "/rtx/realtime/mgpu/masterDeviceLoadBalancingWeight", 0, 1, 0.001,
tooltip="\nThis normalized weight can be used to decrease the rendering workload on the primary device for each viewport"
"\nin relation to the other secondary devices, which can be helpful for load balancing in situations where the primary"
"\ndevice also needs to perform additional expensive operations such as denoising and post-processing.")
self._add_setting(SettingType.BOOL, "Multi-Threading", "/rtx/multiThreading/enabled", tooltip="\nExecute per-device render command recording in separate threads.")
class SubsurfaceScatteringSettingsFrame(SettingsCollectionFrame):
""" Subsurface Scattering """
def _frame_setting_path(self):
return "/rtx/raytracing/subsurface/enabled"
def _on_change(self, *_):
self._rebuild()
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/enabled", self._on_change)
self._add_setting(SettingType.INT, "Max Samples Per Frame", "/rtx/raytracing/subsurface/maxSamplePerFrame", 1, 128, tooltip="\nMax samples per frame for the infinitely-thick geometry SSS approximation.")
# self._add_setting(SettingType.FLOAT, "History Weight", "/rtx/raytracing/subsurface/historyWeight", 0.001, 0.5, 0.02)
# self._add_setting(SettingType.FLOAT, "Variance Threshold", "/rtx/raytracing/subsurface/targetVariance", 0.001, 1, 0.05)
# self._add_setting(SettingType.FLOAT, "World space sample projection Threshold", "/rtx/raytracing/subsurface/shadowRayThreshold", 0, 1, 0.01)
self._add_setting(SettingType.BOOL, "Firefly Filtering", "/rtx/raytracing/subsurface/fireflyFiltering/enabled", tooltip="\nEnables firefly filtering for the subsurface scattering. The maximum filter intensity is determined by '/rtx/directLighting/sampledLighting/maxRayIntensity'.")
self._add_setting(SettingType.BOOL, "Denoiser", "/rtx/raytracing/subsurface/denoiser/enabled", tooltip="\nEnables denoising for the subsurface scattering.")
if self._settings.get("/rtx/directLighting/sampledLighting/enabled"):
self._add_setting(SettingType.BOOL, "Denoise Irradiance Input", "/rtx/directLighting/sampledLighting/irradiance/denoiser/enabled",
tooltip="\nDenoise the irradiance output from sampled lighting pass before it's used, helps in complex lighting conditions"
"\nor if there are large area lights which makes irradiance estimation difficult with low sampled lighting sample count.")
self._add_setting(SettingType.BOOL, "Transmission", "/rtx/raytracing/subsurface/transmission/enabled", tooltip="\nEnables transmission of light through the medium, but requires additional samples and denoising.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/subsurface/transmission/enabled", self._on_change)
if self._settings.get("/rtx/raytracing/subsurface/transmission/enabled"):
self._add_setting(SettingType.INT, " BDSF Sample Count", "/rtx/raytracing/subsurface/transmission/bsdfSampleCount", 0, 8, tooltip="\nTransmission sample count per frame.")
self._add_setting(SettingType.INT, " Samples Per BSDF Sample", "/rtx/raytracing/subsurface/transmission/perBsdfScatteringSampleCount", 0, 16, tooltip="\nTransmission samples count per BSDF Sample. Samples per pixel per frame = BSDF Sample Count * Samples Per BSDF Sample.")
self._add_setting(SettingType.FLOAT, " Screen-Space Fallback Threshold", "/rtx/raytracing/subsurface/transmission/screenSpaceFallbackThresholdScale", 0.0001, 1, tooltip="\nTransmission threshold for screen-space fallback.")
self._add_setting(SettingType.BOOL, " Half-Resolution Rendering", "/rtx/raytracing/subsurface/transmission/halfResolutionBackfaceLighting", tooltip="\nEnables rendering transmission in half-resolution to improve performance at the expense of quality.")
self._add_setting(SettingType.BOOL, " Sample Guiding", "/rtx/raytracing/subsurface/transmission/ReSTIR/enabled", tooltip="\nEnables transmission sample guiding, which may help with complex lighting scenarios.")
self._add_setting(SettingType.BOOL, " Denoiser", "/rtx/raytracing/subsurface/transmission/denoiser/enabled", tooltip="\nEnables transmission denoising.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
super().destroy()
class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame):
""" RT Only Global Volumetric Effects Settings"""
def _build_ui(self):
self._add_setting(SettingType.INT, "Accumulation Frames", "/rtx/raytracing/inscattering/maxAccumulationFrames", 0, 256, tooltip="\nNumber of frames samples accumulate over temporally. High values reduce noise, but increase lighting update times.")
self._add_setting(SettingType.INT, "Depth Slices Count", "/rtx/raytracing/inscattering/depthSlices", 16, 1024, tooltip="\nNumber of layers in the voxel grid to be allocated. High values result in higher precision at the cost of memory and performance.")
self._add_setting(SettingType.INT, "Pixel Density", "/rtx/raytracing/inscattering/pixelRatio", 4, 64, tooltip="\nLower values result in higher fidelity volumetrics at the cost of performance and memory (depending on the # of depth slices).")
self._add_setting(SettingType.FLOAT, "Slice Distribution Exponent", "/rtx/raytracing/inscattering/sliceDistributionExponent", 1, 16, tooltip="\nControls the number (and relative thickness) of the depth slices.")
self._add_setting(SettingType.INT, "Inscatter Upsample", "/rtx/raytracing/inscattering/inscatterUpsample", 1, 64, tooltip="\n")
self._add_setting(SettingType.FLOAT, "Inscatter Blur Sigma", "/rtx/raytracing/inscattering/blurSigma", 0.0, 10.0, 0.01, tooltip="\nSigma parameter for the Gaussian filter used to spatially blur the voxel grid. 1 = no blur, higher values blur further.")
self._add_setting(SettingType.FLOAT, "Inscatter Dithering Scale", "/rtx/raytracing/inscattering/ditheringScale", 0, 10000, tooltip="\nThe scale of the noise dithering. Used to reduce banding from quantization on smooth gradients.")
self._add_setting(SettingType.FLOAT, "Spatial Sample Jittering Scale", "/rtx/raytracing/inscattering/spatialJitterScale", 0.0, 1, 0.0001, tooltip="\nScales how far light samples within a voxel are spatially jittered: 0 = only from the center, 1 = the entire voxel's volume.")
self._add_setting(SettingType.FLOAT, "Temporal Reprojection Jittering Scale", "/rtx/raytracing/inscattering/temporalJitterScale", 0.0, 1, 0.0001,
tooltip="\nScales how far to offset temporally-reprojected samples within a voxel: 0 = only from the center, 1 = the entire voxel's volume."
"\nActs like a temporal blur and helps reduce noise under motion.")
self._add_setting(SettingType.BOOL, "Use 32-bit Precision", "/rtx/raytracing/inscattering/use32bitPrecision", tooltip="\nAllocate the voxel grid with 32-bit per channel color instead of 16-bit. This doubles memory usage and reduces performance, generally avoided.")
self._add_setting(SettingType.BOOL, "Flow Sampling", "/rtx/raytracing/inscattering/enableFlowSampling", tooltip="\n")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/inscattering/enableFlowSampling", self._on_change)
if self._settings.get("/rtx/raytracing/inscattering/enableFlowSampling"):
self._add_setting(SettingType.INT, " Min Layer", "/rtx/raytracing/inscattering/minFlowLayer", 0, 64, tooltip="\n")
self._add_setting(SettingType.INT, " Max Layer", "/rtx/raytracing/inscattering/maxFlowLayer", 0, 64, tooltip="\n")
self._add_setting(SettingType.FLOAT, " Density Scale", "/rtx/raytracing/inscattering/flowDensityScale", 0.0, 100.0, tooltip="\n")
self._add_setting(SettingType.FLOAT, " Density Offset", "/rtx/raytracing/inscattering/flowDensityOffset", 0.0, 100.0, tooltip="\n")
def destroy(self):
self._change_cb1 = None
super().destroy()
class RTSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
EcoMode("Eco Mode", parent=self)
AntiAliasingSettingsFrame("NVIDIA DLSS", parent=self)
DirectLightingSettingsFrame("Direct Lighting", parent=self)
IndirectDiffuseLightingSettingsFrame("Indirect Diffuse Lighting", parent=self)
ReflectionsSettingsFrame("Reflections", parent=self)
translucency = TranslucencySettingsFrame("Translucency", parent=self)
SubsurfaceScatteringSettingsFrame("Subsurface Scattering", parent=translucency)
CausticsSettingsFrame("Caustics", parent=self)
GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self)
gpuCount = carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount")
if gpuCount and gpuCount > 1:
RTMultiGPUSettingsFrame("Multi-GPU", parent=self)
| 33,283 | Python | 90.189041 | 338 | 0.698314 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/tests/__init__.py | from .test_settings import TestRTXCoreSettingsUI | 49 | Python | 48.999951 | 49 | 0.877551 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/tests/test_settings.py |
import carb
import omni.kit.test
import omni.usd
import tempfile
import pathlib
import rtx.settings
from omni.kit import ui_test
from omni.rtx.tests.test_common import wait_for_update
settings = carb.settings.get_settings()
EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
USD_DIR = EXTENSION_FOLDER_PATH.joinpath("data/usd")
class TestRTXCoreSettingsUI(omni.kit.test.AsyncTestCase):
VALUE_EPSILON = 0.00001
async def setUp(self):
super().setUp()
# We need to trigger Iray load to get the default render-settings values written to carb.settings
# Viewports state is valid without any open stage, and only loads renderer when stage is opened.
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
# After running each test
async def tearDown(self):
omni.kit.window.property.managed_frame.reset_collapsed_state()
def get_render_setings_window(self):
render_settings_window = ui_test.find("Render Settings")
render_settings_window.widget.height = 1200
render_settings_window.widget.width = 600
render_settings_window.widget.visible = True
return render_settings_window
def set_renderer(self, render_settings_window, index):
#select the combo box item
box = render_settings_window.find("Frame/VStack[0]/HStack[0]/ComboBox[*]")
box.model.get_item_value_model(None, 0).set_value(index)
def compare_floats(self, a, b, epsilon):
self.assertEqual(len(a), len(b))
for i in range(0, len(a)):
self.assertLessEqual(
abs(a[i] - b[i]), epsilon, "a[" + str(i) + "] = " + str(a[i]) + ", b[" + str(i) + "] = " + str(b[i])
)
def compare_float(self, a, b, epsilon):
self.assertLessEqual(abs(a - b), epsilon)
def open_usd(self, usdSubpath: pathlib.Path):
path = USD_DIR.joinpath(usdSubpath)
omni.usd.get_context().open_stage(str(path))
async def test_bool_checkbox_setting(self):
'''
check that we can switch on/off back face culling in Common/Geometry
'''
render_settings_window = self.get_render_setings_window()
setting_name = "/rtx/hydra/faceCulling/enabled"
#Cycle through Realtime, path-tracing renders
for index in range(0, 2):
self.set_renderer(render_settings_window, index)
# Set initial value
settings.set(setting_name, False)
await omni.kit.app.get_app().next_update_async()
#choose the "Common" tab in each case
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]")
await button.click()
#Get the collapsable frame for Geometry and open it
collapsable_frame = render_settings_window.find("**/Geometry")
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
#This is the back face culling hstack
back_face_culling_setting = collapsable_frame.find("/**/HStack_Back_Face_Culling")
self.assertTrue(isinstance(back_face_culling_setting.widget, omni.ui.HStack))
check_box = back_face_culling_setting.find("**/CheckBox[0]")
self.assertTrue(isinstance(check_box.widget, omni.ui.CheckBox))
await check_box.click(human_delay_speed=10)
face_culling_value = settings.get(setting_name)
self.assertTrue(face_culling_value)
await check_box.click(human_delay_speed=10)
face_culling_value = settings.get(setting_name)
self.assertFalse(face_culling_value)
async def test_combo_box_setting(self):
'''
check that we can set TBNFrame mode Combo Box in Common/Geometry
'''
render_settings_window = self.get_render_setings_window()
setting_name = "/rtx/hydra/TBNFrameMode"
#Cycle through Realtime, path-tracing renders
for index in range(0, 2):
self.set_renderer(render_settings_window, index)
# Set initial value
settings.set(setting_name, 0)
await omni.kit.app.get_app().next_update_async()
#choose the "Common" tab in each case
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]")
await button.click()
#Get the collapsable frame for Geometry and open it
collapsable_frame = render_settings_window.find("**/Geometry")
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
tangent_space_setting = collapsable_frame.find("/**/HStack_Normal_&_Tangent_Space_Generation_Mode")
self.assertTrue(isinstance(tangent_space_setting.widget, omni.ui.HStack))
combo_box = tangent_space_setting.find("ComboBox[0]")
self.assertTrue(isinstance(combo_box.widget, omni.ui.ComboBox))
combo_box.model.get_item_value_model(None, 0).set_value(1)
tbn_frame_mode_setting = settings.get(setting_name)
self.assertTrue(tbn_frame_mode_setting == 1)
async def test_float_setting(self):
'''
check that we can set float MDL Animation Time Override in Common/Materials
'''
render_settings_window = self.get_render_setings_window()
setting_name = "/rtx/animationTime"
#Cycle through Realtime, path-tracing renders
for index in range(0, 2):
self.set_renderer(render_settings_window, index)
# Set initial value
settings.set(setting_name, -1.0)
await omni.kit.app.get_app().next_update_async()
#choose the "Common" tab in each case
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]")
await button.click()
#Get the collapsable frame for Materials and expand it
collapsable_frame = render_settings_window.find("**/Geometry")
collapsable_frame.widget.collapsed = True
collapsable_frame = render_settings_window.find("**/Materials")
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
tangent_space_setting = collapsable_frame.find("**/HStack_Animation_Time_Override")
self.assertTrue(isinstance(tangent_space_setting.widget, omni.ui.HStack))
slider = tangent_space_setting.find("FloatDrag[0]")
self.assertTrue(isinstance(slider.widget, omni.ui.FloatDrag))
await ui_test.human_delay(50)
await slider.input("20.0")
tbn_frame_mode_setting = settings.get(setting_name)
self.assertAlmostEqual(tbn_frame_mode_setting, 20.0, 2, f"was actually {tbn_frame_mode_setting}")
async def run_render_settings_storage_helper(self, must_save=False):
with tempfile.TemporaryDirectory() as tmpdirname:
usd_context = omni.usd.get_context()
await omni.kit.app.get_app().next_update_async()
# save the file with various types of setting value types.
# Note: if ever any of these were removed, replace them with a new setting of the same type.
setting_fog_b = "/rtx/fog/enabled" # bool
setting_meter_unit_f = "/rtx/scene/renderMeterPerUnit" # float
setting_heatmap_i = "/rtx/debugView/heatMapPass" # int
setting_max_bounce_i = "/rtx/pathtracing/maxBounces" # int, pathtracer
setting_mat_white_s = "/rtx/debugMaterialWhite" # string
setting_ambinet_arr_f = "/rtx/sceneDb/ambientLightColor" # array of float3
setting_saturation_arr_f = "/rtx/post/colorcorr/saturation" # array of double3
# settings with special kSettingFlagTransient, treated like rtx-transient.
setting_mthread_transient_b = "/rtx/multiThreading/enabled" # uses kSettingFlagTransient in C++
setting_dir_light_b = "/rtx-transient/disable/directLightingSampled" # manual transient
setting_place_col_b = "/persistent/rtx/resourcemanager/placeholderTextureColor" # persistent
# set as transient in [[test]]
setting_fog_dist_i = "/rtx/fog/fogEndDist" # int
setting_fog_color_arr_f = "/rtx/fog/fogColor" # array of float
settings.set_bool(setting_fog_b, True)
settings.set_float(setting_meter_unit_f, 0.5)
settings.set_int(setting_heatmap_i, 3)
settings.set_int(setting_max_bounce_i, 33)
settings.set_string(setting_mat_white_s, "NoActualMat") # a random non-existent material
settings.set_float_array(setting_ambinet_arr_f, [0.4, 0.5, 0.6])
settings.set_float_array(setting_saturation_arr_f, [0.7, 0.8, 0.9])
# with special flags
# Note: we can't test sync/async settings, since they are needed for the loading stage.
settings.set_bool(setting_mthread_transient_b, False)
settings.set_bool(setting_dir_light_b, True)
settings.set_float_array(setting_place_col_b, [0.4, 0.4, 0.4])
# this was set in [[test]] as transient
settings.set(setting_fog_dist_i, 999)
settings.set_float_array(setting_fog_color_arr_f, [0.21, 0.21, 0.21])
# verify rtx-flags is set as transient in [[test]]
setting_fog_dist_flags = rtx.settings.get_associated_setting_flags_path(setting_fog_dist_i);
setting_fog_color_flags = rtx.settings.get_associated_setting_flags_path(setting_fog_color_arr_f);
value_fog_dist_flags = settings.get(setting_fog_dist_flags)
value_fog_color_flags = settings.get(setting_fog_color_flags)
self.assertEqual(value_fog_dist_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
self.assertEqual(value_fog_color_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
tmp_usd_path = pathlib.Path(tmpdirname) / "tmp_rtx_setting.usd"
result = usd_context.save_as_stage(str(tmp_usd_path))
self.assertTrue(result)
stage = usd_context.get_stage()
# Make stage dirty so reload will work
stage.DefinePrim("/World", "Xform")
await omni.kit.app.get_app().next_update_async()
# Change settings
settings.set_bool(setting_fog_b, False)
settings.set_float(setting_meter_unit_f, 0.3)
settings.set_int(setting_heatmap_i, 2)
settings.set_int(setting_max_bounce_i, 9)
settings.set_string(setting_mat_white_s, "NoActualMat2") # a random non-existent material
settings.set_float_array(setting_ambinet_arr_f, [0.2, 0.2, 0.2])
settings.set_float_array(setting_saturation_arr_f, [0.3, 0.3, 0.3])
# with special flags
settings.set_bool(setting_mthread_transient_b, True)
settings.set_bool(setting_dir_light_b, False)
settings.set_float_array(setting_place_col_b, [0.6, 0.6, 0.6])
await omni.kit.app.get_app().next_update_async()
# Reload stage will reload all the rtx settings
# Reload with native API stage.Reload will not reopen settings
# but only lifecycle API in Kit.
await usd_context.reopen_stage_async()
await omni.kit.app.get_app().next_update_async()
value_fog_b = settings.get(setting_fog_b)
value_meter_unit_f = settings.get(setting_meter_unit_f)
value_heatmap_i = settings.get(setting_heatmap_i)
value_max_bounce_i = settings.get(setting_max_bounce_i)
value_mat_white_s = settings.get(setting_mat_white_s)
value_ambinet_arr_f = settings.get(setting_ambinet_arr_f)
value_saturation_arr_f = settings.get(setting_saturation_arr_f)
# with special flags
value_mthread_transient_b = settings.get(setting_mthread_transient_b)
value_dir_light_b = settings.get(setting_dir_light_b)
value_place_col_b = settings.get(setting_place_col_b)
# Temporarily transient via rtx-flags specified in [[test]]
value_fog_dist_i = settings.get(setting_fog_dist_i)
value_fog_dist_flags = settings.get(setting_fog_dist_flags)
value_fog_color_arr_f = settings.get(setting_fog_color_arr_f)
value_fog_color_flags = settings.get(setting_fog_color_flags)
# New stage to release the temp usd file
await usd_context.new_stage_async()
if must_save:
self.assertEqual(value_fog_b, True)
self.compare_float(value_meter_unit_f, 0.5, self.VALUE_EPSILON)
self.assertEqual(value_heatmap_i, 3)
self.assertEqual(value_max_bounce_i, 33)
self.assertEqual(value_mat_white_s, "NoActualMat")
self.compare_floats(value_ambinet_arr_f, [0.4, 0.5, 0.6], self.VALUE_EPSILON)
self.compare_floats(value_saturation_arr_f, [0.7, 0.8, 0.9], self.VALUE_EPSILON)
else:
self.assertNotEqual(value_fog_b, True)
self.assertNotAlmostEqual(value_meter_unit_f, 0.5, delta=self.VALUE_EPSILON)
self.assertNotEqual(value_heatmap_i, 3)
self.assertNotEqual(value_max_bounce_i, 33)
self.assertNotEqual(value_mat_white_s, "NoActualMat")
# self.compare_floats(value_ambinet_arr_f, [0.4, 0.5, 0.6], self.VALUE_EPSILON)
# self.compare_floats(value_saturation_arr_f, [0.7, 0.8, 0.9], self.VALUE_EPSILON))
# The ones with special flags should NOT be saved or loaded from USD
# same with persistent and rtx-transient
self.assertEqual(value_mthread_transient_b, True)
self.assertEqual(value_dir_light_b, False)
self.compare_floats(value_place_col_b, [0.6, 0.6, 0.6], self.VALUE_EPSILON)
# Temporarily transient via rtx-flags. Should not be saved to or loaded from USD
self.assertEqual(value_fog_dist_i, 999)
self.assertEqual(value_fog_dist_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
self.compare_floats(value_fog_color_arr_f, [0.21, 0.21, 0.21], self.VALUE_EPSILON)
self.assertEqual(value_fog_color_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
async def run_render_settings_loading_helper(self, must_load=True, must_reset=True):
usd_context = omni.usd.get_context()
await omni.kit.app.get_app().next_update_async()
# Custom values already stored in the USD test
setting_tonemap_arr_f = "/rtx/post/tonemap/whitepoint"
setting_sample_threshold_i = "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold"
setting_max_roughness_f = "/rtx/reflections/maxRoughness"
setting_reflections_b = "/rtx/reflections/enabled"
# setting with kSettingFlagTransient, that should not be loaded if saved in the old USD files.
setting_mthread_transient_b = "/rtx/multiThreading/enabled"
setting_mat_syncload_b = "/rtx/materialDb/syncLoads"
setting_hydra_mat_syncload_b = "/rtx/hydra/materialSyncLoads"
# set as transient in [[test]]
setting_fog_dist_i = "/rtx/fog/fogEndDist" # int
setting_fog_color_arr_f = "/rtx/fog/fogColor" # array of float
await omni.kit.app.get_app().next_update_async()
settings.set_float_array(setting_tonemap_arr_f, [0.15, 0.16, 0.17])
settings.set(setting_sample_threshold_i, 43)
# change settings with kSettingFlagTransient
settings.set_bool(setting_mthread_transient_b, True)
settings.set_bool(setting_mat_syncload_b, True)
settings.set_bool(setting_hydra_mat_syncload_b, False)
# this was set in [[test]] as transient and not saved in USD.
settings.set(setting_fog_dist_i, 999)
settings.set_float_array(setting_fog_color_arr_f, [0.21, 0.21, 0.21])
await omni.kit.app.get_app().next_update_async()
self.open_usd("cubeRtxSettings.usda")
await wait_for_update()
value_tonemap_arr_f = settings.get(setting_tonemap_arr_f)
value_sample_threshold_i = settings.get(setting_sample_threshold_i)
value_max_roughness_f = settings.get(setting_max_roughness_f)
value_reflections_b = settings.get(setting_reflections_b)
value_mthread_transient_b = settings.get(setting_mthread_transient_b)
value_mat_syncload_b = settings.get(setting_mat_syncload_b)
value_hydra_mat_syncload_b = settings.get(setting_hydra_mat_syncload_b)
# Not stored in USD file, testing the default value
value_fog_dist_i = settings.get(setting_fog_dist_i)
value_fog_color_arr_f = settings.get(setting_fog_color_arr_f)
if must_load:
# Must match to what we stored in USD
self.compare_floats(value_tonemap_arr_f, [0.1, 0.2, 0.3], self.VALUE_EPSILON)
self.assertEqual(value_sample_threshold_i, 77)
self.compare_float(value_max_roughness_f, 0.53, self.VALUE_EPSILON)
self.assertEqual(value_reflections_b, False)
else:
if must_reset:
# Current default values set in C++ code.
self.compare_floats(value_tonemap_arr_f, [1.0, 1.0, 1.0], self.VALUE_EPSILON)
self.assertEqual(value_sample_threshold_i, 10)
else:
# what we set before loading the USD and not defaults.
self.compare_floats(value_tonemap_arr_f, [0.15, 0.16, 0.17], self.VALUE_EPSILON)
self.assertEqual(value_sample_threshold_i, 43)
self.assertNotAlmostEqual(value_max_roughness_f, 0.53, delta=self.VALUE_EPSILON)
self.assertNotEqual(value_reflections_b, False)
# Must skip loading setting that use kSettingFlagTransient flag from USD
# Such settings are not saved or loaded in USD, ut may exist in old USD files, such as cubeRtxSettings.usda.
# if usd was re-saved, you need to manually add those transient setting for this test. Otherwise, they will be removed.
self.assertEqual(value_mthread_transient_b, True)
self.assertEqual(value_mat_syncload_b, True)
self.assertEqual(value_hydra_mat_syncload_b, False)
# Temporarily transient via rtx-flags. Should not be saved to or loaded from USD
self.assertEqual(value_fog_dist_i, 999)
self.compare_floats(value_fog_color_arr_f, [0.21, 0.21, 0.21], self.VALUE_EPSILON)
async def test_render_settings_storage(self):
await self.run_render_settings_storage_helper(must_save=True)
async def test_render_settings_not_storing(self):
# Test to make sure rtx settings are not stored in USD, when asked.
storeRenderSettingsToStage = "/app/omni.usd/storeRenderSettingsToUsdStage";
settings.set_bool(storeRenderSettingsToStage, False)
await self.run_render_settings_storage_helper(must_save=False)
settings.set_bool(storeRenderSettingsToStage, True)
async def test_render_settings_loading(self):
await self.run_render_settings_loading_helper()
async def test_render_settings_not_loading(self):
# Test to make sure rtx settings are not loaded from USD, when asked.
loadRenderSettingsFromStage = "/app/omni.usd/loadRenderSettingsFromUsdStage";
settings.set_bool(loadRenderSettingsFromStage, False)
await self.run_render_settings_loading_helper(must_load=False)
settings.set_bool(loadRenderSettingsFromStage, True)
async def test_render_settings_not_loading_not_reset(self):
# Test to make sure rtx settings are not loaded from USD, when asked.
loadRenderSettingsFromStage = "/app/omni.usd/loadRenderSettingsFromUsdStage";
resetRenderSettingsStage = "/app/omni.usd/resetRenderSettingsInUsdStage";
settings.set_bool(loadRenderSettingsFromStage, False)
settings.set_bool(resetRenderSettingsStage, False)
await self.run_render_settings_loading_helper(must_load=False, must_reset=False)
settings.set_bool(loadRenderSettingsFromStage, True)
settings.set_bool(resetRenderSettingsStage, True)
| 20,535 | Python | 48.484337 | 127 | 0.645142 |
omniverse-code/kit/exts/omni.usd_resolver/omni/usd_resolver/__init__.py | import os
from typing import Tuple, List, Callable
if hasattr(os, "add_dll_directory"):
scriptdir = os.path.dirname(os.path.realpath(__file__))
dlldir = os.path.abspath(os.path.join(scriptdir, "../../.."))
with os.add_dll_directory(dlldir):
from ._omni_usd_resolver import *
else:
from ._omni_usd_resolver import *
| 341 | Python | 27.499998 | 65 | 0.662757 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/__init__.py | """Action Graph Functionality"""
# Required to be able to instantiate the object types
import omni.core
from ._impl.extension import _PublicExtension # noqa: F401
# Interface from the ABI bindings
from ._omni_graph_action import get_interface
| 247 | Python | 23.799998 | 59 | 0.773279 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnGateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Gate
This node controls a flow of execution based on the state of its gate. The gate can be opened or closed by execution pulses
sent to the gate controls
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnGateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Gate
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.enter
inputs.startClosed
inputs.toggle
Outputs:
outputs.exit
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:enter', 'execution', 0, 'Enter', 'Incoming execution flow controlled by the gate', {}, True, None, False, ''),
('inputs:startClosed', 'bool', 0, 'Start Closed', 'If true the gate will start in a closed state', {}, True, False, False, ''),
('inputs:toggle', 'execution', 0, 'Toggle', 'The gate is opened or closed', {}, True, None, False, ''),
('outputs:exit', 'execution', 0, 'Exit', 'The enter pulses will be passed to this output if the gate is open', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.enter = og.AttributeRole.EXECUTION
role_data.inputs.toggle = og.AttributeRole.EXECUTION
role_data.outputs.exit = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def enter(self):
data_view = og.AttributeValueHelper(self._attributes.enter)
return data_view.get()
@enter.setter
def enter(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.enter)
data_view = og.AttributeValueHelper(self._attributes.enter)
data_view.set(value)
@property
def startClosed(self):
data_view = og.AttributeValueHelper(self._attributes.startClosed)
return data_view.get()
@startClosed.setter
def startClosed(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.startClosed)
data_view = og.AttributeValueHelper(self._attributes.startClosed)
data_view.set(value)
@property
def toggle(self):
data_view = og.AttributeValueHelper(self._attributes.toggle)
return data_view.get()
@toggle.setter
def toggle(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.toggle)
data_view = og.AttributeValueHelper(self._attributes.toggle)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def exit(self):
data_view = og.AttributeValueHelper(self._attributes.exit)
return data_view.get()
@exit.setter
def exit(self, value):
data_view = og.AttributeValueHelper(self._attributes.exit)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnGateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnGateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnGateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,666 | Python | 44.047297 | 146 | 0.655716 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnBranchDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Branch
Outputs an execution pulse along a branch based on a boolean condition
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnBranchDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Branch
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.condition
inputs.execIn
Outputs:
outputs.execFalse
outputs.execTrue
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:condition', 'bool', 0, 'Condition', 'The boolean condition which determines the output direction', {}, True, False, False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('outputs:execFalse', 'execution', 0, 'False', 'The output path when condition is False', {}, True, None, False, ''),
('outputs:execTrue', 'execution', 0, 'True', 'The output path when condition is True', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execFalse = og.AttributeRole.EXECUTION
role_data.outputs.execTrue = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def condition(self):
data_view = og.AttributeValueHelper(self._attributes.condition)
return data_view.get()
@condition.setter
def condition(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.condition)
data_view = og.AttributeValueHelper(self._attributes.condition)
data_view.set(value)
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execFalse(self):
data_view = og.AttributeValueHelper(self._attributes.execFalse)
return data_view.get()
@execFalse.setter
def execFalse(self, value):
data_view = og.AttributeValueHelper(self._attributes.execFalse)
data_view.set(value)
@property
def execTrue(self):
data_view = og.AttributeValueHelper(self._attributes.execTrue)
return data_view.get()
@execTrue.setter
def execTrue(self, value):
data_view = og.AttributeValueHelper(self._attributes.execTrue)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnBranchDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnBranchDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnBranchDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,509 | Python | 43.896551 | 144 | 0.659087 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnMouseInputDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnMouseInput
Event node which fires when a mouse event occurs.
You can choose which mouse element this node reacts to. When mouse element
is chosen to be a button, the only meaningful outputs are: outputs:pressed, outputs:released and outputs:isPressed. When
scroll or move events are chosen, the only meaningful outputs are: outputs:valueChanged and outputs:value. You can choose
to output normalized or pixel coordinates of the mouse.
Pixel coordinates are the absolute position of the mouse cursor
in pixel unit. The original point is the upper left corner. The minimum value is 0, and the maximum value depends on the
size of the window.
Normalized coordinates are the relative position of the mouse cursor to the window. The value is always
between 0 and 1.
"""
import numpy
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnMouseInputDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnMouseInput
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.mouseElement
inputs.onlyPlayback
Outputs:
outputs.isPressed
outputs.pressed
outputs.released
outputs.value
outputs.valueChanged
Predefined Tokens:
tokens.LeftButton
tokens.MiddleButton
tokens.RightButton
tokens.NormalizedMove
tokens.PixelMove
tokens.Scroll
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:mouseElement', 'token', 0, 'Mouse Element', 'The event to trigger the downstream execution ', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Button,Middle Button,Right Button,Normalized Move,Pixel Move,Scroll', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftButton": "Left Button", "MiddleButton": "Middle Button", "RightButton": "Right Button", "NormalizedMove": "Normalized Move", "PixelMove": "Pixel Move", "Scroll": "Scroll"}', ogn.MetadataKeys.DEFAULT: '"Left Button"'}, True, "Left Button", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:isPressed', 'bool', 0, None, 'True if the mouse button was pressed, False if it was released or mouse element is not related to a button', {}, True, None, False, ''),
('outputs:pressed', 'execution', 0, 'Pressed', 'Executes when mouse button was pressed. Will not execute on move or scroll events', {}, True, None, False, ''),
('outputs:released', 'execution', 0, 'Released', 'Executes when mouse button was released. Will not execute on move or scroll events', {}, True, None, False, ''),
('outputs:value', 'float2', 0, 'Delta Value', 'The meaning of this output depends on Event In.\nNormalized Move: will output the normalized coordinates of mouse, each element of the vector is in the range of [0, 1]\nPixel Move: will output the absolute coordinates of mouse, each vector is in the range of [0, pixel width/height of the window]\nScroll: will output the change of scroll value\nOtherwise: will output [0,0]', {}, True, None, False, ''),
('outputs:valueChanged', 'execution', 0, 'Moved', 'Executes when user moves the cursor or scrolls the cursor. Will not execute on button events', {}, True, None, False, ''),
])
class tokens:
LeftButton = "Left Button"
MiddleButton = "Middle Button"
RightButton = "Right Button"
NormalizedMove = "Normalized Move"
PixelMove = "Pixel Move"
Scroll = "Scroll"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.pressed = og.AttributeRole.EXECUTION
role_data.outputs.released = og.AttributeRole.EXECUTION
role_data.outputs.valueChanged = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def mouseElement(self):
data_view = og.AttributeValueHelper(self._attributes.mouseElement)
return data_view.get()
@mouseElement.setter
def mouseElement(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.mouseElement)
data_view = og.AttributeValueHelper(self._attributes.mouseElement)
data_view.set(value)
@property
def onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def isPressed(self):
data_view = og.AttributeValueHelper(self._attributes.isPressed)
return data_view.get()
@isPressed.setter
def isPressed(self, value):
data_view = og.AttributeValueHelper(self._attributes.isPressed)
data_view.set(value)
@property
def pressed(self):
data_view = og.AttributeValueHelper(self._attributes.pressed)
return data_view.get()
@pressed.setter
def pressed(self, value):
data_view = og.AttributeValueHelper(self._attributes.pressed)
data_view.set(value)
@property
def released(self):
data_view = og.AttributeValueHelper(self._attributes.released)
return data_view.get()
@released.setter
def released(self, value):
data_view = og.AttributeValueHelper(self._attributes.released)
data_view.set(value)
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
@property
def valueChanged(self):
data_view = og.AttributeValueHelper(self._attributes.valueChanged)
return data_view.get()
@valueChanged.setter
def valueChanged(self, value):
data_view = og.AttributeValueHelper(self._attributes.valueChanged)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnOnMouseInputDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnMouseInputDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnMouseInputDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,267 | Python | 48.84466 | 581 | 0.67264 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnImpulseEventDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnImpulseEvent
Triggers the output execution once when state is set
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnImpulseEventDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnImpulseEvent
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.onlyPlayback
Outputs:
outputs.execOut
State:
state.enableImpulse
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:execOut', 'execution', 0, 'Trigger', 'The execution output', {}, True, None, False, ''),
('state:enableImpulse', 'bool', 0, None, 'When true, execute output once and reset to false', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
@property
def enableImpulse(self):
data_view = og.AttributeValueHelper(self._attributes.enableImpulse)
return data_view.get()
@enableImpulse.setter
def enableImpulse(self, value):
data_view = og.AttributeValueHelper(self._attributes.enableImpulse)
data_view.set(value)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnOnImpulseEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnImpulseEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnImpulseEventDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,990 | Python | 45.44186 | 232 | 0.669282 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnStageEventDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnStageEvent
Executes when the specified Stage Event occurs. Stage Events are emitted when certain USD stage-related actions are performed
by the system:
Saved: USD file saved.
Selection Changed: USD Prim selection has changed.
Hierarchy Changed: USD stage
hierarchy has changed, e.g. a prim is added, deleted or moved.
OmniGraph Start Play: OmniGraph started
OmniGraph Stop Play:
OmniGraph stopped
Simulation Start Play: Simulation started
Simulation Stop Play: Simulation stopped
Animation Start Play:
Animation playback has started
Animation Stop Play: Animation playback has stopped
"""
import sys
import traceback
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnStageEventDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnStageEvent
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.eventName
inputs.onlyPlayback
Outputs:
outputs.execOut
Predefined Tokens:
tokens.Saved
tokens.SelectionChanged
tokens.HierarchyChanged
tokens.OmniGraphStart
tokens.OmniGraphStop
tokens.SimulationStart
tokens.SimulationStop
tokens.AnimationStart
tokens.AnimationStop
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:eventName', 'token', 0, None, 'The event of interest', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Saved,Selection Changed,Hierarchy Changed,OmniGraph Start Play,OmniGraph Stop Play,Simulation Start Play,Simulation Stop Play,Animation Start Play,Animation Stop Play', 'default': 'Animation Start Play', 'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"Saved": "Saved", "SelectionChanged": "Selection Changed", "HierarchyChanged": "Hierarchy Changed", "OmniGraphStart": "OmniGraph Start Play", "OmniGraphStop": "OmniGraph Stop Play", "SimulationStart": "Simulation Start Play", "SimulationStop": "Simulation Stop Play", "AnimationStart": "Animation Start Play", "AnimationStop": "Animation Stop Play"}'}, True, "", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:execOut', 'execution', 0, None, 'The execution output', {}, True, None, False, ''),
])
class tokens:
Saved = "Saved"
SelectionChanged = "Selection Changed"
HierarchyChanged = "Hierarchy Changed"
OmniGraphStart = "OmniGraph Start Play"
OmniGraphStop = "OmniGraph Stop Play"
SimulationStart = "Simulation Start Play"
SimulationStop = "Simulation Stop Play"
AnimationStart = "Animation Start Play"
AnimationStop = "Animation Stop Play"
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"eventName", "onlyPlayback", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.eventName, self._attributes.onlyPlayback]
self._batchedReadValues = ["", True]
@property
def eventName(self):
return self._batchedReadValues[0]
@eventName.setter
def eventName(self, value):
self._batchedReadValues[0] = value
@property
def onlyPlayback(self):
return self._batchedReadValues[1]
@onlyPlayback.setter
def onlyPlayback(self, value):
self._batchedReadValues[1] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def execOut(self):
value = self._batchedWriteValues.get(self._attributes.execOut)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
self._batchedWriteValues[self._attributes.execOut] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnOnStageEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnStageEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnStageEventDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
class abi:
"""Class defining the ABI interface for the node type"""
@staticmethod
def get_node_type():
get_node_type_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.action.OnStageEvent'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnOnStageEventDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnOnStageEventDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnOnStageEventDatabase(node)
try:
compute_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'compute', None)
if callable(compute_function) and compute_function.__code__.co_argcount > 1:
return compute_function(context, node)
db.inputs._prefetch()
db.inputs._setting_locked = True
with og.in_compute():
return OgnOnStageEventDatabase.NODE_TYPE_CLASS.compute(db)
except Exception as error:
stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
finally:
db.inputs._setting_locked = False
db.outputs._commit()
return False
@staticmethod
def initialize(context, node):
OgnOnStageEventDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnOnStageEventDatabase.PER_NODE_DATA[node.node_id()]
def on_connection_or_disconnection(*args):
per_node_data['_db'] = None
node.register_on_connected_callback(on_connection_or_disconnection)
node.register_on_disconnected_callback(on_connection_or_disconnection)
@staticmethod
def release(node):
release_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnOnStageEventDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnOnStageEventDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
if callable(update_node_version_function):
return update_node_version_function(context, node, old_version, new_version)
return False
@staticmethod
def initialize_type(node_type):
initialize_type_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
needs_initializing = True
if callable(initialize_type_function):
needs_initializing = initialize_type_function(node_type)
if needs_initializing:
node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.action")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On Stage Event")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Executes when the specified Stage Event occurs. Stage Events are emitted when certain USD stage-related actions are performed by the system:\n Saved: USD file saved.\n Selection Changed: USD Prim selection has changed.\n Hierarchy Changed: USD stage hierarchy has changed, e.g. a prim is added, deleted or moved.\n OmniGraph Start Play: OmniGraph started\n OmniGraph Stop Play: OmniGraph stopped\n Simulation Start Play: Simulation started\n Simulation Stop Play: Simulation stopped\n Animation Start Play: Animation playback has started\n Animation Stop Play: Animation playback has stopped")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
__hints = node_type.get_scheduling_hints()
if __hints is not None:
__hints.compute_rule = og.eComputeRule.E_ON_REQUEST
OgnOnStageEventDatabase.INTERFACE.add_to_node_type(node_type)
node_type.set_has_state(True)
@staticmethod
def on_connection_type_resolve(node):
on_connection_type_resolve_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
if callable(on_connection_type_resolve_function):
on_connection_type_resolve_function(node)
NODE_TYPE_CLASS = None
@staticmethod
def register(node_type_class):
OgnOnStageEventDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnOnStageEventDatabase.abi, 3)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.action.OnStageEvent")
| 14,352 | Python | 47.489865 | 790 | 0.651965 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnForEachDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.ForEach
Executes the a loop body once for each element in the input array. The finished output is executed after all iterations are
complete
"""
from typing import Any
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnForEachDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.ForEach
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.arrayIn
inputs.execIn
Outputs:
outputs.arrayIndex
outputs.element
outputs.finished
outputs.loopBody
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:arrayIn', 'bool[],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],double[2][],double[3][],double[4][],double[],float[2][],float[3][],float[4][],float[],frame[4][],half[2][],half[3][],half[4][],half[],int64[],int[2][],int[3][],int[4][],int[],matrixd[3][],matrixd[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],quatd[4][],quatf[4][],quath[4][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],timecode[],token[],transform[4][],uchar[],uint64[],uint[],vectord[3][],vectorf[3][],vectorh[3][]', 1, 'Input Array', 'The array to loop over', {}, True, None, False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('outputs:arrayIndex', 'int', 0, None, 'The current or last index visited', {}, True, None, False, ''),
('outputs:element', 'bool,colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'The current or last element of the array visited', {}, True, None, False, ''),
('outputs:finished', 'execution', 0, None, 'Executed when the loop is finished', {}, True, None, False, ''),
('outputs:loopBody', 'execution', 0, None, 'Executed for each element of the array', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.finished = og.AttributeRole.EXECUTION
role_data.outputs.loopBody = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def arrayIn(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.arrayIn"""
return og.RuntimeAttribute(self._attributes.arrayIn.get_attribute_data(), self._context, True)
@arrayIn.setter
def arrayIn(self, value_to_set: Any):
"""Assign another attribute's value to outputs.arrayIn"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.arrayIn.value = value_to_set.value
else:
self.arrayIn.value = value_to_set
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def arrayIndex(self):
data_view = og.AttributeValueHelper(self._attributes.arrayIndex)
return data_view.get()
@arrayIndex.setter
def arrayIndex(self, value):
data_view = og.AttributeValueHelper(self._attributes.arrayIndex)
data_view.set(value)
@property
def element(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.element"""
return og.RuntimeAttribute(self._attributes.element.get_attribute_data(), self._context, False)
@element.setter
def element(self, value_to_set: Any):
"""Assign another attribute's value to outputs.element"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.element.value = value_to_set.value
else:
self.element.value = value_to_set
@property
def finished(self):
data_view = og.AttributeValueHelper(self._attributes.finished)
return data_view.get()
@finished.setter
def finished(self, value):
data_view = og.AttributeValueHelper(self._attributes.finished)
data_view.set(value)
@property
def loopBody(self):
data_view = og.AttributeValueHelper(self._attributes.loopBody)
return data_view.get()
@loopBody.setter
def loopBody(self, value):
data_view = og.AttributeValueHelper(self._attributes.loopBody)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnForEachDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnForEachDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnForEachDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,947 | Python | 50.131428 | 676 | 0.65005 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.